Skip to Content
flex & bison
book

flex & bison

by John Levine
August 2009
Intermediate to advanced
292 pages
7h 31m
English
O'Reilly Media, Inc.
Content preview from flex & bison

Chapter 3. Using Bison

The previous chapter concentrated on flex alone. In this chapter we turn our attention to bison, although we use flex to generate our lexical analyzers. Where flex recognizes regular expressions, bison recognizes entire grammars. Flex divides the input stream into pieces (tokens), and then bison takes these pieces and groups them together logically. In this chapter we’ll finish the desk calculator we started in Chapter 1, starting with simple arithmetic and then adding built-in functions, user variables, and finally user-defined functions.

How a Bison Parser Matches Its Input

Bison takes a grammar that you specify and writes a parser that recognizes valid “sentences” in that grammar. We use the term sentence here in a fairly general way—for a C language grammar, the sentences are syntactically valid C programs. Programs can be syntactically valid but semantically invalid, for example, a C program that assigns a string to an int variable. Bison handles only the syntax; other validation is up to you. As we saw in Chapter 1, a grammar is a series of rules that the parser uses to recognize syntactically valid input. For example, here is a version of the grammar we’ll use later in this chapter in a calculator:

statement:   NAME '=' expression

expression:  NUMBER '+' NUMBER
           | NUMBER '−' NUMBER

The vertical bar, |, means there are two possibilities for the same symbol; that is, an expression can be either an addition or a subtraction. The symbol to the left of the : is ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust in Action

Rust in Action

Tim McNamara
Learning React, 2nd Edition

Learning React, 2nd Edition

Alex Banks, Eve Porcello
Generative AI Design Patterns

Generative AI Design Patterns

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9780596805418Errata Page