tply.doc 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. TP Lex and Yacc - The Compiler Writer's Tools for Turbo Pascal
  2. == === === ==== = === ======== ======== ===== === ===== ======
  3. Version 4.1 User Manual
  4. ======= === ==== ======
  5. Albert Graef
  6. Department of Musicinformatics
  7. Johannes Gutenberg-University Mainz
  8. [email protected]
  9. April 1998
  10. Introduction
  11. ============
  12. This document describes the TP Lex and Yacc compiler generator toolset. These
  13. tools are designed especially to help you prepare compilers and similar
  14. programs like text processing utilities and command language interpreters with
  15. the Turbo Pascal (TM) programming language.
  16. TP Lex and Yacc are Turbo Pascal adaptions of the well-known UNIX (TM)
  17. utilities Lex and Yacc, which were written by M.E. Lesk and S.C. Johnson at
  18. Bell Laboratories, and are used with the C programming language. TP Lex and
  19. Yacc are intended to be approximately "compatible" with these programs.
  20. However, they are an independent development of the author, based on the
  21. techniques described in the famous "dragon book" of Aho, Sethi and Ullman
  22. (Aho, Sethi, Ullman: "Compilers : principles, techniques and tools," Reading
  23. (Mass.), Addison-Wesley, 1986).
  24. Version 4.1 of TP Lex and Yacc works with all recent flavours of Turbo/Borland
  25. Pascal, including Delphi, and with the Free Pascal Compiler, a free Turbo
  26. Pascal-compatible compiler which currently runs on DOS and Linux (other ports
  27. are under development). Recent information about TP Lex/Yacc, and the sources
  28. are available from the TPLY homepage:
  29. http://www.musikwissenschaft.uni-mainz.de/~ag/tply
  30. For information about the Free Pascal Compiler, please refer to:
  31. http://www.freepascal.org
  32. TP Lex and Yacc, like any other tools of this kind, are not intended for
  33. novices or casual programmers; they require extensive programming experience
  34. as well as a thorough understanding of the principles of parser design and
  35. implementation to be put to work successfully. But if you are a seasoned Turbo
  36. Pascal programmer with some background in compiler design and formal language
  37. theory, you will almost certainly find TP Lex and Yacc to be a powerful
  38. extension of your Turbo Pascal toolset.
  39. This manual tells you how to get started with the TP Lex and Yacc programs and
  40. provides a short description of these programs. Some knowledge about the C
  41. versions of Lex and Yacc will be useful, although not strictly necessary. For
  42. further reading, you may also refer to:
  43. - Aho, Sethi and Ullman: "Compilers : principles, techniques and tools."
  44. Reading (Mass.), Addison-Wesley, 1986.
  45. - Johnson, S.C.: "Yacc - yet another compiler-compiler." CSTR-32, Bell
  46. Telephone Laboratories, 1974.
  47. - Lesk, M.E.: "Lex - a lexical analyser generator." CSTR-39, Bell Telephone
  48. Laboratories, 1975.
  49. - Schreiner, Friedman: "Introduction to compiler construction with UNIX."
  50. Prentice-Hall, 1985.
  51. - The Unix Programmer's Manual, Sections `Lex' and `Yacc'.
  52. Credits
  53. -------
  54. I would like to thank Berend de Boer ([email protected]), who adapted TP Lex
  55. and Yacc to take advantage of the large memory models in Borland Pascal 7.0
  56. and Delphi, and Michael Van Canneyt ([email protected]),
  57. the maintainer of the Linux version of the Free Pascal compiler, who is
  58. responsible for the Free Pascal port. And of course thanks are due to the many
  59. TP Lex/Yacc users all over the world for their support and comments which
  60. helped to improve these programs.
  61. Getting Started
  62. ---------------
  63. Instructions on how to compile and install TP Lex and Yacc on all supported
  64. platforms can be found in the README file contained in the distribution.
  65. Once you have installed TP Lex and Yacc on your system, you can compile your
  66. first TP Lex and Yacc program expr. Expr is a simple desktop calculator
  67. program contained in the distribution, which consists of a lexical analyzer in
  68. the TP Lex source file exprlex.l and the parser and main program in the TP
  69. Yacc source file expr.y. To compile these programs, issue the commands
  70. lex exprlex
  71. yacc expr
  72. That's it! You now have the Turbo Pascal sources (exprlex.pas and expr.pas)
  73. for the expr program. Use the Turbo Pascal compiler to compile these programs
  74. as usual:
  75. tpc expr
  76. (Of course, the precise compilation command depends on the type of compiler
  77. you are using. Thus you may have to replace tpc with bpc, dcc or dcc32,
  78. depending on the version of the Turbo/Borland/Delphi compiler you have, and
  79. with ppc386 for the Free Pascal compiler. If you are using TP Lex and Yacc
  80. with Free Pascal under Linux, the corresponding commands are:
  81. plex exprlex
  82. pyacc expr
  83. ppc386 expr
  84. Note that in the Linux version, the programs are named plex and pyacc to
  85. avoid name clashes with the corresponding UNIX utilities.)
  86. Having compiled expr.pas, you can execute the expr program and type some
  87. expressions to see it work (terminate the program with an empty line). There
  88. is a number of other sample TP Lex and Yacc programs (.l and .y files) in the
  89. distribution, including a TP Yacc cross reference utility and a complete
  90. parser for Standard Pascal.
  91. The TP Lex and Yacc programs recognize some options which may be specified
  92. anywhere on the command line. E.g.,
  93. lex -o exprlex
  94. runs TP Lex with "DFA optimization" and
  95. yacc -v expr
  96. runs TP Yacc in "verbose" mode (TP Yacc generates a readable description of
  97. the generated parser).
  98. The TP Lex and Yacc programs use the following default filename extensions:
  99. - .l: TP Lex input files
  100. - .y: TP Yacc input files
  101. - .pas: TP Lex and Yacc output files
  102. As usual, you may overwrite default filename extensions by explicitly
  103. specifying suffixes.
  104. If you ever forget how to run TP Lex and Yacc, you can issue the command lex
  105. or yacc (resp. plex or pyacc) without arguments to get a short summary of the
  106. command line syntax.
  107. TP Lex
  108. ======
  109. This section describes the TP Lex lexical analyzer generator.
  110. Usage
  111. -----
  112. lex [options] lex-file[.l] [output-file[.pas]]
  113. Options
  114. -------
  115. -v "Verbose:" Lex generates a readable description of the generated
  116. lexical analyzer, written to lex-file with new extension `.lst'.
  117. -o "Optimize:" Lex optimizes DFA tables to produce a minimal DFA.
  118. Description
  119. -----------
  120. TP Lex is a program generator that is used to generate the Turbo Pascal source
  121. code for a lexical analyzer subroutine from the specification of an input
  122. language by a regular expression grammar.
  123. TP Lex parses the source grammar contained in lex-file (with default suffix
  124. .l) and writes the constructed lexical analyzer subroutine to the specified
  125. output-file (with default suffix .pas); if no output file is specified, output
  126. goes to lex-file with new suffix .pas. If any errors are found during
  127. compilation, error messages are written to the list file (lex-file with new
  128. suffix .lst).
  129. The generated output file contains a lexical analyzer routine, yylex,
  130. implemented as:
  131. function yylex : Integer;
  132. This routine has to be called by your main program to execute the lexical
  133. analyzer. The return value of the yylex routine usually denotes the number
  134. of a token recognized by the lexical analyzer (see the return routine in the
  135. LexLib unit). At end-of-file the yylex routine normally returns 0.
  136. The code template for the yylex routine may be found in the yylex.cod
  137. file. This file is needed by TP Lex when it constructs the output file. It
  138. must be present either in the current directory or in the directory from which
  139. TP Lex was executed (TP Lex searches these directories in the indicated
  140. order). (NB: For the Linux/Free Pascal version, the code template is searched
  141. in some directory defined at compile-time instead of the execution path,
  142. usually /usr/lib/fpc/lexyacc.)
  143. The TP Lex library (LexLib) unit is required by programs using Lex-generated
  144. lexical analyzers; you will therefore have to put an appropriate uses clause
  145. into your program or unit that contains the lexical analyzer routine. The
  146. LexLib unit also provides various useful utility routines; see the file
  147. lexlib.pas for further information.
  148. Lex Source
  149. ----------
  150. A TP Lex program consists of three sections separated with the %% delimiter:
  151. definitions
  152. %%
  153. rules
  154. %%
  155. auxiliary procedures
  156. All sections may be empty. The TP Lex language is line-oriented; definitions
  157. and rules are separated by line breaks. There is no special notation for
  158. comments, but (Turbo Pascal style) comments may be included as Turbo Pascal
  159. fragments (see below).
  160. The definitions section may contain the following elements:
  161. - regular definitions in the format:
  162. name substitution
  163. which serve to abbreviate common subexpressions. The {name} notation
  164. causes the corresponding substitution from the definitions section to
  165. be inserted into a regular expression. The name must be a legal
  166. identifier (letter followed by a sequence of letters and digits;
  167. the underscore counts as a letter; upper- and lowercase are distinct).
  168. Regular definitions must be non-recursive.
  169. - start state definitions in the format:
  170. %start name ...
  171. which are used in specifying start conditions on rules (described
  172. below). The %start keyword may also be abbreviated as %s or %S.
  173. - Turbo Pascal declarations enclosed between %{ and %}. These will be
  174. inserted into the output file (at global scope). Also, any line that
  175. does not look like a Lex definition (e.g., starts with blank or tab)
  176. will be treated as Turbo Pascal code. (In particular, this also allows
  177. you to include Turbo Pascal comments in your Lex program.)
  178. The rules section of a TP Lex program contains the actual specification of
  179. the lexical analyzer routine. It may be thought of as a big CASE statement
  180. discriminating over the different patterns to be matched and listing the
  181. corresponding statements (actions) to be executed. Each rule consists of a
  182. regular expression describing the strings to be matched in the input, and a
  183. corresponding action, a Turbo Pascal statement to be executed when the
  184. expression matches. Expression and statement are delimited with whitespace
  185. (blanks and/or tabs). Thus the format of a Lex grammar rule is:
  186. expression statement;
  187. Note that the action must be a single Turbo Pascal statement terminated
  188. with a semicolon (use begin ... end for compound statements). The statement
  189. may span multiple lines if the successor lines are indented with at least
  190. one blank or tab. The action may also be replaced by the | character,
  191. indicating that the action for this rule is the same as that for the next
  192. one.
  193. The TP Lex library unit provides various variables and routines which are
  194. useful in the programming of actions. In particular, the yytext string
  195. variable holds the text of the matched string, and the yyleng Byte variable
  196. its length.
  197. Regular expressions are used to describe the strings to be matched in a
  198. grammar rule. They are built from the usual constructs describing character
  199. classes and sequences, and operators specifying repetitions and alternatives.
  200. The precise format of regular expressions is described in the next section.
  201. The rules section may also start with some Turbo Pascal declarations
  202. (enclosed in %{ %}) which are treated as local declarations of the
  203. actions routine.
  204. Finally, the auxiliary procedures section may contain arbitrary Turbo
  205. Pascal code (such as supporting routines or a main program) which is
  206. simply tacked on to the end of the output file. The auxiliary procedures
  207. section is optional.
  208. Regular Expressions
  209. -------------------
  210. The following table summarizes the format of the regular expressions
  211. recognized by TP Lex (also compare Aho, Sethi, Ullman 1986, fig. 3.48).
  212. c stands for a single character, s for a string, r for a regular expression,
  213. and n,m for nonnegative integers.
  214. expression matches example
  215. ---------- ---------------------------- -------
  216. c any non-operator character c a
  217. \c character c literally \*
  218. "s" string s literally "**"
  219. . any character but newline a.*b
  220. ^ beginning of line ^abc
  221. $ end of line abc$
  222. [s] any character in s [abc]
  223. [^s] any character not in s [^abc]
  224. r* zero or more r's a*
  225. r+ one or more r's a+
  226. r? zero or one r a?
  227. r{m,n} m to n occurrences of r a{1,5}
  228. r{m} m occurrences of r a{5}
  229. r1r2 r1 then r2 ab
  230. r1|r2 r1 or r2 a|b
  231. (r) r (a|b)
  232. r1/r2 r1 when followed by r2 a/b
  233. <x>r r when in start condition x <x>abc
  234. ---------------------------------------------------
  235. The operators *, +, ? and {} have highest precedence, followed by
  236. concatenation. The | operator has lowest precedence. Parentheses ()
  237. may be used to group expressions and overwrite default precedences.
  238. The <> and / operators may only occur once in an expression.
  239. The usual C-like escapes are recognized:
  240. \n denotes newline
  241. \r denotes carriage return
  242. \t denotes tab
  243. \b denotes backspace
  244. \f denotes form feed
  245. \NNN denotes character no. NNN in octal base
  246. You can also use the \ character to quote characters which would otherwise
  247. be interpreted as operator symbols. In character classes, you may use
  248. the - character to denote ranges of characters. For instance, [a-z]
  249. denotes the class of all lowercase letters.
  250. The expressions in a TP Lex program may be ambigious, i.e. there may be inputs
  251. which match more than one rule. In such a case, the lexical analyzer prefers
  252. the longest match and, if it still has the choice between different rules,
  253. it picks the first of these. If no rule matches, the lexical analyzer
  254. executes a default action which consists of copying the input character
  255. to the output unchanged. Thus, if the purpose of a lexical analyzer is
  256. to translate some parts of the input, and leave the rest unchanged, you
  257. only have to specify the patterns which have to be treated specially. If,
  258. however, the lexical analyzer has to absorb its whole input, you will have
  259. to provide rules that match everything. E.g., you might use the rules
  260. . |
  261. \n ;
  262. which match "any other character" (and ignore it).
  263. Sometimes certain patterns have to be analyzed differently depending on some
  264. amount of context in which the pattern appears. In such a case the / operator
  265. is useful. For instance, the expression a/b matches a, but only if followed
  266. by b. Note that the b does not belong to the match; rather, the lexical
  267. analyzer, when matching an a, will look ahead in the input to see whether
  268. it is followed by a b, before it declares that it has matched an a. Such
  269. lookahead may be arbitrarily complex (up to the size of the LexLib input
  270. buffer). E.g., the pattern a/.*b matches an a which is followed by a b
  271. somewhere on the same input line. TP Lex also has a means to specify left
  272. context which is described in the next section.
  273. Start Conditions
  274. ----------------
  275. TP Lex provides some features which make it possible to handle left context.
  276. The ^ character at the beginning of a regular expression may be used to
  277. denote the beginning of the line. More distant left context can be described
  278. conveniently by using start conditions on rules.
  279. Any rule which is prefixed with the <> construct is only valid if the lexical
  280. analyzer is in the denoted start state. For instance, the expression <x>a
  281. can only be matched if the lexical analyzer is in start state x. You can have
  282. multiple start states in a rule; e.g., <x,y>a can be matched in start states
  283. x or y.
  284. Start states have to be declared in the definitions section by means of
  285. one or more start state definitions (see above). The lexical analyzer enters
  286. a start state through a call to the LexLib routine start. E.g., you may
  287. write:
  288. %start x y
  289. %%
  290. <x>a start(y);
  291. <y>b start(x);
  292. %%
  293. begin
  294. start(x); if yylex=0 then ;
  295. end.
  296. Upon initialization, the lexical analyzer is put into state x. It then
  297. proceeds in state x until it matches an a which puts it into state y.
  298. In state y it may match a b which puts it into state x again, etc.
  299. Start conditions are useful when certain constructs have to be analyzed
  300. differently depending on some left context (such as a special character
  301. at the beginning of the line), and if multiple lexical analyzers have to
  302. work in concert. If a rule is not prefixed with a start condition, it is
  303. valid in all user-defined start states, as well as in the lexical analyzer's
  304. default start state.
  305. Lex Library
  306. -----------
  307. The TP Lex library (LexLib) unit provides various variables and routines
  308. which are used by Lex-generated lexical analyzers and application programs.
  309. It provides the input and output streams and other internal data structures
  310. used by the lexical analyzer routine, and supplies some variables and utility
  311. routines which may be used by actions and application programs. Refer to
  312. the file lexlib.pas for a closer description.
  313. You can also modify the Lex library unit (and/or the code template in the
  314. yylex.cod file) to customize TP Lex to your target applications. E.g.,
  315. you might wish to optimize the code of the lexical analyzer for some
  316. special application, make the analyzer read from/write to memory instead
  317. of files, etc.
  318. Implementation Restrictions
  319. ---------------------------
  320. Internal table sizes and the main memory available limit the complexity of
  321. source grammars that TP Lex can handle. There is currently no possibility to
  322. change internal table sizes (apart from modifying the sources of TP Lex
  323. itself), but the maximum table sizes provided by TP Lex seem to be large
  324. enough to handle most realistic applications. The actual table sizes depend on
  325. the particular implementation (they are much larger than the defaults if TP
  326. Lex has been compiled with one of the 32 bit compilers such as Delphi 2 or
  327. Free Pascal), and are shown in the statistics printed by TP Lex when a
  328. compilation is finished. The units given there are "p" (positions, i.e. items
  329. in the position table used to construct the DFA), "s" (DFA states) and "t"
  330. (transitions of the generated DFA).
  331. As implemented, the generated DFA table is stored as a typed array constant
  332. which is inserted into the yylex.cod code template. The transitions in each
  333. state are stored in order. Of course it would have been more efficient to
  334. generate a big CASE statement instead, but I found that this may cause
  335. problems with the encoding of large DFA tables because Turbo Pascal has
  336. a quite rigid limit on the code size of individual procedures. I decided to
  337. use a scheme in which transitions on different symbols to the same state are
  338. merged into one single transition (specifying a character set and the
  339. corresponding next state). This keeps the number of transitions in each state
  340. quite small and still allows a fairly efficient access to the transition
  341. table.
  342. The TP Lex program has an option (-o) to optimize DFA tables. This causes a
  343. minimal DFA to be generated, using the algorithm described in Aho, Sethi,
  344. Ullman (1986). Although the absolute limit on the number of DFA states that TP
  345. Lex can handle is at least 300, TP Lex poses an additional restriction (100)
  346. on the number of states in the initial partition of the DFA optimization
  347. algorithm. Thus, you may get a fatal `integer set overflow' message when using
  348. the -o option even when TP Lex is able to generate an unoptimized DFA. In such
  349. cases you will just have to be content with the unoptimized DFA. (Hopefully,
  350. this will be fixed in a future version. Anyhow, using the merged transitions
  351. scheme described above, TP Lex usually constructs unoptimized DFA's which are
  352. not far from being optimal, and thus in most cases DFA optimization won't have
  353. a great impact on DFA table sizes.)
  354. Differences from UNIX Lex
  355. -------------------------
  356. Major differences between TP Lex and UNIX Lex are listed below.
  357. - TP Lex produces output code for Turbo Pascal, rather than for C.
  358. - Character tables (%T) are not supported; neither are any directives
  359. to determine internal table sizes (%p, %n, etc.).
  360. - Library routines are named differently from the UNIX version (e.g.,
  361. the `start' routine takes the place of the `BEGIN' macro of UNIX
  362. Lex), and, of course, all macros of UNIX Lex (ECHO, REJECT, etc.) had
  363. to be implemented as procedures.
  364. - The TP Lex library unit starts counting line numbers at 0, incrementing
  365. the count BEFORE a line is read (in contrast, UNIX Lex initializes
  366. yylineno to 1 and increments it AFTER the line end has been read). This
  367. is motivated by the way in which TP Lex maintains the current line,
  368. and will not affect your programs unless you explicitly reset the
  369. yylineno value (e.g., when opening a new input file). In such a case
  370. you should set yylineno to 0 rather than 1.
  371. TP Yacc
  372. =======
  373. This section describes the TP Yacc compiler compiler.
  374. Usage
  375. -----
  376. yacc [options] yacc-file[.y] [output-file[.pas]]
  377. Options
  378. -------
  379. -v "Verbose:" TP Yacc generates a readable description of the generated
  380. parser, written to yacc-file with new extension .lst.
  381. -d "Debug:" TP Yacc generates parser with debugging output.
  382. Description
  383. -----------
  384. TP Yacc is a program that lets you prepare parsers from the description
  385. of input languages by BNF-like grammars. You simply specify the grammar
  386. for your target language, augmented with the Turbo Pascal code necessary
  387. to process the syntactic constructs, and TP Yacc translates your grammar
  388. into the Turbo Pascal code for a corresponding parser subroutine named
  389. yyparse.
  390. TP Yacc parses the source grammar contained in yacc-file (with default
  391. suffix .y) and writes the constructed parser subroutine to the specified
  392. output-file (with default suffix .pas); if no output file is specified,
  393. output goes to yacc-file with new suffix .pas. If any errors are found
  394. during compilation, error messages are written to the list file (yacc-file
  395. with new suffix .lst).
  396. The generated parser routine, yyparse, is declared as:
  397. function yyparse : Integer;
  398. This routine may be called by your main program to execute the parser.
  399. The return value of the yyparse routine denotes success or failure of
  400. the parser (possible return values: 0 = success, 1 = unrecoverable syntax
  401. error or parse stack overflow).
  402. Similar to TP Lex, the code template for the yyparse routine may be found in
  403. the yyparse.cod file. The rules for locating this file are analogous to those
  404. of TP Lex (see Section `TP Lex').
  405. The TP Yacc library (YaccLib) unit is required by programs using Yacc-
  406. generated parsers; you will therefore have to put an appropriate uses clause
  407. into your program or unit that contains the parser routine. The YaccLib unit
  408. also provides some routines which may be used to control the actions of the
  409. parser. See the file yacclib.pas for further information.
  410. Yacc Source
  411. -----------
  412. A TP Yacc program consists of three sections separated with the %% delimiter:
  413. definitions
  414. %%
  415. rules
  416. %%
  417. auxiliary procedures
  418. The TP Yacc language is free-format: whitespace (blanks, tabs and newlines)
  419. is ignored, except if it serves as a delimiter. Comments have the C-like
  420. format /* ... */. They are treated as whitespace. Grammar symbols are denoted
  421. by identifiers which have the usual form (letter, including underscore,
  422. followed by a sequence of letters and digits; upper- and lowercase is
  423. distinct). The TP Yacc language also has some keywords which always start
  424. with the % character. Literals are denoted by characters enclosed in single
  425. quotes. The usual C-like escapes are recognized:
  426. \n denotes newline
  427. \r denotes carriage return
  428. \t denotes tab
  429. \b denotes backspace
  430. \f denotes form feed
  431. \NNN denotes character no. NNN in octal base
  432. Definitions
  433. -----------
  434. The first section of a TP Yacc grammar serves to define the symbols used in
  435. the grammar. It may contain the following types of definitions:
  436. - start symbol definition: A definition of the form
  437. %start symbol
  438. declares the start nonterminal of the grammar (if this definition is
  439. omitted, TP Yacc assumes the left-hand side nonterminal of the first
  440. grammar rule as the start symbol of the grammar).
  441. - terminal definitions: Definitions of the form
  442. %token symbol ...
  443. are used to declare the terminal symbols ("tokens") of the target
  444. language. Any identifier not introduced in a %token definition will
  445. be treated as a nonterminal symbol.
  446. As far as TP Yacc is concerned, tokens are atomic symbols which do not
  447. have an innert structure. A lexical analyzer must be provided which
  448. takes on the task of tokenizing the input stream and return the
  449. individual tokens and literals to the parser (see Section `Lexical
  450. Analysis').
  451. - precedence definitions: Operator symbols (terminals) may be associated
  452. with a precedence by means of a precedence definition which may have
  453. one of the following forms
  454. %left symbol ...
  455. %right symbol ...
  456. %nonassoc symbol ...
  457. which are used to declare left-, right- and nonassociative operators,
  458. respectively. Each precedence definition introduces a new precedence
  459. level, lowest precedence first. E.g., you may write:
  460. %nonassoc '<' '>' '=' GEQ LEQ NEQ /* relational operators */
  461. %left '+' '-' OR /* addition operators */
  462. %left '*' '/' AND /* multiplication operators */
  463. %right NOT UMINUS /* unary operators */
  464. A terminal identifier introduced in a precedence definition may, but
  465. need not, appear in a %token definition as well.
  466. - type definitions: Any (terminal or nonterminal) grammar symbol may be
  467. associated with a type identifier which is used in the processing of
  468. semantic values. Type tags of the form <name> may be used in token and
  469. precedence definitions to declare the type of a terminal symbol, e.g.:
  470. %token <Real> NUM
  471. %left <AddOp> '+' '-'
  472. To declare the type of a nonterminal symbol, use a type definition of
  473. the form:
  474. %type <name> symbol ...
  475. e.g.:
  476. %type <Real> expr
  477. In a %type definition, you may also omit the nonterminals, i.e. you
  478. may write:
  479. %type <name>
  480. This is useful when a given type is only used with type casts (see
  481. Section `Grammar Rules and Actions'), and is not associated with a
  482. specific nonterminal.
  483. - Turbo Pascal declarations: You may also include arbitrary Turbo Pascal
  484. code in the definitions section, enclosed in %{ %}. This code will be
  485. inserted as global declarations into the output file, unchanged.
  486. Grammar Rules and Actions
  487. -------------------------
  488. The second part of a TP Yacc grammar contains the grammar rules for the
  489. target language. Grammar rules have the format
  490. name : symbol ... ;
  491. The left-hand side of a rule must be an identifier (which denotes a
  492. nonterminal symbol). The right-hand side may be an arbitrary (possibly
  493. empty) sequence of nonterminal and terminal symbols (including literals
  494. enclosed in single quotes). The terminating semicolon may also be omitted.
  495. Different rules for the same left-hand side symbols may be written using
  496. the | character to separate the different alternatives:
  497. name : symbol ...
  498. | symbol ...
  499. ...
  500. ;
  501. For instance, to specify a simple grammar for arithmetic expressions, you
  502. may write:
  503. %left '+' '-'
  504. %left '*' '/'
  505. %token NUM
  506. %%
  507. expr : expr '+' expr
  508. | expr '-' expr
  509. | expr '*' expr
  510. | expr '/' expr
  511. | '(' expr ')'
  512. | NUM
  513. ;
  514. (The %left definitions at the beginning of the grammar are needed to specify
  515. the precedence and associativity of the operator symbols. This will be
  516. discussed in more detail in Section `Ambigious Grammars'.)
  517. Grammar rules may contain actions - Turbo Pascal statements enclosed in
  518. { } - to be executed as the corresponding rules are recognized. Furthermore,
  519. rules may return values, and access values returned by other rules. These
  520. "semantic" values are written as $$ (value of the left-hand side nonterminal)
  521. and $i (value of the ith right-hand side symbol). They are kept on a special
  522. value stack which is maintained automatically by the parser.
  523. Values associated with terminal symbols must be set by the lexical analyzer
  524. (more about this in Section `Lexical Analysis'). Actions of the form $$ := $1
  525. can frequently be omitted, since it is the default action assumed by TP Yacc
  526. for any rule that does not have an explicit action.
  527. By default, the semantic value type provided by Yacc is Integer. You can
  528. also put a declaration like
  529. %{
  530. type YYSType = Real;
  531. %}
  532. into the definitions section of your Yacc grammar to change the default value
  533. type. However, if you have different value types, the preferred method is to
  534. use type definitions as discussed in Section `Definitions'. When such type
  535. definitions are given, TP Yacc handles all the necessary details of the
  536. YYSType definition and also provides a fair amount of type checking which
  537. makes it easier to find type errors in the grammar.
  538. For instance, we may declare the symbols NUM and expr in the example above
  539. to be of type Real, and then use these values to evaluate an expression as
  540. it is parsed.
  541. %left '+' '-'
  542. %left '*' '/'
  543. %token <Real> NUM
  544. %type <Real> expr
  545. %%
  546. expr : expr '+' expr { $$ := $1+$3; }
  547. | expr '-' expr { $$ := $1-$3; }
  548. | expr '*' expr { $$ := $1*$3; }
  549. | expr '/' expr { $$ := $1/$3; }
  550. | '(' expr ')' { $$ := $2; }
  551. | NUM
  552. ;
  553. (Note that we omitted the action of the last rule. The "copy action"
  554. $$ := $1 required by this rule is automatically added by TP Yacc.)
  555. Actions may not only appear at the end, but also in the middle of a rule
  556. which is useful to perform some processing before a rule is fully parsed.
  557. Such actions inside a rule are treated as special nonterminals which are
  558. associated with an empty right-hand side. Thus, a rule like
  559. x : y { action; } z
  560. will be treated as:
  561. x : y $act z
  562. $act : { action; }
  563. Actions inside a rule may also access values to the left of the action,
  564. and may return values by assigning to the $$ value. The value returned
  565. by such an action can then be accessed by other actions using the usual $i
  566. notation. E.g., we may write:
  567. x : y { $$ := 2*$1; } z { $$ := $2+$3; }
  568. which has the effect of setting the value of x to
  569. 2*(the value of y)+(the value of z).
  570. Sometimes it is desirable to access values in enclosing rules. This can be
  571. done using the notation $i with i<=0. $0 refers to the first value "to the
  572. left" of the current rule, $-1 to the second, and so on. Note that in this
  573. case the referenced value depends on the actual contents of the parse stack,
  574. so you have to make sure that the requested values are always where you
  575. expect them.
  576. There are some situations in which TP Yacc cannot easily determine the
  577. type of values (when a typed parser is used). This is true, in particular,
  578. for values in enclosing rules and for the $$ value in an action inside a
  579. rule. In such cases you may use a type cast to explicitly specify the type
  580. of a value. The format for such type casts is $<name>$ (for left-hand side
  581. values) and $<name>i (for right-hand side values) where name is a type
  582. identifier (which must occur in a %token, precedence or %type definition).
  583. Auxiliary Procedures
  584. --------------------
  585. The third section of a TP Yacc program is optional. If it is present, it
  586. may contain any Turbo Pascal code (such as supporting routines or a main
  587. program) which is tacked on to the end of the output file.
  588. Lexical Analysis
  589. ----------------
  590. For any TP Yacc-generated parser, the programmer must supply a lexical
  591. analyzer routine named yylex which performs the lexical analysis for
  592. the parser. This routine must be declared as
  593. function yylex : Integer;
  594. The yylex routine may either be prepared by hand, or by using the lexical
  595. analyzer generator TP Lex (see Section `TP Lex').
  596. The lexical analyzer must be included in your main program behind the
  597. parser subroutine (the yyparse code template includes a forward
  598. definition of the yylex routine such that the parser can access the
  599. lexical analyzer). For instance, you may put the lexical analyzer
  600. routine into the auxiliary procedures section of your TP Yacc grammar,
  601. either directly, or by using the the Turbo Pascal include directive
  602. ($I).
  603. The parser repeatedly calls the yylex routine to tokenize the input
  604. stream and obtain the individual lexical items in the input. For any
  605. literal character, the yylex routine has to return the corresponding
  606. character code. For the other, symbolic, terminals of the input language,
  607. the lexical analyzer must return corresponding Integer codes. These are
  608. assigned automatically by TP Yacc in the order in which token definitions
  609. appear in the definitions section of the source grammar. The lexical
  610. analyzer can access these values through corresponding Integer constants
  611. which are declared by TP Yacc in the output file.
  612. For instance, if
  613. %token NUM
  614. is the first definition in the Yacc grammar, then TP Yacc will create
  615. a corresponding constant declaration
  616. const NUM = 257;
  617. in the output file (TP Yacc automatically assigns symbolic token numbers
  618. starting at 257; 1 thru 255 are reserved for character literals, 0 denotes
  619. end-of-file, and 256 is reserved for the special error token which will be
  620. discussed in Section `Error Handling'). This definition may then be used,
  621. e.g., in a corresponding TP Lex program as follows:
  622. [0-9]+ return(NUM);
  623. You can also explicitly assign token numbers in the grammar. For this
  624. purpose, the first occurrence of a token identifier in the definitions
  625. section may be followed by an unsigned integer. E.g. you may write:
  626. %token NUM 299
  627. Besides the return value of yylex, the lexical analyzer routine may also
  628. return an additional semantic value for the recognized token. This value
  629. is assigned to a variable named "yylval" and may then be accessed in actions
  630. through the $i notation (see above, Section `Grammar Rules and Actions').
  631. The yylval variable is of type YYSType (the semantic value type, Integer
  632. by default); its declaration may be found in the yyparse.cod file.
  633. For instance, to assign an Integer value to a NUM token in the above
  634. example, we may write:
  635. [0-9]+ begin
  636. val(yytext, yylval, code);
  637. return(NUM);
  638. end;
  639. This assigns yylval the value of the NUM token (using the Turbo Pascal
  640. standard procedure val).
  641. If a parser uses tokens of different types (via a %token <name> definition),
  642. then the yylval variable will not be of type Integer, but instead of a
  643. corresponding variant record type which is capable of holding all the
  644. different value types declared in the TP Yacc grammar. In this case, the
  645. lexical analyzer must assign a semantic value to the corresponding record
  646. component which is named yy<name> (where <name> stands for the corresponding
  647. type identifier).
  648. E.g., if token NUM is declared Real:
  649. %token <Real> NUM
  650. then the value for token NUM must be assigned to yylval.yyReal.
  651. How The Parser Works
  652. --------------------
  653. TP Yacc uses the LALR(1) technique developed by Donald E. Knuth and F.
  654. DeRemer to construct a simple, efficient, non-backtracking bottom-up
  655. parser for the source grammar. The LALR parsing technique is described
  656. in detail in Aho/Sethi/Ullman (1986). It is quite instructive to take a
  657. look at the parser description TP Yacc generates from a small sample
  658. grammar, to get an idea of how the LALR parsing algorithm works. We
  659. consider the following simplified version of the arithmetic expression
  660. grammar:
  661. %token NUM
  662. %left '+'
  663. %left '*'
  664. %%
  665. expr : expr '+' expr
  666. | expr '*' expr
  667. | '(' expr ')'
  668. | NUM
  669. ;
  670. When run with the -v option on the above grammar, TP Yacc generates the
  671. parser description listed below.
  672. state 0:
  673. $accept : _ expr $end
  674. '(' shift 2
  675. NUM shift 3
  676. . error
  677. expr goto 1
  678. state 1:
  679. $accept : expr _ $end
  680. expr : expr _ '+' expr
  681. expr : expr _ '*' expr
  682. $end accept
  683. '*' shift 4
  684. '+' shift 5
  685. . error
  686. state 2:
  687. expr : '(' _ expr ')'
  688. '(' shift 2
  689. NUM shift 3
  690. . error
  691. expr goto 6
  692. state 3:
  693. expr : NUM _ (4)
  694. . reduce 4
  695. state 4:
  696. expr : expr '*' _ expr
  697. '(' shift 2
  698. NUM shift 3
  699. . error
  700. expr goto 7
  701. state 5:
  702. expr : expr '+' _ expr
  703. '(' shift 2
  704. NUM shift 3
  705. . error
  706. expr goto 8
  707. state 6:
  708. expr : '(' expr _ ')'
  709. expr : expr _ '+' expr
  710. expr : expr _ '*' expr
  711. ')' shift 9
  712. '*' shift 4
  713. '+' shift 5
  714. . error
  715. state 7:
  716. expr : expr '*' expr _ (2)
  717. expr : expr _ '+' expr
  718. expr : expr _ '*' expr
  719. . reduce 2
  720. state 8:
  721. expr : expr '+' expr _ (1)
  722. expr : expr _ '+' expr
  723. expr : expr _ '*' expr
  724. '*' shift 4
  725. $end reduce 1
  726. ')' reduce 1
  727. '+' reduce 1
  728. . error
  729. state 9:
  730. expr : '(' expr ')' _ (3)
  731. . reduce 3
  732. Each state of the parser corresponds to a certain prefix of the input
  733. which has already been seen. The parser description lists the grammar
  734. rules wich are parsed in each state, and indicates the portion of each
  735. rule which has already been parsed by an underscore. In state 0, the
  736. start state of the parser, the parsed rule is
  737. $accept : expr $end
  738. This is not an actual grammar rule, but a starting rule automatically
  739. added by TP Yacc. In general, it has the format
  740. $accept : X $end
  741. where X is the start nonterminal of the grammar, and $end is a pseudo
  742. token denoting end-of-input (the $end symbol is used by the parser to
  743. determine when it has successfully parsed the input).
  744. The description of the start rule in state 0,
  745. $accept : _ expr $end
  746. with the underscore positioned before the expr symbol, indicates that
  747. we are at the beginning of the parse and are ready to parse an expression
  748. (nonterminal expr).
  749. The parser maintains a stack to keep track of states visited during the
  750. parse. There are two basic kinds of actions in each state: "shift", which
  751. reads an input symbol and pushes the corresponding next state on top of
  752. the stack, and "reduce" which pops a number of states from the stack
  753. (corresponding to the number of right-hand side symbols of the rule used
  754. in the reduction) and consults the "goto" entries of the uncovered state
  755. to find the transition corresponding to the left-hand side symbol of the
  756. reduced rule.
  757. In each step of the parse, the parser is in a given state (the state on
  758. top of its stack) and may consult the current "lookahead symbol", the
  759. next symbol in the input, to determine the parse action - shift or reduce -
  760. to perform. The parser terminates as soon as it reaches state 1 and reads
  761. in the endmarker, indicated by the "accept" action on $end in state 1.
  762. Sometimes the parser may also carry out an action without inspecting the
  763. current lookahead token. This is the case, e.g., in state 3 where the
  764. only action is reduction by rule 4:
  765. . reduce 4
  766. The default action in a state can also be "error" indicating that any
  767. other input represents a syntax error. (In case of such an error the
  768. parser will start syntactic error recovery, as described in Section
  769. `Error Handling'.)
  770. Now let us see how the parser responds to a given input. We consider the
  771. input string 2+5*3 which is presented to the parser as the token sequence:
  772. NUM + NUM * NUM
  773. The following table traces the corresponding actions of the parser. We also
  774. show the current state in each move, and the remaining states on the stack.
  775. State Stack Lookahead Action
  776. ----- ------------ --------- --------------------------------------------
  777. 0 NUM shift state 3
  778. 3 0 reduce rule 4 (pop 1 state, uncovering state
  779. 0, then goto state 1 on symbol expr)
  780. 1 0 + shift state 5
  781. 5 1 0 NUM shift state 3
  782. 3 5 1 0 reduce rule 4 (pop 1 state, uncovering state
  783. 5, then goto state 8 on symbol expr)
  784. 8 5 1 0 * shift 4
  785. 4 8 5 1 0 NUM shift 3
  786. 3 4 8 5 1 0 reduce rule 4 (pop 1 state, uncovering state
  787. 4, then goto state 7 on symbol expr)
  788. 7 4 8 5 1 0 reduce rule 2 (pop 3 states, uncovering state
  789. 5, then goto state 8 on symbol expr)
  790. 8 5 1 0 $end reduce rule 1 (pop 3 states, uncovering state
  791. 0, then goto state 1 on symbol expr)
  792. 1 0 $end accept
  793. It is also instructive to see how the parser responds to illegal inputs.
  794. E.g., you may try to figure out what the parser does when confronted with:
  795. NUM + )
  796. or:
  797. ( NUM * NUM
  798. You will find that the parser, sooner or later, will always run into an
  799. error action when confronted with errorneous inputs. An LALR parser will
  800. never shift an invalid symbol and thus will always find syntax errors as
  801. soon as it is possible during a left-to-right scan of the input.
  802. TP Yacc provides a debugging option (-d) that may be used to trace the
  803. actions performed by the parser. When a grammar is compiled with the
  804. -d option, the generated parser will print out the actions as it parses
  805. its input.
  806. Ambigious Grammars
  807. ------------------
  808. There are situations in which TP Yacc will not produce a valid parser for
  809. a given input language. LALR(1) parsers are restricted to one-symbol
  810. lookahead on which they have to base their parsing decisions. If a
  811. grammar is ambigious, or cannot be parsed unambigiously using one-symbol
  812. lookahead, TP Yacc will generate parsing conflicts when constructing the
  813. parse table. There are two types of such conflicts: shift/reduce conflicts
  814. (when there is both a shift and a reduce action for a given input symbol
  815. in a given state), and reduce/reduce conflicts (if there is more than
  816. one reduce action for a given input symbol in a given state). Note that
  817. there never will be a shift/shift conflict.
  818. When a grammar generates parsing conflicts, TP Yacc prints out the number
  819. of shift/reduce and reduce/reduce conflicts it encountered when constructing
  820. the parse table. However, TP Yacc will still generate the output code for the
  821. parser. To resolve parsing conflicts, TP Yacc uses the following built-in
  822. disambiguating rules:
  823. - in a shift/reduce conflict, TP Yacc chooses the shift action.
  824. - in a reduce/reduce conflict, TP Yacc chooses reduction of the first
  825. grammar rule.
  826. The shift/reduce disambiguating rule correctly resolves a type of
  827. ambiguity known as the "dangling-else ambiguity" which arises in the
  828. syntax of conditional statements of many programming languages (as in
  829. Pascal):
  830. %token IF THEN ELSE
  831. %%
  832. stmt : IF expr THEN stmt
  833. | IF expr THEN stmt ELSE stmt
  834. ;
  835. This grammar is ambigious, because a nested construct like
  836. IF expr-1 THEN IF expr-2 THEN stmt-1 ELSE stmt-2
  837. can be parsed two ways, either as:
  838. IF expr-1 THEN ( IF expr-2 THEN stmt-1 ELSE stmt-2 )
  839. or as:
  840. IF expr-1 THEN ( IF expr-2 THEN stmt-1 ) ELSE stmt-2
  841. The first interpretation makes an ELSE belong to the last unmatched
  842. IF which also is the interpretation chosen in most programming languages.
  843. This is also the way that a TP Yacc-generated parser will parse the construct
  844. since the shift/reduce disambiguating rule has the effect of neglecting the
  845. reduction of IF expr-2 THEN stmt-1; instead, the parser will shift the ELSE
  846. symbol which eventually leads to the reduction of IF expr-2 THEN stmt-1 ELSE
  847. stmt-2.
  848. The reduce/reduce disambiguating rule is used to resolve conflicts that
  849. arise when there is more than one grammar rule matching a given construct.
  850. Such ambiguities are often caused by "special case constructs" which may be
  851. given priority by simply listing the more specific rules ahead of the more
  852. general ones.
  853. For instance, the following is an excerpt from the grammar describing the
  854. input language of the UNIX equation formatter EQN:
  855. %right SUB SUP
  856. %%
  857. expr : expr SUB expr SUP expr
  858. | expr SUB expr
  859. | expr SUP expr
  860. ;
  861. Here, the SUB and SUP operator symbols denote sub- and superscript,
  862. respectively. The rationale behind this example is that an expression
  863. involving both sub- and superscript is often set differently from a
  864. superscripted subscripted expression. This special case is therefore
  865. caught by the first rule in the above example which causes a reduce/reduce
  866. conflict with rule 3 in expressions like expr-1 SUB expr-2 SUP expr-3.
  867. The conflict is resolved in favour of the first rule.
  868. In both cases discussed above, the ambiguities could also be eliminated
  869. by rewriting the grammar accordingly (although this yields more complicated
  870. and less readable grammars). This may not always be the case. Often
  871. ambiguities are also caused by design errors in the grammar. Hence, if
  872. TP Yacc reports any parsing conflicts when constructing the parser, you
  873. should use the -v option to generate the parser description (.lst file)
  874. and check whether TP Yacc resolved the conflicts correctly.
  875. There is one type of syntactic constructs for which one often deliberately
  876. uses an ambigious grammar as a more concise representation for a language
  877. that could also be specified unambigiously: the syntax of expressions.
  878. For instance, the following is an unambigious grammar for simple arithmetic
  879. expressions:
  880. %token NUM
  881. %%
  882. expr : term
  883. | expr '+' term
  884. ;
  885. term : factor
  886. | term '*' factor
  887. ;
  888. factor : '(' expr ')'
  889. | NUM
  890. ;
  891. You may check yourself that this grammar gives * a higher precedence than
  892. + and makes both operators left-associative. The same effect can be achieved
  893. with the following ambigious grammar using precedence definitions:
  894. %token NUM
  895. %left '+'
  896. %left '*'
  897. %%
  898. expr : expr '+' expr
  899. | expr '*' expr
  900. | '(' expr ')'
  901. | NUM
  902. ;
  903. Without the precedence definitions, this is an ambigious grammar causing
  904. a number of shift/reduce conflicts. The precedence definitions are used
  905. to correctly resolve these conflicts (conflicts resolved using precedence
  906. will not be reported by TP Yacc).
  907. Each precedence definition introduces a new precedence level (lowest
  908. precedence first) and specifies whether the corresponding operators
  909. should be left-, right- or nonassociative (nonassociative operators
  910. cannot be combined at all; example: relational operators in Pascal).
  911. TP Yacc uses precedence information to resolve shift/reduce conflicts as
  912. follows. Precedences are associated with each terminal occuring in a
  913. precedence definition. Furthermore, each grammar rule is given the
  914. precedence of its rightmost terminal (this default choice can be
  915. overwritten using a %prec tag; see below). To resolve a shift/reduce
  916. conflict using precedence, both the symbol and the rule involved must
  917. have been assigned precedences. TP Yacc then chooses the parse action
  918. as follows:
  919. - If the symbol has higher precedence than the rule: shift.
  920. - If the rule has higher precedence than the symbol: reduce.
  921. - If symbol and rule have the same precedence, the associativity of the
  922. symbol determines the parse action: if the symbol is left-associative:
  923. reduce; if the symbol is right-associative: shift; if the symbol is
  924. non-associative: error.
  925. To give you an idea of how this works, let us consider our ambigious
  926. arithmetic expression grammar (without precedences):
  927. %token NUM
  928. %%
  929. expr : expr '+' expr
  930. | expr '*' expr
  931. | '(' expr ')'
  932. | NUM
  933. ;
  934. This grammar generates four shift/reduce conflicts. The description
  935. of state 8 reads as follows:
  936. state 8:
  937. *** conflicts:
  938. shift 4, reduce 1 on '*'
  939. shift 5, reduce 1 on '+'
  940. expr : expr '+' expr _ (1)
  941. expr : expr _ '+' expr
  942. expr : expr _ '*' expr
  943. '*' shift 4
  944. '+' shift 5
  945. $end reduce 1
  946. ')' reduce 1
  947. . error
  948. In this state, we have successfully parsed a + expression (rule 1). When
  949. the next symbol is + or *, we have the choice between the reduction and
  950. shifting the symbol. Using the default shift/reduce disambiguating rule,
  951. TP Yacc has resolved these conflicts in favour of shift.
  952. Now let us assume the above precedence definition:
  953. %left '+'
  954. %left '*'
  955. which gives * higher precedence than + and makes both operators left-
  956. associative. The rightmost terminal in rule 1 is +. Hence, given these
  957. precedence definitions, the first conflict will be resolved in favour
  958. of shift (* has higher precedence than +), while the second one is resolved
  959. in favour of reduce (+ is left-associative).
  960. Similar conflicts arise in state 7:
  961. state 7:
  962. *** conflicts:
  963. shift 4, reduce 2 on '*'
  964. shift 5, reduce 2 on '+'
  965. expr : expr '*' expr _ (2)
  966. expr : expr _ '+' expr
  967. expr : expr _ '*' expr
  968. '*' shift 4
  969. '+' shift 5
  970. $end reduce 2
  971. ')' reduce 2
  972. . error
  973. Here, we have successfully parsed a * expression which may be followed
  974. by another + or * operator. Since * is left-associative and has higher
  975. precedence than +, both conflicts will be resolved in favour of reduce.
  976. Of course, you can also have different operators on the same precedence
  977. level. For instance, consider the following extended version of the
  978. arithmetic expression grammar:
  979. %token NUM
  980. %left '+' '-'
  981. %left '*' '/'
  982. %%
  983. expr : expr '+' expr
  984. | expr '-' expr
  985. | expr '*' expr
  986. | expr '/' expr
  987. | '(' expr ')'
  988. | NUM
  989. ;
  990. This puts all "addition" operators on the first and all "multiplication"
  991. operators on the second precedence level. All operators are left-associative;
  992. for instance, 5+3-2 will be parsed as (5+3)-2.
  993. By default, TP Yacc assigns each rule the precedence of its rightmost
  994. terminal. This is a sensible decision in most cases. Occasionally, it
  995. may be necessary to overwrite this default choice and explicitly assign
  996. a precedence to a rule. This can be done by putting a precedence tag
  997. of the form
  998. %prec symbol
  999. at the end of the corresponding rule which gives the rule the precedence
  1000. of the specified symbol. For instance, to extend the expression grammar
  1001. with a unary minus operator, giving it highest precedence, you may write:
  1002. %token NUM
  1003. %left '+' '-'
  1004. %left '*' '/'
  1005. %right UMINUS
  1006. %%
  1007. expr : expr '+' expr
  1008. | expr '-' expr
  1009. | expr '*' expr
  1010. | expr '/' expr
  1011. | '-' expr %prec UMINUS
  1012. | '(' expr ')'
  1013. | NUM
  1014. ;
  1015. Note the use of the UMINUS token which is not an actual input symbol but
  1016. whose sole purpose it is to give unary minus its proper precedence. If
  1017. we omitted the precedence tag, both unary and binary minus would have the
  1018. same precedence because they are represented by the same input symbol.
  1019. Error Handling
  1020. --------------
  1021. Syntactic error handling is a difficult area in the design of user-friendly
  1022. parsers. Usually, you will not like to have the parser give up upon the
  1023. first occurrence of an errorneous input symbol. Instead, the parser should
  1024. recover from a syntax error, that is, it should try to find a place in the
  1025. input where it can resume the parse.
  1026. TP Yacc provides a general mechanism to implement parsers with error
  1027. recovery. A special predefined "error" token may be used in grammar rules
  1028. to indicate positions where syntax errors might occur. When the parser runs
  1029. into an error action (i.e., reads an errorneous input symbol) it prints out
  1030. an error message and starts error recovery by popping its stack until it
  1031. uncovers a state in which there is a shift action on the error token. If
  1032. there is no such state, the parser terminates with return value 1, indicating
  1033. an unrecoverable syntax error. If there is such a state, the parser takes the
  1034. shift on the error token (pretending it has seen an imaginary error token in
  1035. the input), and resumes parsing in a special "error mode."
  1036. While in error mode, the parser quietly skips symbols until it can again
  1037. perform a legal shift action. To prevent a cascade of error messages, the
  1038. parser returns to its normal mode of operation only after it has seen
  1039. and shifted three legal input symbols. Any additional error found after
  1040. the first shifted symbol restarts error recovery, but no error message
  1041. is printed. The TP Yacc library routine yyerrok may be used to reset the
  1042. parser to its normal mode of operation explicitly.
  1043. For a simple example, consider the rule
  1044. stmt : error ';' { yyerrok; }
  1045. and assume a syntax error occurs while a statement (nonterminal stmt) is
  1046. parsed. The parser prints an error message, then pops its stack until it
  1047. can shift the token error of the error rule. Proceeding in error mode, it
  1048. will skip symbols until it finds a semicolon, then reduces by the error
  1049. rule. The call to yyerrok tells the parser that we have recovered from
  1050. the error and that it should proceed with the normal parse. This kind of
  1051. "panic mode" error recovery scheme works well when statements are always
  1052. terminated with a semicolon. The parser simply skips the "bad" statement
  1053. and then resumes the parse.
  1054. Implementing a good error recovery scheme can be a difficult task; see
  1055. Aho/Sethi/Ullman (1986) for a more comprehensive treatment of this topic.
  1056. Schreiner and Friedman have developed a systematic technique to implement
  1057. error recovery with Yacc which I found quite useful (I used it myself
  1058. to implement error recovery in the TP Yacc parser); see Schreiner/Friedman
  1059. (1985).
  1060. Yacc Library
  1061. ------------
  1062. The TP Yacc library (YaccLib) unit provides some global declarations used
  1063. by the parser routine yyparse, and some variables and utility routines
  1064. which may be used to control the actions of the parser and to implement
  1065. error recovery. See the file yacclib.pas for a description of these
  1066. variables and routines.
  1067. You can also modify the Yacc library unit (and/or the code template in the
  1068. yyparse.cod file) to customize TP Yacc to your target applications.
  1069. Other Features
  1070. --------------
  1071. TP Yacc supports all additional language elements entitled as "Old Features
  1072. Supported But not Encouraged" in the UNIX manual, which are provided for
  1073. backward compatibility with older versions of (UNIX) Yacc:
  1074. - literals delimited by double quotes.
  1075. - multiple-character literals. Note that these are not treated as character
  1076. sequences but represent single tokens which are given a symbolic integer
  1077. code just like any other token identifier. However, they will not be
  1078. declared in the output file, so you have to make sure yourself that
  1079. the lexical analyzer returns the correct codes for these symbols. E.g.,
  1080. you might explicitly assign token numbers by using a definition like
  1081. %token ':=' 257
  1082. at the beginning of the Yacc grammar.
  1083. - \ may be used instead of %, i.e. \\ means %%, \left is the same as %left,
  1084. etc.
  1085. - other synonyms:
  1086. %< for %left
  1087. %> for %right
  1088. %binary or %2 for %nonassoc
  1089. %term or %0 for %token
  1090. %= for %prec
  1091. - actions may also be written as = { ... } or = single-statement;
  1092. - Turbo Pascal declarations (%{ ... %}) may be put at the beginning of the
  1093. rules section. They will be treated as local declarations of the actions
  1094. routine.
  1095. Implementation Restrictions
  1096. ---------------------------
  1097. As with TP Lex, internal table sizes and the main memory available limit the
  1098. complexity of source grammars that TP Yacc can handle. However, the maximum
  1099. table sizes provided by TP Yacc are large enough to handle quite complex
  1100. grammars (such as the Pascal grammar in the TP Yacc distribution). The actual
  1101. table sizes are shown in the statistics printed by TP Yacc when a compilation
  1102. is finished. The given figures are "s" (states), "i" (LR0 kernel items), "t"
  1103. (shift and goto transitions) and "r" (reductions).
  1104. The default stack size of the generated parsers is yymaxdepth = 1024, as
  1105. declared in the TP Yacc library unit. This should be sufficient for any
  1106. average application, but you can change the stack size by including a
  1107. corresponding declaration in the definitions part of the Yacc grammar
  1108. (or change the value in the YaccLib unit). Note that right-recursive
  1109. grammar rules may increase stack space requirements, so it is a good
  1110. idea to use left-recursive rules wherever possible.
  1111. Differences from UNIX Yacc
  1112. --------------------------
  1113. Major differences between TP Yacc and UNIX Yacc are listed below.
  1114. - TP Yacc produces output code for Turbo Pascal, rather than for C.
  1115. - TP Yacc does not support %union definitions. Instead, a value type is
  1116. declared by specifying the type identifier itself as the tag of a %token
  1117. or %type definition. TP Yacc will automatically generate an appropriate
  1118. variant record type (YYSType) which is capable of holding values of any
  1119. of the types used in %token and %type.
  1120. Type checking is very strict. If you use type definitions, then
  1121. any symbol referred to in an action must have a type introduced
  1122. in a type definition. Either the symbol must have been assigned a
  1123. type in the definitions section, or the $<type-identifier> notation
  1124. must be used. The syntax of the %type definition has been changed
  1125. slightly to allow definitions of the form
  1126. %type <type-identifier>
  1127. (omitting the nonterminals) which may be used to declare types which
  1128. are not assigned to any grammar symbol, but are used with the
  1129. $<...> construct.
  1130. - The parse tables constructed by this Yacc version are slightly greater
  1131. than those constructed by UNIX Yacc, since a reduce action will only be
  1132. chosen as the default action if it is the only action in the state.
  1133. In difference, UNIX Yacc chooses a reduce action as the default action
  1134. whenever it is the only reduce action of the state (even if there are
  1135. other shift actions).
  1136. This solves a bug in UNIX Yacc that makes the generated parser start
  1137. error recovery too late with certain types of error productions (see
  1138. also Schreiner/Friedman, "Introduction to compiler construction with
  1139. UNIX," 1985). Also, errors will be caught sooner in most cases where
  1140. UNIX Yacc would carry out an additional (default) reduction before
  1141. detecting the error.
  1142. - Library routines are named differently from the UNIX version (e.g.,
  1143. the `yyerrlab' routine takes the place of the `YYERROR' macro of UNIX
  1144. Yacc), and, of course, all macros of UNIX Yacc (YYERROR, YYACCEPT, etc.)
  1145. had to be implemented as procedures.