bison.info-2 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. This is Info file bison.info, produced by Makeinfo-1.55 from the input
  2. file ./bison.texinfo.
  3. This file documents the Bison parser generator.
  4. Copyright (C) 1988, 89, 90, 91, 92, 93, 1995 Free Software
  5. Foundation, Inc.
  6. Permission is granted to make and distribute verbatim copies of this
  7. manual provided the copyright notice and this permission notice are
  8. preserved on all copies.
  9. Permission is granted to copy and distribute modified versions of
  10. this manual under the conditions for verbatim copying, provided also
  11. that the sections entitled "GNU General Public License" and "Conditions
  12. for Using Bison" are included exactly as in the original, and provided
  13. that the entire resulting derived work is distributed under the terms
  14. of a permission notice identical to this one.
  15. Permission is granted to copy and distribute translations of this
  16. manual into another language, under the above conditions for modified
  17. versions, except that the sections entitled "GNU General Public
  18. License", "Conditions for Using Bison" and this permission notice may be
  19. included in translations approved by the Free Software Foundation
  20. instead of in the original English.
  21. 
  22. File: bison.info, Node: Rpcalc Rules, Next: Rpcalc Lexer, Prev: Rpcalc Decls, Up: RPN Calc
  23. Grammar Rules for `rpcalc'
  24. --------------------------
  25. Here are the grammar rules for the reverse polish notation
  26. calculator.
  27. input: /* empty */
  28. | input line
  29. ;
  30. line: '\n'
  31. | exp '\n' { printf ("\t%.10g\n", $1); }
  32. ;
  33. exp: NUM { $$ = $1; }
  34. | exp exp '+' { $$ = $1 + $2; }
  35. | exp exp '-' { $$ = $1 - $2; }
  36. | exp exp '*' { $$ = $1 * $2; }
  37. | exp exp '/' { $$ = $1 / $2; }
  38. /* Exponentiation */
  39. | exp exp '^' { $$ = pow ($1, $2); }
  40. /* Unary minus */
  41. | exp 'n' { $$ = -$1; }
  42. ;
  43. %%
  44. The groupings of the rpcalc "language" defined here are the
  45. expression (given the name `exp'), the line of input (`line'), and the
  46. complete input transcript (`input'). Each of these nonterminal symbols
  47. has several alternate rules, joined by the `|' punctuator which is read
  48. as "or". The following sections explain what these rules mean.
  49. The semantics of the language is determined by the actions taken
  50. when a grouping is recognized. The actions are the C code that appears
  51. inside braces. *Note Actions::.
  52. You must specify these actions in C, but Bison provides the means for
  53. passing semantic values between the rules. In each action, the
  54. pseudo-variable `$$' stands for the semantic value for the grouping
  55. that the rule is going to construct. Assigning a value to `$$' is the
  56. main job of most actions. The semantic values of the components of the
  57. rule are referred to as `$1', `$2', and so on.
  58. * Menu:
  59. * Rpcalc Input::
  60. * Rpcalc Line::
  61. * Rpcalc Expr::
  62. 
  63. File: bison.info, Node: Rpcalc Input, Next: Rpcalc Line, Up: Rpcalc Rules
  64. Explanation of `input'
  65. ......................
  66. Consider the definition of `input':
  67. input: /* empty */
  68. | input line
  69. ;
  70. This definition reads as follows: "A complete input is either an
  71. empty string, or a complete input followed by an input line". Notice
  72. that "complete input" is defined in terms of itself. This definition
  73. is said to be "left recursive" since `input' appears always as the
  74. leftmost symbol in the sequence. *Note Recursive Rules: Recursion.
  75. The first alternative is empty because there are no symbols between
  76. the colon and the first `|'; this means that `input' can match an empty
  77. string of input (no tokens). We write the rules this way because it is
  78. legitimate to type `Ctrl-d' right after you start the calculator. It's
  79. conventional to put an empty alternative first and write the comment
  80. `/* empty */' in it.
  81. The second alternate rule (`input line') handles all nontrivial
  82. input. It means, "After reading any number of lines, read one more
  83. line if possible." The left recursion makes this rule into a loop.
  84. Since the first alternative matches empty input, the loop can be
  85. executed zero or more times.
  86. The parser function `yyparse' continues to process input until a
  87. grammatical error is seen or the lexical analyzer says there are no more
  88. input tokens; we will arrange for the latter to happen at end of file.
  89. 
  90. File: bison.info, Node: Rpcalc Line, Next: Rpcalc Expr, Prev: Rpcalc Input, Up: Rpcalc Rules
  91. Explanation of `line'
  92. .....................
  93. Now consider the definition of `line':
  94. line: '\n'
  95. | exp '\n' { printf ("\t%.10g\n", $1); }
  96. ;
  97. The first alternative is a token which is a newline character; this
  98. means that rpcalc accepts a blank line (and ignores it, since there is
  99. no action). The second alternative is an expression followed by a
  100. newline. This is the alternative that makes rpcalc useful. The
  101. semantic value of the `exp' grouping is the value of `$1' because the
  102. `exp' in question is the first symbol in the alternative. The action
  103. prints this value, which is the result of the computation the user
  104. asked for.
  105. This action is unusual because it does not assign a value to `$$'.
  106. As a consequence, the semantic value associated with the `line' is
  107. uninitialized (its value will be unpredictable). This would be a bug if
  108. that value were ever used, but we don't use it: once rpcalc has printed
  109. the value of the user's input line, that value is no longer needed.
  110. 
  111. File: bison.info, Node: Rpcalc Expr, Prev: Rpcalc Line, Up: Rpcalc Rules
  112. Explanation of `expr'
  113. .....................
  114. The `exp' grouping has several rules, one for each kind of
  115. expression. The first rule handles the simplest expressions: those
  116. that are just numbers. The second handles an addition-expression,
  117. which looks like two expressions followed by a plus-sign. The third
  118. handles subtraction, and so on.
  119. exp: NUM
  120. | exp exp '+' { $$ = $1 + $2; }
  121. | exp exp '-' { $$ = $1 - $2; }
  122. ...
  123. ;
  124. We have used `|' to join all the rules for `exp', but we could
  125. equally well have written them separately:
  126. exp: NUM ;
  127. exp: exp exp '+' { $$ = $1 + $2; } ;
  128. exp: exp exp '-' { $$ = $1 - $2; } ;
  129. ...
  130. Most of the rules have actions that compute the value of the
  131. expression in terms of the value of its parts. For example, in the
  132. rule for addition, `$1' refers to the first component `exp' and `$2'
  133. refers to the second one. The third component, `'+'', has no meaningful
  134. associated semantic value, but if it had one you could refer to it as
  135. `$3'. When `yyparse' recognizes a sum expression using this rule, the
  136. sum of the two subexpressions' values is produced as the value of the
  137. entire expression. *Note Actions::.
  138. You don't have to give an action for every rule. When a rule has no
  139. action, Bison by default copies the value of `$1' into `$$'. This is
  140. what happens in the first rule (the one that uses `NUM').
  141. The formatting shown here is the recommended convention, but Bison
  142. does not require it. You can add or change whitespace as much as you
  143. wish. For example, this:
  144. exp : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  145. means the same thing as this:
  146. exp: NUM
  147. | exp exp '+' { $$ = $1 + $2; }
  148. | ...
  149. The latter, however, is much more readable.
  150. 
  151. File: bison.info, Node: Rpcalc Lexer, Next: Rpcalc Main, Prev: Rpcalc Rules, Up: RPN Calc
  152. The `rpcalc' Lexical Analyzer
  153. -----------------------------
  154. The lexical analyzer's job is low-level parsing: converting
  155. characters or sequences of characters into tokens. The Bison parser
  156. gets its tokens by calling the lexical analyzer. *Note The Lexical
  157. Analyzer Function `yylex': Lexical.
  158. Only a simple lexical analyzer is needed for the RPN calculator.
  159. This lexical analyzer skips blanks and tabs, then reads in numbers as
  160. `double' and returns them as `NUM' tokens. Any other character that
  161. isn't part of a number is a separate token. Note that the token-code
  162. for such a single-character token is the character itself.
  163. The return value of the lexical analyzer function is a numeric code
  164. which represents a token type. The same text used in Bison rules to
  165. stand for this token type is also a C expression for the numeric code
  166. for the type. This works in two ways. If the token type is a
  167. character literal, then its numeric code is the ASCII code for that
  168. character; you can use the same character literal in the lexical
  169. analyzer to express the number. If the token type is an identifier,
  170. that identifier is defined by Bison as a C macro whose definition is
  171. the appropriate number. In this example, therefore, `NUM' becomes a
  172. macro for `yylex' to use.
  173. The semantic value of the token (if it has one) is stored into the
  174. global variable `yylval', which is where the Bison parser will look for
  175. it. (The C data type of `yylval' is `YYSTYPE', which was defined at
  176. the beginning of the grammar; *note Declarations for `rpcalc': Rpcalc
  177. Decls..)
  178. A token type code of zero is returned if the end-of-file is
  179. encountered. (Bison recognizes any nonpositive value as indicating the
  180. end of the input.)
  181. Here is the code for the lexical analyzer:
  182. /* Lexical analyzer returns a double floating point
  183. number on the stack and the token NUM, or the ASCII
  184. character read if not a number. Skips all blanks
  185. and tabs, returns 0 for EOF. */
  186. #include <ctype.h>
  187. yylex ()
  188. {
  189. int c;
  190. /* skip white space */
  191. while ((c = getchar ()) == ' ' || c == '\t')
  192. ;
  193. /* process numbers */
  194. if (c == '.' || isdigit (c))
  195. {
  196. ungetc (c, stdin);
  197. scanf ("%lf", &yylval);
  198. return NUM;
  199. }
  200. /* return end-of-file */
  201. if (c == EOF)
  202. return 0;
  203. /* return single chars */
  204. return c;
  205. }
  206. 
  207. File: bison.info, Node: Rpcalc Main, Next: Rpcalc Error, Prev: Rpcalc Lexer, Up: RPN Calc
  208. The Controlling Function
  209. ------------------------
  210. In keeping with the spirit of this example, the controlling function
  211. is kept to the bare minimum. The only requirement is that it call
  212. `yyparse' to start the process of parsing.
  213. main ()
  214. {
  215. yyparse ();
  216. }
  217. 
  218. File: bison.info, Node: Rpcalc Error, Next: Rpcalc Gen, Prev: Rpcalc Main, Up: RPN Calc
  219. The Error Reporting Routine
  220. ---------------------------
  221. When `yyparse' detects a syntax error, it calls the error reporting
  222. function `yyerror' to print an error message (usually but not always
  223. `"parse error"'). It is up to the programmer to supply `yyerror'
  224. (*note Parser C-Language Interface: Interface.), so here is the
  225. definition we will use:
  226. #include <stdio.h>
  227. yyerror (s) /* Called by yyparse on error */
  228. char *s;
  229. {
  230. printf ("%s\n", s);
  231. }
  232. After `yyerror' returns, the Bison parser may recover from the error
  233. and continue parsing if the grammar contains a suitable error rule
  234. (*note Error Recovery::.). Otherwise, `yyparse' returns nonzero. We
  235. have not written any error rules in this example, so any invalid input
  236. will cause the calculator program to exit. This is not clean behavior
  237. for a real calculator, but it is adequate in the first example.
  238. 
  239. File: bison.info, Node: Rpcalc Gen, Next: Rpcalc Compile, Prev: Rpcalc Error, Up: RPN Calc
  240. Running Bison to Make the Parser
  241. --------------------------------
  242. Before running Bison to produce a parser, we need to decide how to
  243. arrange all the source code in one or more source files. For such a
  244. simple example, the easiest thing is to put everything in one file.
  245. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  246. "additional C code" section of the file (*note The Overall Layout of a
  247. Bison Grammar: Grammar Layout.).
  248. For a large project, you would probably have several source files,
  249. and use `make' to arrange to recompile them.
  250. With all the source in a single file, you use the following command
  251. to convert it into a parser file:
  252. bison FILE_NAME.y
  253. In this example the file was called `rpcalc.y' (for "Reverse Polish
  254. CALCulator"). Bison produces a file named `FILE_NAME.tab.c', removing
  255. the `.y' from the original file name. The file output by Bison contains
  256. the source code for `yyparse'. The additional functions in the input
  257. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  258. 
  259. File: bison.info, Node: Rpcalc Compile, Prev: Rpcalc Gen, Up: RPN Calc
  260. Compiling the Parser File
  261. -------------------------
  262. Here is how to compile and run the parser file:
  263. # List files in current directory.
  264. % ls
  265. rpcalc.tab.c rpcalc.y
  266. # Compile the Bison parser.
  267. # `-lm' tells compiler to search math library for `pow'.
  268. % cc rpcalc.tab.c -lm -o rpcalc
  269. # List files again.
  270. % ls
  271. rpcalc rpcalc.tab.c rpcalc.y
  272. The file `rpcalc' now contains the executable code. Here is an
  273. example session using `rpcalc'.
  274. % rpcalc
  275. 4 9 +
  276. 13
  277. 3 7 + 3 4 5 *+-
  278. -13
  279. 3 7 + 3 4 5 * + - n Note the unary minus, `n'
  280. 13
  281. 5 6 / 4 n +
  282. -3.166666667
  283. 3 4 ^ Exponentiation
  284. 81
  285. ^D End-of-file indicator
  286. %
  287. 
  288. File: bison.info, Node: Infix Calc, Next: Simple Error Recovery, Prev: RPN Calc, Up: Examples
  289. Infix Notation Calculator: `calc'
  290. =================================
  291. We now modify rpcalc to handle infix operators instead of postfix.
  292. Infix notation involves the concept of operator precedence and the need
  293. for parentheses nested to arbitrary depth. Here is the Bison code for
  294. `calc.y', an infix desk-top calculator.
  295. /* Infix notation calculator--calc */
  296. %{
  297. #define YYSTYPE double
  298. #include <math.h>
  299. %}
  300. /* BISON Declarations */
  301. %token NUM
  302. %left '-' '+'
  303. %left '*' '/'
  304. %left NEG /* negation--unary minus */
  305. %right '^' /* exponentiation */
  306. /* Grammar follows */
  307. %%
  308. input: /* empty string */
  309. | input line
  310. ;
  311. line: '\n'
  312. | exp '\n' { printf ("\t%.10g\n", $1); }
  313. ;
  314. exp: NUM { $$ = $1; }
  315. | exp '+' exp { $$ = $1 + $3; }
  316. | exp '-' exp { $$ = $1 - $3; }
  317. | exp '*' exp { $$ = $1 * $3; }
  318. | exp '/' exp { $$ = $1 / $3; }
  319. | '-' exp %prec NEG { $$ = -$2; }
  320. | exp '^' exp { $$ = pow ($1, $3); }
  321. | '(' exp ')' { $$ = $2; }
  322. ;
  323. %%
  324. The functions `yylex', `yyerror' and `main' can be the same as before.
  325. There are two important new features shown in this code.
  326. In the second section (Bison declarations), `%left' declares token
  327. types and says they are left-associative operators. The declarations
  328. `%left' and `%right' (right associativity) take the place of `%token'
  329. which is used to declare a token type name without associativity.
  330. (These tokens are single-character literals, which ordinarily don't
  331. need to be declared. We declare them here to specify the
  332. associativity.)
  333. Operator precedence is determined by the line ordering of the
  334. declarations; the higher the line number of the declaration (lower on
  335. the page or screen), the higher the precedence. Hence, exponentiation
  336. has the highest precedence, unary minus (`NEG') is next, followed by
  337. `*' and `/', and so on. *Note Operator Precedence: Precedence.
  338. The other important new feature is the `%prec' in the grammar section
  339. for the unary minus operator. The `%prec' simply instructs Bison that
  340. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  341. next-to-highest. *Note Context-Dependent Precedence: Contextual
  342. Precedence.
  343. Here is a sample run of `calc.y':
  344. % calc
  345. 4 + 4.5 - (34/(8*3+-3))
  346. 6.880952381
  347. -56 + 2
  348. -54
  349. 3 ^ 2
  350. 9
  351. 
  352. File: bison.info, Node: Simple Error Recovery, Next: Multi-function Calc, Prev: Infix Calc, Up: Examples
  353. Simple Error Recovery
  354. =====================
  355. Up to this point, this manual has not addressed the issue of "error
  356. recovery"--how to continue parsing after the parser detects a syntax
  357. error. All we have handled is error reporting with `yyerror'. Recall
  358. that by default `yyparse' returns after calling `yyerror'. This means
  359. that an erroneous input line causes the calculator program to exit.
  360. Now we show how to rectify this deficiency.
  361. The Bison language itself includes the reserved word `error', which
  362. may be included in the grammar rules. In the example below it has been
  363. added to one of the alternatives for `line':
  364. line: '\n'
  365. | exp '\n' { printf ("\t%.10g\n", $1); }
  366. | error '\n' { yyerrok; }
  367. ;
  368. This addition to the grammar allows for simple error recovery in the
  369. event of a parse error. If an expression that cannot be evaluated is
  370. read, the error will be recognized by the third rule for `line', and
  371. parsing will continue. (The `yyerror' function is still called upon to
  372. print its message as well.) The action executes the statement
  373. `yyerrok', a macro defined automatically by Bison; its meaning is that
  374. error recovery is complete (*note Error Recovery::.). Note the
  375. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  376. This form of error recovery deals with syntax errors. There are
  377. other kinds of errors; for example, division by zero, which raises an
  378. exception signal that is normally fatal. A real calculator program
  379. must handle this signal and use `longjmp' to return to `main' and
  380. resume parsing input lines; it would also have to discard the rest of
  381. the current line of input. We won't discuss this issue further because
  382. it is not specific to Bison programs.
  383. 
  384. File: bison.info, Node: Multi-function Calc, Next: Exercises, Prev: Simple Error Recovery, Up: Examples
  385. Multi-Function Calculator: `mfcalc'
  386. ===================================
  387. Now that the basics of Bison have been discussed, it is time to move
  388. on to a more advanced problem. The above calculators provided only five
  389. functions, `+', `-', `*', `/' and `^'. It would be nice to have a
  390. calculator that provides other mathematical functions such as `sin',
  391. `cos', etc.
  392. It is easy to add new operators to the infix calculator as long as
  393. they are only single-character literals. The lexical analyzer `yylex'
  394. passes back all non-number characters as tokens, so new grammar rules
  395. suffice for adding a new operator. But we want something more
  396. flexible: built-in functions whose syntax has this form:
  397. FUNCTION_NAME (ARGUMENT)
  398. At the same time, we will add memory to the calculator, by allowing you
  399. to create named variables, store values in them, and use them later.
  400. Here is a sample session with the multi-function calculator:
  401. % mfcalc
  402. pi = 3.141592653589
  403. 3.1415926536
  404. sin(pi)
  405. 0.0000000000
  406. alpha = beta1 = 2.3
  407. 2.3000000000
  408. alpha
  409. 2.3000000000
  410. ln(alpha)
  411. 0.8329091229
  412. exp(ln(beta1))
  413. 2.3000000000
  414. %
  415. Note that multiple assignment and nested function calls are
  416. permitted.
  417. * Menu:
  418. * Decl: Mfcalc Decl. Bison declarations for multi-function calculator.
  419. * Rules: Mfcalc Rules. Grammar rules for the calculator.
  420. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  421. 
  422. File: bison.info, Node: Mfcalc Decl, Next: Mfcalc Rules, Up: Multi-function Calc
  423. Declarations for `mfcalc'
  424. -------------------------
  425. Here are the C and Bison declarations for the multi-function
  426. calculator.
  427. %{
  428. #include <math.h> /* For math functions, cos(), sin(), etc. */
  429. #include "calc.h" /* Contains definition of `symrec' */
  430. %}
  431. %union {
  432. double val; /* For returning numbers. */
  433. symrec *tptr; /* For returning symbol-table pointers */
  434. }
  435. %token <val> NUM /* Simple double precision number */
  436. %token <tptr> VAR FNCT /* Variable and Function */
  437. %type <val> exp
  438. %right '='
  439. %left '-' '+'
  440. %left '*' '/'
  441. %left NEG /* Negation--unary minus */
  442. %right '^' /* Exponentiation */
  443. /* Grammar follows */
  444. %%
  445. The above grammar introduces only two new features of the Bison
  446. language. These features allow semantic values to have various data
  447. types (*note More Than One Value Type: Multiple Types.).
  448. The `%union' declaration specifies the entire list of possible types;
  449. this is instead of defining `YYSTYPE'. The allowable types are now
  450. double-floats (for `exp' and `NUM') and pointers to entries in the
  451. symbol table. *Note The Collection of Value Types: Union Decl.
  452. Since values can now have various types, it is necessary to
  453. associate a type with each grammar symbol whose semantic value is used.
  454. These symbols are `NUM', `VAR', `FNCT', and `exp'. Their declarations
  455. are augmented with information about their data type (placed between
  456. angle brackets).
  457. The Bison construct `%type' is used for declaring nonterminal
  458. symbols, just as `%token' is used for declaring token types. We have
  459. not used `%type' before because nonterminal symbols are normally
  460. declared implicitly by the rules that define them. But `exp' must be
  461. declared explicitly so we can specify its value type. *Note
  462. Nonterminal Symbols: Type Decl.
  463. 
  464. File: bison.info, Node: Mfcalc Rules, Next: Mfcalc Symtab, Prev: Mfcalc Decl, Up: Multi-function Calc
  465. Grammar Rules for `mfcalc'
  466. --------------------------
  467. Here are the grammar rules for the multi-function calculator. Most
  468. of them are copied directly from `calc'; three rules, those which
  469. mention `VAR' or `FNCT', are new.
  470. input: /* empty */
  471. | input line
  472. ;
  473. line:
  474. '\n'
  475. | exp '\n' { printf ("\t%.10g\n", $1); }
  476. | error '\n' { yyerrok; }
  477. ;
  478. exp: NUM { $$ = $1; }
  479. | VAR { $$ = $1->value.var; }
  480. | VAR '=' exp { $$ = $3; $1->value.var = $3; }
  481. | FNCT '(' exp ')' { $$ = (*($1->value.fnctptr))($3); }
  482. | exp '+' exp { $$ = $1 + $3; }
  483. | exp '-' exp { $$ = $1 - $3; }
  484. | exp '*' exp { $$ = $1 * $3; }
  485. | exp '/' exp { $$ = $1 / $3; }
  486. | '-' exp %prec NEG { $$ = -$2; }
  487. | exp '^' exp { $$ = pow ($1, $3); }
  488. | '(' exp ')' { $$ = $2; }
  489. ;
  490. /* End of grammar */
  491. %%
  492. 
  493. File: bison.info, Node: Mfcalc Symtab, Prev: Mfcalc Rules, Up: Multi-function Calc
  494. The `mfcalc' Symbol Table
  495. -------------------------
  496. The multi-function calculator requires a symbol table to keep track
  497. of the names and meanings of variables and functions. This doesn't
  498. affect the grammar rules (except for the actions) or the Bison
  499. declarations, but it requires some additional C functions for support.
  500. The symbol table itself consists of a linked list of records. Its
  501. definition, which is kept in the header `calc.h', is as follows. It
  502. provides for either functions or variables to be placed in the table.
  503. /* Data type for links in the chain of symbols. */
  504. struct symrec
  505. {
  506. char *name; /* name of symbol */
  507. int type; /* type of symbol: either VAR or FNCT */
  508. union {
  509. double var; /* value of a VAR */
  510. double (*fnctptr)(); /* value of a FNCT */
  511. } value;
  512. struct symrec *next; /* link field */
  513. };
  514. typedef struct symrec symrec;
  515. /* The symbol table: a chain of `struct symrec'. */
  516. extern symrec *sym_table;
  517. symrec *putsym ();
  518. symrec *getsym ();
  519. The new version of `main' includes a call to `init_table', a
  520. function that initializes the symbol table. Here it is, and
  521. `init_table' as well:
  522. #include <stdio.h>
  523. main ()
  524. {
  525. init_table ();
  526. yyparse ();
  527. }
  528. yyerror (s) /* Called by yyparse on error */
  529. char *s;
  530. {
  531. printf ("%s\n", s);
  532. }
  533. struct init
  534. {
  535. char *fname;
  536. double (*fnct)();
  537. };
  538. struct init arith_fncts[]
  539. = {
  540. "sin", sin,
  541. "cos", cos,
  542. "atan", atan,
  543. "ln", log,
  544. "exp", exp,
  545. "sqrt", sqrt,
  546. 0, 0
  547. };
  548. /* The symbol table: a chain of `struct symrec'. */
  549. symrec *sym_table = (symrec *)0;
  550. init_table () /* puts arithmetic functions in table. */
  551. {
  552. int i;
  553. symrec *ptr;
  554. for (i = 0; arith_fncts[i].fname != 0; i++)
  555. {
  556. ptr = putsym (arith_fncts[i].fname, FNCT);
  557. ptr->value.fnctptr = arith_fncts[i].fnct;
  558. }
  559. }
  560. By simply editing the initialization list and adding the necessary
  561. include files, you can add additional functions to the calculator.
  562. Two important functions allow look-up and installation of symbols in
  563. the symbol table. The function `putsym' is passed a name and the type
  564. (`VAR' or `FNCT') of the object to be installed. The object is linked
  565. to the front of the list, and a pointer to the object is returned. The
  566. function `getsym' is passed the name of the symbol to look up. If
  567. found, a pointer to that symbol is returned; otherwise zero is returned.
  568. symrec *
  569. putsym (sym_name,sym_type)
  570. char *sym_name;
  571. int sym_type;
  572. {
  573. symrec *ptr;
  574. ptr = (symrec *) malloc (sizeof (symrec));
  575. ptr->name = (char *) malloc (strlen (sym_name) + 1);
  576. strcpy (ptr->name,sym_name);
  577. ptr->type = sym_type;
  578. ptr->value.var = 0; /* set value to 0 even if fctn. */
  579. ptr->next = (struct symrec *)sym_table;
  580. sym_table = ptr;
  581. return ptr;
  582. }
  583. symrec *
  584. getsym (sym_name)
  585. char *sym_name;
  586. {
  587. symrec *ptr;
  588. for (ptr = sym_table; ptr != (symrec *) 0;
  589. ptr = (symrec *)ptr->next)
  590. if (strcmp (ptr->name,sym_name) == 0)
  591. return ptr;
  592. return 0;
  593. }
  594. The function `yylex' must now recognize variables, numeric values,
  595. and the single-character arithmetic operators. Strings of alphanumeric
  596. characters with a leading nondigit are recognized as either variables or
  597. functions depending on what the symbol table says about them.
  598. The string is passed to `getsym' for look up in the symbol table. If
  599. the name appears in the table, a pointer to its location and its type
  600. (`VAR' or `FNCT') is returned to `yyparse'. If it is not already in
  601. the table, then it is installed as a `VAR' using `putsym'. Again, a
  602. pointer and its type (which must be `VAR') is returned to `yyparse'.
  603. No change is needed in the handling of numeric values and arithmetic
  604. operators in `yylex'.
  605. #include <ctype.h>
  606. yylex ()
  607. {
  608. int c;
  609. /* Ignore whitespace, get first nonwhite character. */
  610. while ((c = getchar ()) == ' ' || c == '\t');
  611. if (c == EOF)
  612. return 0;
  613. /* Char starts a number => parse the number. */
  614. if (c == '.' || isdigit (c))
  615. {
  616. ungetc (c, stdin);
  617. scanf ("%lf", &yylval.val);
  618. return NUM;
  619. }
  620. /* Char starts an identifier => read the name. */
  621. if (isalpha (c))
  622. {
  623. symrec *s;
  624. static char *symbuf = 0;
  625. static int length = 0;
  626. int i;
  627. /* Initially make the buffer long enough
  628. for a 40-character symbol name. */
  629. if (length == 0)
  630. length = 40, symbuf = (char *)malloc (length + 1);
  631. i = 0;
  632. do
  633. {
  634. /* If buffer is full, make it bigger. */
  635. if (i == length)
  636. {
  637. length *= 2;
  638. symbuf = (char *)realloc (symbuf, length + 1);
  639. }
  640. /* Add this character to the buffer. */
  641. symbuf[i++] = c;
  642. /* Get another character. */
  643. c = getchar ();
  644. }
  645. while (c != EOF && isalnum (c));
  646. ungetc (c, stdin);
  647. symbuf[i] = '\0';
  648. s = getsym (symbuf);
  649. if (s == 0)
  650. s = putsym (symbuf, VAR);
  651. yylval.tptr = s;
  652. return s->type;
  653. }
  654. /* Any other character is a token by itself. */
  655. return c;
  656. }
  657. This program is both powerful and flexible. You may easily add new
  658. functions, and it is a simple job to modify this code to install
  659. predefined variables such as `pi' or `e' as well.
  660. 
  661. File: bison.info, Node: Exercises, Prev: Multi-function Calc, Up: Examples
  662. Exercises
  663. =========
  664. 1. Add some new functions from `math.h' to the initialization list.
  665. 2. Add another array that contains constants and their values. Then
  666. modify `init_table' to add these constants to the symbol table.
  667. It will be easiest to give the constants type `VAR'.
  668. 3. Make the program report an error if the user refers to an
  669. uninitialized variable in any way except to store a value in it.
  670. 
  671. File: bison.info, Node: Grammar File, Next: Interface, Prev: Examples, Up: Top
  672. Bison Grammar Files
  673. *******************
  674. Bison takes as input a context-free grammar specification and
  675. produces a C-language function that recognizes correct instances of the
  676. grammar.
  677. The Bison grammar input file conventionally has a name ending in
  678. `.y'.
  679. * Menu:
  680. * Grammar Outline:: Overall layout of the grammar file.
  681. * Symbols:: Terminal and nonterminal symbols.
  682. * Rules:: How to write grammar rules.
  683. * Recursion:: Writing recursive rules.
  684. * Semantics:: Semantic values and actions.
  685. * Declarations:: All kinds of Bison declarations are described here.
  686. * Multiple Parsers:: Putting more than one Bison parser in one program.
  687. 
  688. File: bison.info, Node: Grammar Outline, Next: Symbols, Up: Grammar File
  689. Outline of a Bison Grammar
  690. ==========================
  691. A Bison grammar file has four main sections, shown here with the
  692. appropriate delimiters:
  693. %{
  694. C DECLARATIONS
  695. %}
  696. BISON DECLARATIONS
  697. %%
  698. GRAMMAR RULES
  699. %%
  700. ADDITIONAL C CODE
  701. Comments enclosed in `/* ... */' may appear in any of the sections.
  702. * Menu:
  703. * C Declarations:: Syntax and usage of the C declarations section.
  704. * Bison Declarations:: Syntax and usage of the Bison declarations section.
  705. * Grammar Rules:: Syntax and usage of the grammar rules section.
  706. * C Code:: Syntax and usage of the additional C code section.
  707. 
  708. File: bison.info, Node: C Declarations, Next: Bison Declarations, Up: Grammar Outline
  709. The C Declarations Section
  710. --------------------------
  711. The C DECLARATIONS section contains macro definitions and
  712. declarations of functions and variables that are used in the actions in
  713. the grammar rules. These are copied to the beginning of the parser
  714. file so that they precede the definition of `yyparse'. You can use
  715. `#include' to get the declarations from a header file. If you don't
  716. need any C declarations, you may omit the `%{' and `%}' delimiters that
  717. bracket this section.
  718. 
  719. File: bison.info, Node: Bison Declarations, Next: Grammar Rules, Prev: C Declarations, Up: Grammar Outline
  720. The Bison Declarations Section
  721. ------------------------------
  722. The BISON DECLARATIONS section contains declarations that define
  723. terminal and nonterminal symbols, specify precedence, and so on. In
  724. some simple grammars you may not need any declarations. *Note Bison
  725. Declarations: Declarations.
  726. 
  727. File: bison.info, Node: Grammar Rules, Next: C Code, Prev: Bison Declarations, Up: Grammar Outline
  728. The Grammar Rules Section
  729. -------------------------
  730. The "grammar rules" section contains one or more Bison grammar
  731. rules, and nothing else. *Note Syntax of Grammar Rules: Rules.
  732. There must always be at least one grammar rule, and the first `%%'
  733. (which precedes the grammar rules) may never be omitted even if it is
  734. the first thing in the file.
  735. 
  736. File: bison.info, Node: C Code, Prev: Grammar Rules, Up: Grammar Outline
  737. The Additional C Code Section
  738. -----------------------------
  739. The ADDITIONAL C CODE section is copied verbatim to the end of the
  740. parser file, just as the C DECLARATIONS section is copied to the
  741. beginning. This is the most convenient place to put anything that you
  742. want to have in the parser file but which need not come before the
  743. definition of `yyparse'. For example, the definitions of `yylex' and
  744. `yyerror' often go here. *Note Parser C-Language Interface: Interface.
  745. If the last section is empty, you may omit the `%%' that separates it
  746. from the grammar rules.
  747. The Bison parser itself contains many static variables whose names
  748. start with `yy' and many macros whose names start with `YY'. It is a
  749. good idea to avoid using any such names (except those documented in this
  750. manual) in the additional C code section of the grammar file.
  751. 
  752. File: bison.info, Node: Symbols, Next: Rules, Prev: Grammar Outline, Up: Grammar File
  753. Symbols, Terminal and Nonterminal
  754. =================================
  755. "Symbols" in Bison grammars represent the grammatical classifications
  756. of the language.
  757. A "terminal symbol" (also known as a "token type") represents a
  758. class of syntactically equivalent tokens. You use the symbol in grammar
  759. rules to mean that a token in that class is allowed. The symbol is
  760. represented in the Bison parser by a numeric code, and the `yylex'
  761. function returns a token type code to indicate what kind of token has
  762. been read. You don't need to know what the code value is; you can use
  763. the symbol to stand for it.
  764. A "nonterminal symbol" stands for a class of syntactically equivalent
  765. groupings. The symbol name is used in writing grammar rules. By
  766. convention, it should be all lower case.
  767. Symbol names can contain letters, digits (not at the beginning),
  768. underscores and periods. Periods make sense only in nonterminals.
  769. There are two ways of writing terminal symbols in the grammar:
  770. * A "named token type" is written with an identifier, like an
  771. identifier in C. By convention, it should be all upper case. Each
  772. such name must be defined with a Bison declaration such as
  773. `%token'. *Note Token Type Names: Token Decl.
  774. * A "character token type" (or "literal token") is written in the
  775. grammar using the same syntax used in C for character constants;
  776. for example, `'+'' is a character token type. A character token
  777. type doesn't need to be declared unless you need to specify its
  778. semantic value data type (*note Data Types of Semantic Values:
  779. Value Type.), associativity, or precedence (*note Operator
  780. Precedence: Precedence.).
  781. By convention, a character token type is used only to represent a
  782. token that consists of that particular character. Thus, the token
  783. type `'+'' is used to represent the character `+' as a token.
  784. Nothing enforces this convention, but if you depart from it, your
  785. program will confuse other readers.
  786. All the usual escape sequences used in character literals in C can
  787. be used in Bison as well, but you must not use the null character
  788. as a character literal because its ASCII code, zero, is the code
  789. `yylex' returns for end-of-input (*note Calling Convention for
  790. `yylex': Calling Convention.).
  791. How you choose to write a terminal symbol has no effect on its
  792. grammatical meaning. That depends only on where it appears in rules and
  793. on when the parser function returns that symbol.
  794. The value returned by `yylex' is always one of the terminal symbols
  795. (or 0 for end-of-input). Whichever way you write the token type in the
  796. grammar rules, you write it the same way in the definition of `yylex'.
  797. The numeric code for a character token type is simply the ASCII code for
  798. the character, so `yylex' can use the identical character constant to
  799. generate the requisite code. Each named token type becomes a C macro in
  800. the parser file, so `yylex' can use the name to stand for the code.
  801. (This is why periods don't make sense in terminal symbols.) *Note
  802. Calling Convention for `yylex': Calling Convention.
  803. If `yylex' is defined in a separate file, you need to arrange for the
  804. token-type macro definitions to be available there. Use the `-d'
  805. option when you run Bison, so that it will write these macro definitions
  806. into a separate header file `NAME.tab.h' which you can include in the
  807. other source files that need it. *Note Invoking Bison: Invocation.
  808. The symbol `error' is a terminal symbol reserved for error recovery
  809. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  810. In particular, `yylex' should never return this value.
  811. 
  812. File: bison.info, Node: Rules, Next: Recursion, Prev: Symbols, Up: Grammar File
  813. Syntax of Grammar Rules
  814. =======================
  815. A Bison grammar rule has the following general form:
  816. RESULT: COMPONENTS...
  817. ;
  818. where RESULT is the nonterminal symbol that this rule describes and
  819. COMPONENTS are various terminal and nonterminal symbols that are put
  820. together by this rule (*note Symbols::.).
  821. For example,
  822. exp: exp '+' exp
  823. ;
  824. says that two groupings of type `exp', with a `+' token in between, can
  825. be combined into a larger grouping of type `exp'.
  826. Whitespace in rules is significant only to separate symbols. You
  827. can add extra whitespace as you wish.
  828. Scattered among the components can be ACTIONS that determine the
  829. semantics of the rule. An action looks like this:
  830. {C STATEMENTS}
  831. Usually there is only one action and it follows the components. *Note
  832. Actions::.
  833. Multiple rules for the same RESULT can be written separately or can
  834. be joined with the vertical-bar character `|' as follows:
  835. RESULT: RULE1-COMPONENTS...
  836. | RULE2-COMPONENTS...
  837. ...
  838. ;
  839. They are still considered distinct rules even when joined in this way.
  840. If COMPONENTS in a rule is empty, it means that RESULT can match the
  841. empty string. For example, here is how to define a comma-separated
  842. sequence of zero or more `exp' groupings:
  843. expseq: /* empty */
  844. | expseq1
  845. ;
  846. expseq1: exp
  847. | expseq1 ',' exp
  848. ;
  849. It is customary to write a comment `/* empty */' in each rule with no
  850. components.
  851. 
  852. File: bison.info, Node: Recursion, Next: Semantics, Prev: Rules, Up: Grammar File
  853. Recursive Rules
  854. ===============
  855. A rule is called "recursive" when its RESULT nonterminal appears
  856. also on its right hand side. Nearly all Bison grammars need to use
  857. recursion, because that is the only way to define a sequence of any
  858. number of somethings. Consider this recursive definition of a
  859. comma-separated sequence of one or more expressions:
  860. expseq1: exp
  861. | expseq1 ',' exp
  862. ;
  863. Since the recursive use of `expseq1' is the leftmost symbol in the
  864. right hand side, we call this "left recursion". By contrast, here the
  865. same construct is defined using "right recursion":
  866. expseq1: exp
  867. | exp ',' expseq1
  868. ;
  869. Any kind of sequence can be defined using either left recursion or
  870. right recursion, but you should always use left recursion, because it
  871. can parse a sequence of any number of elements with bounded stack
  872. space. Right recursion uses up space on the Bison stack in proportion
  873. to the number of elements in the sequence, because all the elements
  874. must be shifted onto the stack before the rule can be applied even
  875. once. *Note The Bison Parser Algorithm: Algorithm, for further
  876. explanation of this.
  877. "Indirect" or "mutual" recursion occurs when the result of the rule
  878. does not appear directly on its right hand side, but does appear in
  879. rules for other nonterminals which do appear on its right hand side.
  880. For example:
  881. expr: primary
  882. | primary '+' primary
  883. ;
  884. primary: constant
  885. | '(' expr ')'
  886. ;
  887. defines two mutually-recursive nonterminals, since each refers to the
  888. other.
  889. 
  890. File: bison.info, Node: Semantics, Next: Declarations, Prev: Recursion, Up: Grammar File
  891. Defining Language Semantics
  892. ===========================
  893. The grammar rules for a language determine only the syntax. The
  894. semantics are determined by the semantic values associated with various
  895. tokens and groupings, and by the actions taken when various groupings
  896. are recognized.
  897. For example, the calculator calculates properly because the value
  898. associated with each expression is the proper number; it adds properly
  899. because the action for the grouping `X + Y' is to add the numbers
  900. associated with X and Y.
  901. * Menu:
  902. * Value Type:: Specifying one data type for all semantic values.
  903. * Multiple Types:: Specifying several alternative data types.
  904. * Actions:: An action is the semantic definition of a grammar rule.
  905. * Action Types:: Specifying data types for actions to operate on.
  906. * Mid-Rule Actions:: Most actions go at the end of a rule.
  907. This says when, why and how to use the exceptional
  908. action in the middle of a rule.
  909. 
  910. File: bison.info, Node: Value Type, Next: Multiple Types, Up: Semantics
  911. Data Types of Semantic Values
  912. -----------------------------
  913. In a simple program it may be sufficient to use the same data type
  914. for the semantic values of all language constructs. This was true in
  915. the RPN and infix calculator examples (*note Reverse Polish Notation
  916. Calculator: RPN Calc.).
  917. Bison's default is to use type `int' for all semantic values. To
  918. specify some other type, define `YYSTYPE' as a macro, like this:
  919. #define YYSTYPE double
  920. This macro definition must go in the C declarations section of the
  921. grammar file (*note Outline of a Bison Grammar: Grammar Outline.).
  922. 
  923. File: bison.info, Node: Multiple Types, Next: Actions, Prev: Value Type, Up: Semantics
  924. More Than One Value Type
  925. ------------------------
  926. In most programs, you will need different data types for different
  927. kinds of tokens and groupings. For example, a numeric constant may
  928. need type `int' or `long', while a string constant needs type `char *',
  929. and an identifier might need a pointer to an entry in the symbol table.
  930. To use more than one data type for semantic values in one parser,
  931. Bison requires you to do two things:
  932. * Specify the entire collection of possible data types, with the
  933. `%union' Bison declaration (*note The Collection of Value Types:
  934. Union Decl.).
  935. * Choose one of those types for each symbol (terminal or nonterminal)
  936. for which semantic values are used. This is done for tokens with
  937. the `%token' Bison declaration (*note Token Type Names: Token
  938. Decl.) and for groupings with the `%type' Bison declaration (*note
  939. Nonterminal Symbols: Type Decl.).
  940. 
  941. File: bison.info, Node: Actions, Next: Action Types, Prev: Multiple Types, Up: Semantics
  942. Actions
  943. -------
  944. An action accompanies a syntactic rule and contains C code to be
  945. executed each time an instance of that rule is recognized. The task of
  946. most actions is to compute a semantic value for the grouping built by
  947. the rule from the semantic values associated with tokens or smaller
  948. groupings.
  949. An action consists of C statements surrounded by braces, much like a
  950. compound statement in C. It can be placed at any position in the rule;
  951. it is executed at that position. Most rules have just one action at
  952. the end of the rule, following all the components. Actions in the
  953. middle of a rule are tricky and used only for special purposes (*note
  954. Actions in Mid-Rule: Mid-Rule Actions.).
  955. The C code in an action can refer to the semantic values of the
  956. components matched by the rule with the construct `$N', which stands for
  957. the value of the Nth component. The semantic value for the grouping
  958. being constructed is `$$'. (Bison translates both of these constructs
  959. into array element references when it copies the actions into the parser
  960. file.)
  961. Here is a typical example:
  962. exp: ...
  963. | exp '+' exp
  964. { $$ = $1 + $3; }
  965. This rule constructs an `exp' from two smaller `exp' groupings
  966. connected by a plus-sign token. In the action, `$1' and `$3' refer to
  967. the semantic values of the two component `exp' groupings, which are the
  968. first and third symbols on the right hand side of the rule. The sum is
  969. stored into `$$' so that it becomes the semantic value of the
  970. addition-expression just recognized by the rule. If there were a
  971. useful semantic value associated with the `+' token, it could be
  972. referred to as `$2'.
  973. If you don't specify an action for a rule, Bison supplies a default:
  974. `$$ = $1'. Thus, the value of the first symbol in the rule becomes the
  975. value of the whole rule. Of course, the default rule is valid only if
  976. the two data types match. There is no meaningful default action for an
  977. empty rule; every empty rule must have an explicit action unless the
  978. rule's value does not matter.
  979. `$N' with N zero or negative is allowed for reference to tokens and
  980. groupings on the stack *before* those that match the current rule.
  981. This is a very risky practice, and to use it reliably you must be
  982. certain of the context in which the rule is applied. Here is a case in
  983. which you can use this reliably:
  984. foo: expr bar '+' expr { ... }
  985. | expr bar '-' expr { ... }
  986. ;
  987. bar: /* empty */
  988. { previous_expr = $0; }
  989. ;
  990. As long as `bar' is used only in the fashion shown here, `$0' always
  991. refers to the `expr' which precedes `bar' in the definition of `foo'.
  992. 
  993. File: bison.info, Node: Action Types, Next: Mid-Rule Actions, Prev: Actions, Up: Semantics
  994. Data Types of Values in Actions
  995. -------------------------------
  996. If you have chosen a single data type for semantic values, the `$$'
  997. and `$N' constructs always have that data type.
  998. If you have used `%union' to specify a variety of data types, then
  999. you must declare a choice among these types for each terminal or
  1000. nonterminal symbol that can have a semantic value. Then each time you
  1001. use `$$' or `$N', its data type is determined by which symbol it refers
  1002. to in the rule. In this example,
  1003. exp: ...
  1004. | exp '+' exp
  1005. { $$ = $1 + $3; }
  1006. `$1' and `$3' refer to instances of `exp', so they all have the data
  1007. type declared for the nonterminal symbol `exp'. If `$2' were used, it
  1008. would have the data type declared for the terminal symbol `'+'',
  1009. whatever that might be.
  1010. Alternatively, you can specify the data type when you refer to the
  1011. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1012. reference. For example, if you have defined types as shown here:
  1013. %union {
  1014. int itype;
  1015. double dtype;
  1016. }
  1017. then you can write `$<itype>1' to refer to the first subunit of the
  1018. rule as an integer, or `$<dtype>1' to refer to it as a double.