| 1 |
% Copyright 2012 VAStech SA (PTY) LTD |
| 2 |
% |
| 3 |
% Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
% you may not use this file except in compliance with the License. |
| 5 |
% You may obtain a copy of the License at |
| 6 |
% |
| 7 |
% http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
% |
| 9 |
% Unless required by applicable law or agreed to in writing, software |
| 10 |
% distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
% See the License for the specific language governing permissions and |
| 13 |
% limitations under the License. |
| 14 |
|
| 15 |
|
| 16 |
\documentclass[12pt]{article} |
| 17 |
\usepackage{amsmath} |
| 18 |
\usepackage[margin=2cm]{geometry} |
| 19 |
\usepackage[parfill]{parskip} |
| 20 |
\usepackage[pdftex]{graphicx} |
| 21 |
\DeclareGraphicsExtensions{.jpg, .pdf} |
| 22 |
\usepackage{longtable} |
| 23 |
\usepackage{fancyvrb} |
| 24 |
\usepackage{listings} |
| 25 |
\usepackage{pdflscape} |
| 26 |
\usepackage{pdfpages} |
| 27 |
\usepackage[bookmarksnumbered,bookmarksopen,bookmarksopenlevel=2,pdffitwindow]{hyperref} |
| 28 |
|
| 29 |
\begin{document} |
| 30 |
\begin{center} |
| 31 |
{\Huge Learn You a gocc for Great Good} \\ |
| 32 |
{\large or \\ |
| 33 |
How to save the world by using compiler theory \\ |
| 34 |
\vspace{1cm} |
| 35 |
2014-05-28}\\ |
| 36 |
\vspace{1cm} |
| 37 |
\includegraphics[scale=.1]{gocc} |
| 38 |
\end{center} |
| 39 |
\tableofcontents |
| 40 |
|
| 41 |
\newcommand{\TBD}{\textcolor{red}{TBD}} |
| 42 |
\newcommand{\TBDx}[1]{\textcolor{red}{TBD:} #1} |
| 43 |
\newcommand{\Go}{{\em Go}\ } |
| 44 |
\newcommand{\Code}[1]{{\bf #1} } |
| 45 |
\newcommand{\gocc}{{\em gocc}\ } |
| 46 |
\newcommand{\Clang}{{\em C} language} |
| 47 |
|
| 48 |
\section{Introduction} |
| 49 |
gocc is a compiler kit which generates lexers, parsers and stand-alone DFAs from an EBNF file. |
| 50 |
|
| 51 |
gocc lexers are deterministic finite state automata (DFA), which recognise regular languages. |
| 52 |
|
| 53 |
gocc parsers are pushdown automata (PDA), which recognise LR-1 languages. LR-1 is the set of languages, which can be parsed deterministically. Some context free grammars (CFG) are outside LR-1, because they produce ambiguous derivations. gocc recognises ambiguous grammars and can automatically resolve LR-1 conflicts (see section~\ref{sec:lr conflicts}). |
| 54 |
|
| 55 |
gocc can also be used to generate stand-alone finite state automata for parsing simple regular languages. See for example: see the mail address example (section~\ref{sec:example mail}). |
| 56 |
|
| 57 |
gocc supports parser error recovery (see section~\ref{sec:error recovery}). |
| 58 |
|
| 59 |
gocc supports action expressions, embedded in the input grammar, for the specification of semantic actions. For simple applications action expressions can be used to implement a syntax directed translation directly within the grammar. See the example in section~\ref{sec:first example}. For more complex applications the action routines can be used to build an abstract syntax tree (AST), which is further processed by later stages of the application. See the example in section~\ref{sec:example ast}. |
| 60 |
|
| 61 |
gocc has been successfully used to develop a query language compiler; a configuration / control language for a distributed system; parsers for protocol messages specified in ABNF~\cite{ABNF} and gographviz (\url{https://github.com/awalterschulze/gographviz}). In addition gocc1 was used to generate the parser for gocc2, and gocc2 to generate the lexer and parser for gocc3. |
| 62 |
|
| 63 |
gocc was designed to be easy to use and experience has shown that its users require very little background knowledge of language and compiler theory to apply it to simple language applications, such as syntax directed translation. An appreciation of mathematical formalism is usually enough and this guide is intended to provide sufficient information for such users, provided they understand: |
| 64 |
\begin{itemize} |
| 65 |
\item The go language; |
| 66 |
\item How to use context free grammars; |
| 67 |
\item How to separate lexical, syntactic and semantic analysis. |
| 68 |
\end{itemize} |
| 69 |
|
| 70 |
More complex applications, such as compiled languages and advanced protocol message parsing require more background, especially: |
| 71 |
\begin{itemize} |
| 72 |
\item The relationship between languages, grammars and automata; |
| 73 |
\item The relationship between regular and context free grammars; |
| 74 |
\item The equivalence of finite state automata with regular grammars; and of pushdown automata with context free grammars; |
| 75 |
\item The meaning and limits of top down/predictive parsing, bottom up parsing and deterministic parsing; |
| 76 |
\item The implications of language ambiguity as well as shift/reduce and reduce/reduce conflicts; |
| 77 |
\item The implications of grammars that generate languages outside the class of context free languages; |
| 78 |
\item Compiler design. |
| 79 |
\end{itemize} |
| 80 |
|
| 81 |
The author considers the {\em Dragon Book}~\cite{Dragon Book} still the best reference for these topics. The reader is also directed to \cite{Modern Compiler Design} for a modern treatment of compiler design, as well as \cite{Parsing} for a comprehensive treatment of the parsing techniques used in gocc. |
| 82 |
|
| 83 |
gocc was conceived out of need in the year after Google released the \Go language. At the time there was no other parser generator available, which could generate parsers in the \Go language. The author set out to create a parser generator for the set of all deterministically parseable languages, which implied the LR(1) technique. Although there are now alternatives to gocc available to \Go programmers we offer gocc to the community in the hope that someone may find it useful and as a token of thanks to Google for the gift of \Go. |
| 84 |
|
| 85 |
\section{Copyright} |
| 86 |
\begin{verbatim} |
| 87 |
Copyright 2012 VAStech SA (PTY) LTD |
| 88 |
|
| 89 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 90 |
you may not use this file except in compliance with the License. |
| 91 |
You may obtain a copy of the License at |
| 92 |
|
| 93 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 94 |
|
| 95 |
Unless required by applicable law or agreed to in writing, software |
| 96 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 97 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 98 |
See the License for the specific language governing permissions and |
| 99 |
limitations under the License. |
| 100 |
\end{verbatim} |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
\section{Definition of terms} |
| 105 |
\begin{longtable}{lp{15cm}} |
| 106 |
\bf AST & Abstract syntax tree\\ |
| 107 |
\bf CFG & Context Free Grammar \\ |
| 108 |
\bf DFA & Deterministic Finite State Automaton. gocc lexers are DFAs. \\ |
| 109 |
\bf PDA & Pushdown Automaton. gocc parsers are PDA's, and can recognise all deterministically parseable (LR-1) languages.\\ |
| 110 |
\end{longtable} |
| 111 |
|
| 112 |
\section{Getting started} |
| 113 |
\begin{enumerate} |
| 114 |
\item Download and install \Go from \url{http://golang.org}. |
| 115 |
|
| 116 |
\item Set your \Code{GOPATH} environment variable. See \url{http://golang.org/doc/code.html}. |
| 117 |
|
| 118 |
\item Install \gocc: |
| 119 |
\begin{enumerate} |
| 120 |
\item In your command line run: \Code{go get github.com/goccmack/gocc/} (go get will git clone gocc into GOPATH/src/github.com/goccmack/gocc and run go install) |
| 121 |
|
| 122 |
or |
| 123 |
|
| 124 |
\item Alternatively clone the repository: \url{https://github.com/goccmack/gocc/archive/master.zip}. Followed by: |
| 125 |
\verb|go install github.com/goccmack/gocc|. |
| 126 |
\end{enumerate} |
| 127 |
|
| 128 |
\end{enumerate} |
| 129 |
|
| 130 |
Test your installation by running \verb|make test| from \verb|$GOPATH/src/github.com/goccmack/gocc|. |
| 131 |
|
| 132 |
\section{How to create and use a parser with gocc} |
| 133 |
Figure~\ref{fig:hl design} shows the high-level design of a user application, which uses a parser generated with gocc. |
| 134 |
\begin{itemize} |
| 135 |
\item The user creates a target grammar conforming to the gocc BNF standard (see section~\ref{sec:gocc syntax}). |
| 136 |
|
| 137 |
\item gocc reads the target grammar and generates the components shown in heavy outline in fig~\ref{fig:hl design}, i.e.: the lexer, parser, token and error packages. |
| 138 |
|
| 139 |
\item The user also creates a package called by the compiler to execute semantic actions for each recognised production of the target grammar. The methods of the semantic package provided by the user correspond to the method calls specified in the action expressions of the target grammar. |
| 140 |
|
| 141 |
\item The user application initialises a lexer object with the input text. Then it calls the \Code{Parse(...)} method of the parser. |
| 142 |
|
| 143 |
\item Once created, the lexer and parser objects may be used repeatedly for successive inputs. For each input the lexer must be initialised with the next input text and the parser's \Code{Parse(...)} method called with a reference to the lexer. |
| 144 |
|
| 145 |
\item The parser reads a stream of tokens (lexical elements) from the lexer (lexer) by repeatedly calling the lexer interface method, \Code{lexer.Scan()}. |
| 146 |
|
| 147 |
\begin{verbatim} |
| 148 |
type Scanner interface { |
| 149 |
Scan() (tok *token.Token) |
| 150 |
} |
| 151 |
\end{verbatim} |
| 152 |
|
| 153 |
Each call to \Code{lexer.Scan} returns a pointer to token.Token. |
| 154 |
|
| 155 |
\item The lexer reads a stream of input characters and recognizes the tokens specified in the target grammar. After reaching the end of input it returns the end of input token to every call to \Code{lexer.Scan()}. |
| 156 |
|
| 157 |
\item Whenever the parser recognises the complete body of a production of the target grammar, it calls the function specified in the action expression associated with that production alternative. The parsed symbols of the recognised production are passed as parameters to the action expression (see section~\ref{sec:gocc syntax}). The result of the action expression is placed on the parser's stack as an attribute of the recognised language symbol. |
| 158 |
|
| 159 |
\item When the parser recognises the complete start production of the grammar it calls its associated action expression. The result of the action expression is returned to the user application as type \Code{interface\{\}} together with a \Code{nil} error value. |
| 160 |
|
| 161 |
\item If the parser encounters an error in the input it may perform automatic error recovery (see section~\ref{sec:error recovery}). If the error is recoverable the parser places all the parsed language symbols associated with the error (completed productions as well as tokens) in a symbol of type \Code{*errors.Error} and places this symbol on the parser stack. The parser then discards input tokens until it encounters an input token which may validly follow the recovered production and parsing continues normally. When error recovery is specified the user application must handle the error symbols which it may receive as attributes in calls to action expressions, or which may be returned as a top-level result of the parse to the calling application. |
| 162 |
|
| 163 |
\item If the parser encounters an irrecoverable error it returns a non-\Code{nil} error value together with an {\em indeterminate} parse result. |
| 164 |
\end{itemize} |
| 165 |
|
| 166 |
\begin{figure} |
| 167 |
\includegraphics[scale=1]{"hl_design"} |
| 168 |
\caption{High-level design} |
| 169 |
\label{fig:hl design} |
| 170 |
\end{figure} |
| 171 |
|
| 172 |
\section{First example}\label{sec:first example} |
| 173 |
This example shows how action expressions in the BNF can be used to implement a syntax directed translation scheme without the need for further user provided packages, such as AST. |
| 174 |
|
| 175 |
The source code of the following example can be found at |
| 176 |
|
| 177 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/calc| |
| 178 |
|
| 179 |
The grammar implements the simple desktop calculator described in~\cite{Dragon Book}. The generated code is both a parser and an interpreter for the calculator. |
| 180 |
|
| 181 |
The following files are provided by the user: |
| 182 |
\begin{verbatim} |
| 183 |
> ls -R |
| 184 |
calc.bnf calc_test.go |
| 185 |
\end{verbatim} |
| 186 |
|
| 187 |
\begin{description} |
| 188 |
\item[calc.bnf] contains the grammar for this example. |
| 189 |
|
| 190 |
\item[calc\_test.go] will be used to execute the generated code. It represents the user application. |
| 191 |
|
| 192 |
\end{description} |
| 193 |
|
| 194 |
\subsection{Step 1: generate code} |
| 195 |
To generate code we run gocc from the directory containing \verb|calc.bnf| with the following command: |
| 196 |
|
| 197 |
\begin{verbatim} |
| 198 |
> gocc calc.bnf |
| 199 |
\end{verbatim} |
| 200 |
|
| 201 |
After running gocc we see that the directory structure now contains the following files: |
| 202 |
|
| 203 |
\begin{verbatim} |
| 204 |
> ls -R |
| 205 |
LR1_sets.txt calc_test.go first.txt lexer_sets.txt token |
| 206 |
calc.bnf errors lexer parser util |
| 207 |
|
| 208 |
./errors: |
| 209 |
errors.go |
| 210 |
|
| 211 |
./lexer: |
| 212 |
acttab.go lexer.go transitiontable.go |
| 213 |
|
| 214 |
./parser: |
| 215 |
action.go actiontable.go gototable.go parser.go productionstable.go |
| 216 |
|
| 217 |
./token: |
| 218 |
token.go |
| 219 |
|
| 220 |
./util: |
| 221 |
litconv.go rune.go |
| 222 |
\end{verbatim} |
| 223 |
|
| 224 |
The generated files are: |
| 225 |
\begin{description} |
| 226 |
\item[LR1\_sets.txt and first.txt] Files containing information about the parser table generation process. They are useful for debugging the parser. |
| 227 |
|
| 228 |
\item[lexer\_sets.txt] File containing information about the lexer generation process. It us useful for debugging the lexer. |
| 229 |
|
| 230 |
\item[errors/errors.go] Declares \verb|type Error|, which is used during automatic recovery from errors in the input. See section~\ref{sec:error recovery} for more details. |
| 231 |
|
| 232 |
\item[lexer/] Contains the files generated for the lexer. |
| 233 |
|
| 234 |
\item[parser/] Contains the files generated for the parser. The interpreter code is embedded within \verb|parser/productionstable.go|. |
| 235 |
|
| 236 |
\item[token/token.go] Contains the declaration of the tokens of the grammar. |
| 237 |
|
| 238 |
\item[util/litconv.go] Contains functions to convert a token literal to a value, e.g.: int64 or rune. |
| 239 |
|
| 240 |
\item[util/rune.go] Contains func() RuneToString, which is used by debug code in the lexer. |
| 241 |
\end{description} |
| 242 |
|
| 243 |
\subsection{The example grammar} |
| 244 |
\verb|calc.bnf| displays the main features of a gocc BNF file: |
| 245 |
|
| 246 |
\begin{verbatim} |
| 247 |
/* Lexical part */ |
| 248 |
|
| 249 |
_digit : '0'-'9' ; |
| 250 |
|
| 251 |
int64 : '1'-'9' {_digit} ; |
| 252 |
|
| 253 |
!whitespace : ' ' | '\t' | '\n' | '\r' ; |
| 254 |
|
| 255 |
/* Syntax part */ |
| 256 |
|
| 257 |
<< |
| 258 |
import( |
| 259 |
"github.com/goccmack/gocc/example/calc/token" |
| 260 |
"github.com/goccmack/gocc/example/calc/util" |
| 261 |
) |
| 262 |
>> |
| 263 |
|
| 264 |
Calc : Expr; |
| 265 |
|
| 266 |
Expr |
| 267 |
: Expr "+" Term << $0.(int64) + $2.(int64), nil >> |
| 268 |
| Term |
| 269 |
; |
| 270 |
|
| 271 |
Term |
| 272 |
: Term "*" Factor << $0.(int64) * $2.(int64), nil >> |
| 273 |
| Factor |
| 274 |
; |
| 275 |
|
| 276 |
Factor |
| 277 |
: "(" Expr ")" << $1, nil >> |
| 278 |
| int64 << util.IntValue($0.(*token.Token).Lit) >> |
| 279 |
; |
| 280 |
|
| 281 |
\end{verbatim} |
| 282 |
|
| 283 |
The BNF has two parts: a lexical and a syntax part. Both parts are optional -- gocc can be used to generate only a lexer or only a parser -- but every BNF must have at least a lexical part or a syntax part. This example has both and gocc will generate a lexer, a parser and all the support they require to function. |
| 284 |
|
| 285 |
It declares the imported package \verb|github.com/goccmack/gocc/example/calc/token| (generated by gocc), which will be used in the action expressions of some productions of the grammar. |
| 286 |
|
| 287 |
The lexical part consists of: |
| 288 |
|
| 289 |
\begin{enumerate} |
| 290 |
\item A token definition, \verb|int64|, which is used in the syntax part. Token identifiers always start with a lower case letter in the range: \verb|'a'-'z'|. The token \verb|int64| must start with a digit in the range, \verb|'1'-'9'|, followed by zero or more digits in the range, \verb|'0'-'9'|. It uses the regular definition, \verb|_digit|, to declare the range, \verb|'0'-'9'|. The curly braces around \verb|_digit| indicate that it may be repeated zero or more times. |
| 291 |
|
| 292 |
A lexical pattern may also be enclosed in square brackets, e.g.: \verb|[ '0'-'9' ]|, to indicate zero or one instances of it (in this case a decimal digit) may be present. See section~\ref{sec:gocc syntax} for details. |
| 293 |
|
| 294 |
\item \verb|!whitespace| declares an ignored token. The \verb|'!'| before \verb|whitespace| indicates that the token is to be ignored. The generated lexer suppresses ignored tokens so that the parser never sees them. They can be uses for white space and comments. |
| 295 |
|
| 296 |
\item A regular definition, \verb|_digit|. Regular definition identifiers always start with \verb|'_'|. Regular definitions act like macros definitions in the BNF and allow tokens to be constructed from pre-defined components. Regular definitions and token definitions may not be mutually or self-recursive. That would lead to a context free grammar, which cannot be recognised by a finite state automaton. |
| 297 |
\end{enumerate} |
| 298 |
|
| 299 |
gocc supports c-style line and block comments. The calc BNF contains two block comments. |
| 300 |
|
| 301 |
The syntax part consists of: |
| 302 |
|
| 303 |
\begin{enumerate} |
| 304 |
\item An optional file header section, which is textually included in the generated parser file, \verb|parser/productionstable.go|. The file header allows the user to specify imports, declarations and functions, which are required by the action routines in the syntax part. In the calc example the file header contains two import declarations. |
| 305 |
|
| 306 |
\item The syntax start symbol, \verb|Calc|, is the highest level syntax production of the BNF. The parser will try to match the input source with a valid derivation of the start symbol. All syntax production identifiers start with an upper case letter in the range, \verb|'A'-'Z'|. |
| 307 |
|
| 308 |
\item Each alternative of a production may optionally have an action expression. E.g.: |
| 309 |
|
| 310 |
\begin{verbatim} |
| 311 |
Factor : int64 << util.IntValue($T0.Lit) >> |
| 312 |
\end{verbatim} |
| 313 |
|
| 314 |
has an action expression, \verb|<< util.IntValue($T0.Lit) >>|, which contains a call to the function, IntValue, in the generated file util/litconv.go. Attribute \verb|$T0|, associated with the symbol \verb|int64| in the body of the production, is type asserted to \verb|*token.Token|, of which the field \verb|Lit| is passed as parameter to the function. |
| 315 |
Action expressions must always return a value of type, \verb|(interface{}, error)|. If the returned error parameter is \verb|nil|, the \verb|interface{}| parameter is placed on the parser stack as the attribute of the recognised production. |
| 316 |
|
| 317 |
\item Each recognised term in a production has an associated attribute. For example: the production alternative: |
| 318 |
|
| 319 |
\begin{verbatim} |
| 320 |
Term : Term "*" Factor << $0.(int64) * $2.(int64), nil >> |
| 321 |
\end{verbatim} |
| 322 |
|
| 323 |
has three symbols in its body. Each has an associated attribute on the stack: \verb|Term|, type \verb|int64|; \verb|"*"|, type \verb|*token.Token|; and \verb|Factor|, type \verb|int64|. They may be referred to in the action expression as \$0, \$1 and \$2, respectively. |
| 324 |
|
| 325 |
The action expression in this example means the following: {\em return the product of \$0 and \$2, both cast to type \verb|int64|, together with \verb|nil|.} |
| 326 |
\end{enumerate} |
| 327 |
|
| 328 |
If an attribute is known to be a \verb|*token.Token| they can be referenced through the shorthand syntax, \$T0, \$T1 and \$T2, respectively. Note, you will need to import the token package. |
| 329 |
|
| 330 |
When the parser has recognised the whole body of a production alternative, it calls the associated action expression with the attributes of the recognised language symbols of that body. If the action expression returns a non-nil error the parser stops and returns the error to the calling user application. If the action expression returns a nil error the parser replaces the recognised language symbols of the production on its stack with the attribute returned by the action expression. |
| 331 |
|
| 332 |
If a recognised production alternative does not have a specific action expression, e.g.: |
| 333 |
\begin{verbatim} |
| 334 |
Calc : Expr; |
| 335 |
\end{verbatim} |
| 336 |
|
| 337 |
the parser always pushes \$0 on the stack as the attribute of the production. |
| 338 |
|
| 339 |
The first alternative of \verb|Expr| returns the sum of the attributes of \verb|Expr| and \verb|Term| after casting them to \verb|int64|. The second alternative returns the attribute of \verb|Term|. |
| 340 |
|
| 341 |
The first alternative of \verb|Term| returns the product of \verb|Term| and \verb|Factor| after casting them to \verb|int64|. The second term returns the attribute of \verb|Factor|. |
| 342 |
|
| 343 |
The first alternative of \verb|Factor| simply returns the attribute of the parenthesised \verb|Expr|. The second alternative returns the value of a numeric token. |
| 344 |
|
| 345 |
In the second alternative of \verb|Factor| we use a method on the input token, which returns |
| 346 |
\verb|(int64, error)|. Therefore the types of all numbers are \verb|int64|. |
| 347 |
|
| 348 |
\subsection{The test program} |
| 349 |
The root folder of the \Code{Calc} example contains \Code{calc\_test.go}, which has the following test program. In addition to testing the code it shows how to initialise and use the generated lexer and parser/interpreter. |
| 350 |
|
| 351 |
\begin{verbatim} |
| 352 |
package calc |
| 353 |
|
| 354 |
import ( |
| 355 |
"github.com/goccmack/gocc/example/calc/lexer" |
| 356 |
"github.com/goccmack/gocc/example/calc/parser" |
| 357 |
"fmt" |
| 358 |
"testing" |
| 359 |
) |
| 360 |
|
| 361 |
type TI struct { |
| 362 |
src string |
| 363 |
expect int64 |
| 364 |
} |
| 365 |
|
| 366 |
var testData = []*TI{ |
| 367 |
{"1 + 1", 2}, |
| 368 |
{"1 * 1", 1}, |
| 369 |
{"1 + 2 * 3", 7}, |
| 370 |
} |
| 371 |
|
| 372 |
func Test1(t *testing.T) { |
| 373 |
p := parser.NewParser() |
| 374 |
pass := true |
| 375 |
for _, ts := range testData { |
| 376 |
s := lexer.NewLexer([]byte(ts.src)) |
| 377 |
sum, err := p.Parse(s) |
| 378 |
if err != nil { |
| 379 |
pass = false |
| 380 |
t.Log(err.Error()) |
| 381 |
} |
| 382 |
if sum != ts.expect { |
| 383 |
pass = false |
| 384 |
t.Log(fmt.Sprintf("Error: %s = %d. Got %d\n", ts.src, sum, ts.expect)) |
| 385 |
} |
| 386 |
} |
| 387 |
if !pass { |
| 388 |
t.Fail() |
| 389 |
} |
| 390 |
} |
| 391 |
\end{verbatim} |
| 392 |
|
| 393 |
\subsection{Step 2: running \Code{go test}} |
| 394 |
From the root folder of the \Code{Calc} example, execute the following command: |
| 395 |
|
| 396 |
\begin{verbatim} |
| 397 |
> go test -v . |
| 398 |
\end{verbatim} |
| 399 |
|
| 400 |
which generates the following output: |
| 401 |
|
| 402 |
\begin{verbatim} |
| 403 |
> go test -v |
| 404 |
warning: building out-of-date packages: |
| 405 |
github.com/goccmack/gocc/example/calc/token |
| 406 |
github.com/goccmack/gocc/example/calc/lexer |
| 407 |
github.com/goccmack/gocc/example/calc/errors |
| 408 |
github.com/goccmack/gocc/example/calc/parser |
| 409 |
installing these packages with 'go test -i' will speed future tests. |
| 410 |
|
| 411 |
=== RUN Test1 |
| 412 |
--- PASS: Test1 (0.00 seconds) |
| 413 |
PASS |
| 414 |
ok github.com/goccmack/gocc/example/calc 0.017s |
| 415 |
\end{verbatim} |
| 416 |
|
| 417 |
{\em Congratulations!} You have executed your first gocc-generated code. |
| 418 |
|
| 419 |
\section{Commandline syntax}\label{sec:commandline} |
| 420 |
\begin{verbatim} |
| 421 |
usage: gocc flags bnf_file |
| 422 |
|
| 423 |
bnf_file: contains the BNF grammar |
| 424 |
|
| 425 |
Flags: |
| 426 |
-a=false: automatically resolve LR(1) conflicts |
| 427 |
-debug_lexer=false: enable debug logging in lexer |
| 428 |
-debug_parser=false: enable debug logging in parser |
| 429 |
-h=false: help |
| 430 |
-no_lexer=false: do not generate a lexer |
| 431 |
-o="/Users/marius/goprj/src/github.com/goccmack/gocc": output dir. |
| 432 |
-p="github.com/goccmack/gocc": package |
| 433 |
-u=false: allow unreachable productions |
| 434 |
-v=false: verbose |
| 435 |
\end{verbatim} |
| 436 |
|
| 437 |
\section{Example: parsing simple mail addresses} \label{sec:example mail} |
| 438 |
This example shows how gocc can be used to generate a stand-alone FSA to parse a regular language. The goal is to parse simple mail address specifications like: \verb|[email protected]| or \verb|"mail box"@gmail.com|. The source code of the sample can be found at |
| 439 |
|
| 440 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/mail| |
| 441 |
|
| 442 |
\verb|mail.bnf| contains: |
| 443 |
|
| 444 |
\begin{verbatim} |
| 445 |
!whitespace : '\t' | '\n' | '\r' | ' ' ; |
| 446 |
|
| 447 |
_atext : 'A'-'Z' | 'a'-'z' | '0'-'9' |
| 448 |
| '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | '-' | '/' |
| 449 |
| '=' | '?' | '^' | '_' | '`' | '{' | '|' | '}' | '~' |
| 450 |
| '\u0100'-'\U0010FFFF' |
| 451 |
; |
| 452 |
|
| 453 |
_atom : _atext {_atext} ; |
| 454 |
|
| 455 |
_dotatom : _atom {'.' _atom} ; |
| 456 |
|
| 457 |
_quotedpair : '\\' . ; |
| 458 |
|
| 459 |
_quotedstring : '"' (_quotedpair | .) {_quotedpair | .} '"' ; |
| 460 |
|
| 461 |
addrspec : (_dotatom | _quotedstring) '@' _dotatom ; |
| 462 |
\end{verbatim} |
| 463 |
|
| 464 |
The production |
| 465 |
|
| 466 |
\verb|_quotedpair : ’\\’ . ;| |
| 467 |
|
| 468 |
uses \verb|'.'| to specify that any UTF-8 rune will be accepted after a \verb|'\'| character in the input. |
| 469 |
|
| 470 |
We generate code for the example by |
| 471 |
|
| 472 |
\verb|gocc mail.bnf| |
| 473 |
|
| 474 |
which produces the following generated code: |
| 475 |
|
| 476 |
\begin{verbatim} |
| 477 |
> ls -R |
| 478 |
lexer lexer_sets.txt mail.bnf parser_test.go token util |
| 479 |
|
| 480 |
./lexer: |
| 481 |
acttab.go lexer.go transitiontable.go |
| 482 |
|
| 483 |
./token: |
| 484 |
token.go |
| 485 |
|
| 486 |
./util: |
| 487 |
rune.go |
| 488 |
\end{verbatim} |
| 489 |
|
| 490 |
Note that no parser had been generated, because the BNF does not include a syntax part. gocc generates only a DFA/lexer for the lexical part, which is present in the BNF. This application uses only a DFA to parse its input. |
| 491 |
|
| 492 |
\verb|parser_test.go| shows how the generated DFA could be repeatedly invoked to parse a stream of email addresses: |
| 493 |
|
| 494 |
\begin{verbatim} |
| 495 |
package mail |
| 496 |
|
| 497 |
import ( |
| 498 |
"github.com/goccmack/gocc/example/mail/lexer" |
| 499 |
"github.com/goccmack/gocc/example/mail/token" |
| 500 |
"testing" |
| 501 |
) |
| 502 |
|
| 503 |
var testData1 = map[string]bool{ |
| 504 |
"[email protected]": true, |
| 505 |
"@google.com": false, |
| 506 |
`"quoted string"@mymail.com`: true, |
| 507 |
`"unclosed [email protected]`: false, |
| 508 |
} |
| 509 |
\end{verbatim} |
| 510 |
|
| 511 |
Function \verb|Test1| proves that the DFA correctly recognises addresses according to the specification. |
| 512 |
|
| 513 |
\begin{verbatim} |
| 514 |
func Test1(t *testing.T) { |
| 515 |
for input, ok := range testData1 { |
| 516 |
l := lexer.NewLexer([]byte(input)) |
| 517 |
tok := l.Scan() |
| 518 |
switch { |
| 519 |
case tok.Type == token.INVALID: |
| 520 |
if ok { |
| 521 |
t.Errorf("%s", input) |
| 522 |
} |
| 523 |
case tok.Type == token.TokMap.Type("addrspec"): |
| 524 |
if !ok { |
| 525 |
t.Errorf("%s", input) |
| 526 |
} |
| 527 |
default: |
| 528 |
t.Fatalf("This must not happen") |
| 529 |
} |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
\end{verbatim} |
| 534 |
|
| 535 |
Function \verb|Test2| shows how to invoke the lexer repeatedly to parse a stream of addresses. |
| 536 |
|
| 537 |
\begin{verbatim} |
| 538 |
var checkData2 = []string{ |
| 539 |
"[email protected]", |
| 540 |
"[email protected]", |
| 541 |
"[email protected]", |
| 542 |
} |
| 543 |
|
| 544 |
var testData2 = ` |
| 545 |
[email protected] |
| 546 |
[email protected] |
| 547 |
[email protected] |
| 548 |
` |
| 549 |
|
| 550 |
func Test2(t *testing.T) { |
| 551 |
l := lexer.NewLexer([]byte(testData2)) |
| 552 |
num := 0 |
| 553 |
for tok := l.Scan(); tok.Type == token.TokMap.Type("addrspec"); tok = l.Scan() { |
| 554 |
if string(tok.Lit) != checkData2[num] { |
| 555 |
t.Errorf("%s != %s", string(tok.Lit), checkData2[num]) |
| 556 |
} |
| 557 |
num++ |
| 558 |
} |
| 559 |
if num != len(checkData2) { |
| 560 |
t.Fatalf("%d addresses parsed", num) |
| 561 |
} |
| 562 |
} |
| 563 |
\end{verbatim} |
| 564 |
|
| 565 |
\section{Handling LR(1) conflicts} \label{sec:lr conflicts} |
| 566 |
If a target grammar is outside the class of LR(1) grammars it cannot be parsed deterministically with one symbol lookahead. This condition manifests as LR(1) conflicts, of which there are two types: |
| 567 |
|
| 568 |
\begin{description} |
| 569 |
\item[Shift/Reduce conflict:] The parser has recognised a valid production body on the stack, and can reduce it to the corresponding production. |
| 570 |
|
| 571 |
However, the same symbols are also a valid prefix of the body of another, longer production. The parser could continue to shift the input symbols and attempt to recognise the longer production. |
| 572 |
|
| 573 |
\gocc uses the {\em maximal-munch rule} (see~\cite{Modern Compiler Design}) to resolve this conflict by always choosing shift over reduce. The longest valid production will therefore always be recognised. |
| 574 |
|
| 575 |
\item[Reduce/Reduce conflict:] The parser has recognised a valid sequence of symbols, which can be reduced to more than one production. |
| 576 |
|
| 577 |
\gocc will always reduce the production that was declared first in the grammar. |
| 578 |
\end{description} |
| 579 |
|
| 580 |
\section{Example: reduce/reduce conflict handling} \label{sec:example rr} |
| 581 |
The source code of the following example can be found at |
| 582 |
|
| 583 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/rr| |
| 584 |
|
| 585 |
\begin{verbatim} |
| 586 |
RR : A | B ; |
| 587 |
|
| 588 |
B : a ; |
| 589 |
|
| 590 |
A : a | A a ; |
| 591 |
|
| 592 |
\end{verbatim} |
| 593 |
|
| 594 |
When we run \gocc on \verb|$GOPATH/src/github.com/goccmack/gocc/example/rr/rr.bnf| we discover a reduce/reduce conflict: |
| 595 |
|
| 596 |
\begin{verbatim} |
| 597 |
> gocc -v rr.bnf |
| 598 |
-a = false |
| 599 |
-debug_lexer = false |
| 600 |
-debug_parser = false |
| 601 |
-h = false |
| 602 |
-no_lexer = false |
| 603 |
-o = /home/src/github.com/goccmack/gocc/example/rr |
| 604 |
-p = github.com/goccmack/gocc/example/rr |
| 605 |
-u = false |
| 606 |
-v = true |
| 607 |
Error: 1 LR-1 conflicts |
| 608 |
\end{verbatim} |
| 609 |
|
| 610 |
\gocc does not generate code because the default for automatic LR(1) conflict resolution is \verb|off|. |
| 611 |
|
| 612 |
When run with \verb|-v|, \gocc generates a number of informational files, we can inspect the file \verb|LR1_conflicts.txt| |
| 613 |
|
| 614 |
\begin{verbatim} |
| 615 |
1 LR-1 conflicts: |
| 616 |
S4 |
| 617 |
symbol: $ |
| 618 |
Reduce(4:A : a << "A0 ", nil >>) |
| 619 |
Reduce(3:B : a << "B ", nil >>) |
| 620 |
\end{verbatim} |
| 621 |
|
| 622 |
From the output we see that \gocc could reduce either of production \verb|B| or \verb|A| in state \verb|4|.and at this point we turn to |
| 623 |
|
| 624 |
We can use \verb|LR1_sets.txt| to analyse the conflict. \verb|LR1_sets.txt| contains the LR(1) sets, which will be translated into the states of the parser. Each state contains a set of {\em LR(1) items}, which specifies what the parser expects in that state. |
| 625 |
|
| 626 |
An LR(1) item is a production alternative with the position of the parser marked by a $\bullet$, and the next symbol expected after this production body, in double angle brackets. Alternatives of a production are in separate items. For example: |
| 627 |
|
| 628 |
$A : a\bullet <<\$>>$ |
| 629 |
|
| 630 |
indicates that the compiler has recognised the production alternative, \verb|A : a| and next expects to see the end of input character, \verb|$|. |
| 631 |
|
| 632 |
Getting back to our R/R conflict, \verb|S4| in \verb|LR1_sets.txt| represents state 4 and contains the following items: |
| 633 |
|
| 634 |
\[ |
| 635 |
\begin{array}{ll} |
| 636 |
S4 \{ \\ |
| 637 |
& A : a\bullet <<\$>> \\ |
| 638 |
& B : a\bullet <<\$>> \\ |
| 639 |
& A : a\bullet <<a>> \\ |
| 640 |
\} \\ |
| 641 |
\end{array} |
| 642 |
\] |
| 643 |
|
| 644 |
We see that the bodies of all items in S4 are the same and that the parser has completely recognised them. Two items reduce to production \verb|A| and one to production \verb|B|. This is the reduce/reduce conflict: \verb|A| vs \verb|B|. |
| 645 |
|
| 646 |
When \gocc is run with the \verb|-a| option it will automatically resolve this conflict by reducing production \verb|B|, because it is declared in \verb|rr.bnf| before \verb|A|: |
| 647 |
|
| 648 |
\begin{verbatim} |
| 649 |
> gocc -a rr.bnf |
| 650 |
\end{verbatim} |
| 651 |
No errors are reported. |
| 652 |
|
| 653 |
|
| 654 |
\section{Example: Shift/reduce conflict handling} \label{sec:example sr} |
| 655 |
The source code of the following example can be found at |
| 656 |
|
| 657 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/sr| |
| 658 |
|
| 659 |
It is the classic example of the dangling else in the \Clang: |
| 660 |
|
| 661 |
\begin{verbatim} |
| 662 |
Stmt : |
| 663 |
if expr then Stmt |
| 664 |
| if expr then Stmt else Stmt |
| 665 |
; |
| 666 |
\end{verbatim} |
| 667 |
|
| 668 |
When we run \gocc on \verb|$GOPATH/src/github.com/goccmack/gocc/example/sr/sr.bnf| we discover a shift/reduce conflict: |
| 669 |
|
| 670 |
\begin{verbatim} |
| 671 |
> gocc -v sr.bnf |
| 672 |
[...] |
| 673 |
Error: 1 LR-1 conflicts |
| 674 |
\end{verbatim} |
| 675 |
|
| 676 |
Inspecting \verb|LR1_conflicts.txt| we see: |
| 677 |
|
| 678 |
\begin{verbatim} |
| 679 |
1 LR-1 conflicts: |
| 680 |
S13 |
| 681 |
symbol: else |
| 682 |
Shift(14) |
| 683 |
Reduce(1:Stmt : "if" id "then" Stmt << ast.NewIf(X[1], X[3]), nil >>) |
| 684 |
\end{verbatim} |
| 685 |
|
| 686 |
|
| 687 |
The problem is in the last two items of state 13, where the next symbol is \verb|else| and the parser can both shift and reduce: |
| 688 |
|
| 689 |
\[ |
| 690 |
\begin{array}{ll} |
| 691 |
S13 \{ \\ |
| 692 |
& Stmt : if\ expr\ then\ Stmt\bullet\ <<\$>> \\ |
| 693 |
& Stmt : if\ expr\ then\ Stmt\ \bullet else\ Stmt\ <<\$>> \\ |
| 694 |
& Stmt : if\ expr\ then\ Stmt \bullet\ <<else>> \\ |
| 695 |
& Stmt : if\ expr\ then\ Stmt\ \bullet else\ Stmt\ <<else>> \\ |
| 696 |
\} \\ |
| 697 |
\end{array} |
| 698 |
\] |
| 699 |
|
| 700 |
When automatic LR(1) conflict resolution is selected by the \verb|-a| option, \gocc resolves this conflict in the same way as specified in the \Clang\ specification: by shifting and parsing the longest valid production ({\em maximal-munch}). This means recognising the \verb|else|-statement as part of the second \verb|if|. |
| 701 |
|
| 702 |
\section{Example: Using an AST} \label{sec:example ast} |
| 703 |
The following example illustrates the use of user-provided action expressions to produce a simple abstract syntax tree (AST) for a list of simple statements. |
| 704 |
|
| 705 |
The code for the example can be found at |
| 706 |
|
| 707 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/astx| |
| 708 |
|
| 709 |
The grammar is in \verb|ast.bnf|: |
| 710 |
|
| 711 |
\begin{verbatim} |
| 712 |
<< |
| 713 |
import "github.com/goccmack/gocc/example/astx/ast" |
| 714 |
import "github.com/goccmack/gocc/example/astx/token" |
| 715 |
>> |
| 716 |
|
| 717 |
StmtList : |
| 718 |
Stmt << ast.NewStmtList($0) >> |
| 719 |
| StmtList Stmt << ast.AppendStmt($0, $1) >> |
| 720 |
; |
| 721 |
|
| 722 |
Stmt : |
| 723 |
id << ast.NewStmt($T0) >> |
| 724 |
; |
| 725 |
\end{verbatim} |
| 726 |
|
| 727 |
At the top of the grammar is a file header section containing an import statement for the user-provided package, |
| 728 |
\verb|github.com/goccmack/gocc/example/astx/ast|. |
| 729 |
|
| 730 |
The production action expressions will use functions from the package, \verb|ast|. |
| 731 |
|
| 732 |
The start production, \verb"StmtList" returns a tuple: \verb|(ast.StmtList, error)|, as we can see from the code of functions |
| 733 |
\verb|NewStmtList| and \verb|AppendStmt| in |
| 734 |
|
| 735 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/astx/ast.go|: |
| 736 |
|
| 737 |
\begin{verbatim} |
| 738 |
package ast |
| 739 |
|
| 740 |
import( |
| 741 |
"github.com/goccmack/gocc/example/astx/token" |
| 742 |
) |
| 743 |
|
| 744 |
type ( |
| 745 |
StmtList []Stmt |
| 746 |
Stmt string |
| 747 |
) |
| 748 |
|
| 749 |
func NewStmtList(stmt interface{}) (StmtList, error) { |
| 750 |
return StmtList{stmt.(Stmt)}, nil |
| 751 |
} |
| 752 |
|
| 753 |
func AppendStmt(stmtList, stmt interface{}) (StmtList, error) { |
| 754 |
return append(stmtList.(StmtList), stmt.(Stmt)), nil |
| 755 |
} |
| 756 |
|
| 757 |
// stmtList is passed using $T0. |
| 758 |
func NewStmt(stmtList *token.Token) (Stmt, error) { |
| 759 |
return Stmt(stmtList.Lit), nil |
| 760 |
} |
| 761 |
\end{verbatim} |
| 762 |
|
| 763 |
Note the following: |
| 764 |
|
| 765 |
\begin{itemize} |
| 766 |
\item The attributes of the language symbols in the production are passed to the action expressions as parameters, referred to as $\$0, \$1, ...$ |
| 767 |
|
| 768 |
\item The type of the parameters passed to the action expressions is \verb|interface{}| and must be type asserted by the called function to the expected type. |
| 769 |
|
| 770 |
\item The parser will return the result of a successful parse, a \verb"StmtList", to the calling application as type \verb"interface{}". The calling application must type assert the returned value to the expected type. |
| 771 |
\end{itemize} |
| 772 |
|
| 773 |
If we run |
| 774 |
|
| 775 |
\verb"go test -v ." |
| 776 |
|
| 777 |
from the directory |
| 778 |
|
| 779 |
\verb|$GOPATH/src/github.com/goccmack/gocc/example/astx/| |
| 780 |
|
| 781 |
we get the following output: |
| 782 |
|
| 783 |
\begin{verbatim} |
| 784 |
> go test -v . |
| 785 |
=== RUN TestPass |
| 786 |
input: a b c d e f |
| 787 |
output: [a b c d e f] |
| 788 |
--- PASS: TestPass (0.00s) |
| 789 |
=== RUN TestFail |
| 790 |
input: a b ; d e f |
| 791 |
Parsing failed as expected: |
| 792 |
Error in S3: INVALID(0,;), Pos(offset=4, line=1, column=5), |
| 793 |
expected one of: $ id |
| 794 |
--- PASS: TestFail (0.00s) |
| 795 |
PASS |
| 796 |
ok github.com/goccmack/gocc/example/astx 0.006s \end{verbatim} |
| 797 |
|
| 798 |
The first test, \verb"TestPass", has a valid input string, \verb|"a b c d e f"|; and parses successfully; and returns the expected StmtList, \verb|[a b c d e f]|. |
| 799 |
|
| 800 |
The input to the second test, \verb|TestFail|, contains an invalid identifier, \verb|;|. The parser returns an error, indicating that it encountered an invalid token when it expect a token of type \verb|id| or the end of input. |
| 801 |
|
| 802 |
\section{Example: Parser error recovery} \label{sec:error recovery} |
| 803 |
Without error recovery a \gocc parser terminates when it reaches the first error in the input. Sometimes it is convenient to attempt to continue the parse and this can be achieved in \gocc by specifying in the grammar which productions can recover from errors in the input. |
| 804 |
|
| 805 |
When the \gocc reserved word, \verb|error|, is the first symbol in a production alternative, it indicates that that production can recover from input errors. |
| 806 |
|
| 807 |
We modify the AST example to illustrate error recovery. See: |
| 808 |
|
| 809 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/errorrecovery/er.bnf|: |
| 810 |
|
| 811 |
\begin{verbatim} |
| 812 |
<< import "github.com/goccmack/gocc/example/errorrecovery/ast" >> |
| 813 |
|
| 814 |
StmtList : |
| 815 |
Stmt << ast.NewStmtList($0) >> |
| 816 |
| StmtList Stmt << ast.AppendStmt($0, $1) >> |
| 817 |
; |
| 818 |
|
| 819 |
Stmt : |
| 820 |
id << ast.NewStmt($0) >> |
| 821 |
| error |
| 822 |
; |
| 823 |
\end{verbatim} |
| 824 |
|
| 825 |
The production, \verb|Stmt|, now has an alternative: \verb"| error" |
| 826 |
|
| 827 |
This indicates to \gocc that input errors can be handles in production \verb|Stmt|. |
| 828 |
|
| 829 |
From the directory, |
| 830 |
|
| 831 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/errorrecovery/|, |
| 832 |
|
| 833 |
run \verb|go test| as follows: |
| 834 |
|
| 835 |
\begin{verbatim} |
| 836 |
> go test -v . |
| 837 |
warning: building out-of-date packages: |
| 838 |
github.com/goccmack/gocc/example/errorrecovery/token |
| 839 |
github.com/goccmack/gocc/example/errorrecovery/ast |
| 840 |
github.com/goccmack/gocc/example/errorrecovery/errors |
| 841 |
github.com/goccmack/gocc/example/errorrecovery/parser |
| 842 |
github.com/goccmack/gocc/example/errorrecovery/lexer |
| 843 |
installing these packages with 'go test -i .' will speed future tests. |
| 844 |
|
| 845 |
=== RUN TestFail |
| 846 |
input: a b ; d e f |
| 847 |
parser.firstRecoveryState: State 3 |
| 848 |
parser.firstRecoveryState: State 1, canRecover, true |
| 849 |
output: [ |
| 850 |
a |
| 851 |
error: |
| 852 |
Err: nil |
| 853 |
ErrorToken: ";"(-1) |
| 854 |
ErrorPos: 1:5 |
| 855 |
ErrorSymbols: ["b"(1)] |
| 856 |
ExpectedTokens: [error $ id] |
| 857 |
d |
| 858 |
e |
| 859 |
f |
| 860 |
] |
| 861 |
--- PASS: TestFail (0.00 seconds) |
| 862 |
PASS ok github.com/goccmack/gocc/example/errorrecovery 0.015s |
| 863 |
\end{verbatim} |
| 864 |
|
| 865 |
The test case can be found in \\ |
| 866 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/errorrecovery/er_test.go|. \\ |
| 867 |
It calls the parser with input string, \verb|"a b ; d e f"|, which contains an invalid token, \verb|;|. |
| 868 |
|
| 869 |
From the \verb|go test| output we see that the parser successfully recovered from the input error and returned a \verb|StmtList| containing an error symbol between \verb|[a| and \verb|d, e, f]|. The \verb|id|, \verb|b|, was lost in the error recovery. \TBDx{Explain exactly why the 'b' was lost.} The errored token was \verb|;| (invalid token) when the parser expected one of \verb|error, $| (end of input) or \verb|id|. |
| 870 |
|
| 871 |
The parser returned an error value of \verb|nil|, because it successfully recovered from the error. |
| 872 |
|
| 873 |
{\bf Note:} \\ |
| 874 |
\begin{enumerate} |
| 875 |
\item When error recovery is allowed the user's code must expect errors and handle the appropriately in the code called by the production action expressions, as well as by the code handling the results returned by the parser. |
| 876 |
|
| 877 |
\item The parser will still return a non-\verb|nil| error value if it encounters an irrecoverable error. |
| 878 |
\end{enumerate} |
| 879 |
|
| 880 |
See \verb|$GOPATH/src/github.com/goccmack/gocc/examples/errorrecovery/errors/error.go| for the definition of errors.Error. |
| 881 |
|
| 882 |
\section{Example: Using another lexer} \label{sec:no lexer} |
| 883 |
The generation of lexer code can be suppressed with the \verb|no_lexer| option (see section~\ref{sec:commandline}). An example, |
| 884 |
which uses a hand-written lexer, can be found at: |
| 885 |
|
| 886 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/nolexer.bnf|: |
| 887 |
|
| 888 |
\begin{verbatim} |
| 889 |
<< |
| 890 |
import ( |
| 891 |
"fmt" |
| 892 |
"github.com/goccmack/gocc/example/nolexer/token" |
| 893 |
) |
| 894 |
>> |
| 895 |
|
| 896 |
Hello : Saying name << func () (Attrib, error) { |
| 897 |
fmt.Println(string($1.(*token.Token).Lit)); |
| 898 |
return nil, nil} () >> |
| 899 |
; |
| 900 |
|
| 901 |
Saying : "hello" << func () (Attrib, error) { |
| 902 |
fmt.Print("hello "); |
| 903 |
return nil, nil} () >> |
| 904 |
| "hiya" << func () (Attrib, error) { |
| 905 |
fmt.Print("hiya "); |
| 906 |
return nil, nil} () >> |
| 907 |
; |
| 908 |
\end{verbatim} |
| 909 |
|
| 910 |
This grammar contains no lexical productions. We generate code for it using |
| 911 |
|
| 912 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/gen.sh|: |
| 913 |
|
| 914 |
\verb|gocc -no_lexer nolexer.bnf| |
| 915 |
|
| 916 |
After running gocc the directory structure contains the following files: |
| 917 |
\begin{verbatim} |
| 918 |
> ls -R |
| 919 |
errors nolexer.bnf parser token |
| 920 |
gen.sh nolexer_test.go scanner util |
| 921 |
|
| 922 |
./errors: |
| 923 |
errors.go |
| 924 |
|
| 925 |
./parser: |
| 926 |
action.go actiontable.go gototable.go parser.go productionstable.go |
| 927 |
|
| 928 |
./scanner: |
| 929 |
scanner.go |
| 930 |
|
| 931 |
./token: |
| 932 |
token.go |
| 933 |
|
| 934 |
./util: |
| 935 |
litconv.go rune.go |
| 936 |
\end{verbatim} |
| 937 |
|
| 938 |
Note the absence of a \verb|lexer| directory. Instead there is a hand-written scanner in |
| 939 |
|
| 940 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/scanner/scanner.go| |
| 941 |
|
| 942 |
The scanner implements the interface: |
| 943 |
|
| 944 |
\lstinputlisting[numbers=left, linerange=89-91, firstnumber=89]{../example/nolexer/parser/parser.go} |
| 945 |
|
| 946 |
which is declared in the generated parser: |
| 947 |
|
| 948 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/parser/parser.go|. |
| 949 |
|
| 950 |
The scanner must recognise the tokens required by the parser generated from the BNF. They are declared in a \verb|TokenMap| in |
| 951 |
|
| 952 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/token/token.go|: |
| 953 |
|
| 954 |
\lstinputlisting[numbers=left,linerange=59-75,firstnumber=59]{../example/nolexer/token/token.go} |
| 955 |
|
| 956 |
\verb|$| is the EOF symbol used by the parser. |
| 957 |
|
| 958 |
\verb|hello| and \verb|hiya| are string literals from the BNF. |
| 959 |
|
| 960 |
\verb|name| is literal other than \verb|hello| and \verb|hiya|. |
| 961 |
|
| 962 |
Any lexeme not matching a valid terminal symbol of the grammar must be returned as \verb|INVALID|. |
| 963 |
|
| 964 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/scanner/scanner.go| implements a lexical analyser for this grammar as follows: |
| 965 |
|
| 966 |
\lstinputlisting[numbers=left]{../example/nolexer/scanner/scanner.go} |
| 967 |
|
| 968 |
Examples of using the generated parser with the hand-written scanner are given in |
| 969 |
|
| 970 |
\verb|$GOPATH/src/github.com/goccmack/gocc/examples/nolexer/nolexer_test.go| |
| 971 |
|
| 972 |
\section{gocc syntax}\label{sec:gocc syntax} |
| 973 |
A gocc source file contains UTF-8 encoded Unicode text. |
| 974 |
|
| 975 |
c-style block and line comments are allowed in the source code. All comments are suppressed by the lexer. |
| 976 |
In the following BNF \Code{!comment} means that \Code{comment} is a token, which is recognised and suppressed by the lexer -- it is not seen by the parser. |
| 977 |
|
| 978 |
\begin{Verbatim}[frame=single] |
| 979 |
!comment : _lineComment | _blockComment ; |
| 980 |
|
| 981 |
_lineComment : '/' '/' {.} '\n' ; |
| 982 |
|
| 983 |
_blockComment : '/' '*' {. | '*'} '*' '/' ; |
| 984 |
\end{Verbatim} |
| 985 |
|
| 986 |
gocc source code consists of a sequence of tokens separated by white space. The white space characters are: |
| 987 |
|
| 988 |
\begin{tabular}{ccc} |
| 989 |
\bf Character & \bf Unicode value & \bf go char literal\\ |
| 990 |
\hline |
| 991 |
space & 0x20 & \verb|' '| \\ |
| 992 |
horizontal tab & 0x09 & \verb|'\t'| \\ |
| 993 |
newline & 0x0a & \verb|'\n'| \\ |
| 994 |
carriage return & 0x0d & \verb|'\r'| \\ |
| 995 |
\end{tabular} |
| 996 |
|
| 997 |
White space is suppressed by the lexer. |
| 998 |
|
| 999 |
\begin{Verbatim}[frame=single] |
| 1000 |
!whitespace : ' ' | '\t' | '\n' | '\r' ; |
| 1001 |
\end{Verbatim} |
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
A gocc source file must contain at least one of a lexical part or a syntax part. |
| 1006 |
|
| 1007 |
\begin{Verbatim}[frame=single] |
| 1008 |
Grammar |
| 1009 |
: LexicalPart SyntaxPart |
| 1010 |
| LexicalPart |
| 1011 |
| SyntaxPart |
| 1012 |
; |
| 1013 |
\end{Verbatim} |
| 1014 |
|
| 1015 |
The lexical part is a sequence of lexical productions. |
| 1016 |
|
| 1017 |
\begin{Verbatim}[frame=single] |
| 1018 |
LexicalPart |
| 1019 |
: LexProductions |
| 1020 |
; |
| 1021 |
\end{Verbatim} |
| 1022 |
|
| 1023 |
\begin{Verbatim}[frame=single] |
| 1024 |
LexProductions |
| 1025 |
: LexProduction |
| 1026 |
| LexProductions LexProduction |
| 1027 |
; |
| 1028 |
\end{Verbatim} |
| 1029 |
|
| 1030 |
Each lexical production is token definition or a regular definition or an ignored token definition. Token identifiers start with a lower case character in the range \verb|'a'-'z'|, regular definition identifiers start with \verb|'_'| and ignored token identifiers start with \verb|'!'|. |
| 1031 |
|
| 1032 |
Regular definitions are used as building blocks for other regular definitions, token definitions and ignored token definitions. Regular definitions may not be mutually or self recursive. |
| 1033 |
|
| 1034 |
Token definitions define the tokens that are recognised by the lexer and passed to the parser. |
| 1035 |
|
| 1036 |
Ignored token definitions define tokens that are recognised by the lexer but suppressed so that the parser never sees them. Comments and the white space separating tokens are examples of ignored tokens. |
| 1037 |
|
| 1038 |
\begin{Verbatim}[frame=single] |
| 1039 |
LexProduction |
| 1040 |
: tokId ":" LexPattern ";" // token definition |
| 1041 |
| regDefId ":" LexPattern ";" // regular definition |
| 1042 |
| ignoredTokId ":" LexPattern ";" // ignored token defition |
| 1043 |
; |
| 1044 |
\end{Verbatim} |
| 1045 |
|
| 1046 |
Token identifiers start with a lowercase letter in the range \verb|'a'-'z'|. |
| 1047 |
|
| 1048 |
\begin{Verbatim}[frame=single] |
| 1049 |
tokId : _tokId ; |
| 1050 |
|
| 1051 |
_tokId : _lowcase {_id_char} ; |
| 1052 |
|
| 1053 |
_lowcase : 'a'-'z' ; |
| 1054 |
|
| 1055 |
_id_char : _upcase | _lowcase | '_' | _digit ; |
| 1056 |
|
| 1057 |
_upcase : 'A'-'Z' ; |
| 1058 |
|
| 1059 |
_digit : '0'-'9' ; |
| 1060 |
\end{Verbatim} |
| 1061 |
|
| 1062 |
Regular definition identifiers start with \verb|'_'|. |
| 1063 |
|
| 1064 |
\begin{Verbatim}[frame=single] |
| 1065 |
regDefId : '_' {_id_char} ; |
| 1066 |
\end{Verbatim} |
| 1067 |
|
| 1068 |
Ignored token identifiers start with \verb|'!'| |
| 1069 |
|
| 1070 |
\begin{Verbatim}[frame=single] |
| 1071 |
ignoredTokId : '!' _tokId ; |
| 1072 |
\end{Verbatim} |
| 1073 |
|
| 1074 |
A lexical pattern is one or more alternatives, each consisting of a sequence of terms. |
| 1075 |
|
| 1076 |
\begin{Verbatim}[frame=single] |
| 1077 |
LexPattern |
| 1078 |
: LexAlt |
| 1079 |
| LexPattern "|" LexAlt |
| 1080 |
; |
| 1081 |
|
| 1082 |
LexAlt |
| 1083 |
: LexTerm |
| 1084 |
| LexAlt LexTerm |
| 1085 |
; |
| 1086 |
\end{Verbatim} |
| 1087 |
|
| 1088 |
A lexical term can be one of: |
| 1089 |
|
| 1090 |
\begin{longtable}{lp{12cm}} |
| 1091 |
\verb|.| & Match any UTF-8 rune. This match is only applied after all more specific terms have been matched. \\ |
| 1092 |
\verb|char_lit| & A specific character literal, e.g.: \verb|'a'|. \\ |
| 1093 |
\verb|char_lit "-" char_lit| & An inclusive range, e.g.: \verb|'a'-'z'| \\ |
| 1094 |
\verb|regDefId| & the identifier of a regular definition production in the BNF \\ |
| 1095 |
\verb|"[" LexPattern "]"| & An optional lexical pattern \\ |
| 1096 |
\verb|"{" LexPattern "}"| & Zero or more instances of a lexical pattern \\ |
| 1097 |
\verb|"(" LexPattern ")"| & A grouped lexical pattern, e.g.: \verb+('a' | 'b')+ \\ |
| 1098 |
\end{longtable} |
| 1099 |
|
| 1100 |
\begin{Verbatim}[frame=single] |
| 1101 |
LexTerm |
| 1102 |
: "." |
| 1103 |
| char_lit |
| 1104 |
| char_lit "-" char_lit |
| 1105 |
| regDefId |
| 1106 |
| "[" LexPattern "]" |
| 1107 |
| "{" LexPattern "}" |
| 1108 |
| "(" LexPattern ")" |
| 1109 |
; |
| 1110 |
\end{Verbatim} |
| 1111 |
|
| 1112 |
Character literals are specified as a valid Unicode or byte value, enclosed in single quotes: |
| 1113 |
|
| 1114 |
\begin{Verbatim}[frame=single] |
| 1115 |
char_lit |
| 1116 |
: '\'' (_unicode_value | _byte_value) '\'' |
| 1117 |
; |
| 1118 |
\end{Verbatim} |
| 1119 |
|
| 1120 |
A Unicode character may be specified as a character literal (e.g.: \verb|'a'|), a Unicode value or an escaped character. |
| 1121 |
|
| 1122 |
\begin{Verbatim}[frame=single] |
| 1123 |
_unicode_value |
| 1124 |
: . // Any UTF-8 character literal |
| 1125 |
| _little_u_value |
| 1126 |
| _big_u_value |
| 1127 |
| _escaped_char |
| 1128 |
; |
| 1129 |
|
| 1130 |
_byte_value |
| 1131 |
: _octal_byte_value |
| 1132 |
| _hex_byte_value |
| 1133 |
; |
| 1134 |
|
| 1135 |
_little_u_value |
| 1136 |
: '\\' 'u' _hex_digit _hex_digit _hex_digit _hex_digit |
| 1137 |
; |
| 1138 |
|
| 1139 |
_big_u_value |
| 1140 |
: '\\' 'U' _hex_digit _hex_digit _hex_digit _hex_digit |
| 1141 |
_hex_digit _hex_digit _hex_digit _hex_digit |
| 1142 |
; |
| 1143 |
|
| 1144 |
_escaped_char |
| 1145 |
: '\\' ( 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' | '\\' | '\'' | '"' ) |
| 1146 |
; |
| 1147 |
|
| 1148 |
_octal_byte_value |
| 1149 |
: '\\' _octal_digit _octal_digit _octal_digit |
| 1150 |
; |
| 1151 |
|
| 1152 |
_hex_byte_value |
| 1153 |
: '\\' 'x' _hex_digit _hex_digit |
| 1154 |
; |
| 1155 |
|
| 1156 |
_octal_digit |
| 1157 |
: '0' - '7' |
| 1158 |
; |
| 1159 |
|
| 1160 |
_hex_digit |
| 1161 |
: '0' - '9' |
| 1162 |
| 'A' - 'F' |
| 1163 |
| 'a' - 'f' |
| 1164 |
; |
| 1165 |
\end{Verbatim} |
| 1166 |
|
| 1167 |
The syntax part may start with an optional file header, followed by a sequence of syntax productions. The file header is textually included in the generated parser file, \verb|productiontable.go|, and is used to declare imports, constants, types and functions required by the action expressions of the productions. |
| 1168 |
|
| 1169 |
\begin{Verbatim}[frame=single] |
| 1170 |
SyntaxPart |
| 1171 |
: FileHeader SyntaxProdList |
| 1172 |
| SyntaxProdList |
| 1173 |
; |
| 1174 |
|
| 1175 |
FileHeader |
| 1176 |
: g_sdt_lit |
| 1177 |
; |
| 1178 |
|
| 1179 |
SyntaxProdList |
| 1180 |
: SyntaxProduction |
| 1181 |
| SyntaxProdList SyntaxProduction |
| 1182 |
; |
| 1183 |
\end{Verbatim} |
| 1184 |
|
| 1185 |
Syntax productions define a context free language and may be mutually and self recursive. Left recursion is preferable to right recursion in LR grammar productions, as this leads to less stack activity during parsing. A syntax production starts with an identifier, followed by \verb|":"| and one or more alternative bodies, which are separated by \verb+"|"+. |
| 1186 |
|
| 1187 |
Syntax production identifiers start with an upper case character in the range \verb|'A'-'Z'|. |
| 1188 |
|
| 1189 |
\begin{Verbatim}[frame=single] |
| 1190 |
SyntaxProduction |
| 1191 |
: prodId ":" Alternatives ";" |
| 1192 |
; |
| 1193 |
|
| 1194 |
prodId |
| 1195 |
: _upcase {_id_char} |
| 1196 |
; |
| 1197 |
|
| 1198 |
Alternatives |
| 1199 |
: SyntaxBody |
| 1200 |
| Alternatives "|" SyntaxBody |
| 1201 |
; |
| 1202 |
\end{Verbatim} |
| 1203 |
|
| 1204 |
A syntax body is a sequence of syntax symbols, optionally followed by an action literal. If a syntax body starts with the keyword, \verb|error|, it indicates that the parser may accept an error in the input of the production and continue parsing if it is able to recover from the error. |
| 1205 |
|
| 1206 |
A syntax body may also be empty, indicated by the reserved word, \verb|empty|. This allows you to write productions with optional elements, such as: |
| 1207 |
|
| 1208 |
\begin{verbatim} |
| 1209 |
A : B "c"; |
| 1210 |
B : "b" | empty; |
| 1211 |
\end{verbatim} |
| 1212 |
|
| 1213 |
This grammar will match strings, \verb|b c| or \verb|c|. |
| 1214 |
|
| 1215 |
\begin{Verbatim}[frame=single] |
| 1216 |
SyntaxBody |
| 1217 |
: Symbols |
| 1218 |
| Symbols g_sdt_lit |
| 1219 |
| "error" |
| 1220 |
| "error" Symbols |
| 1221 |
| "error" Symbols g_sdt_lit |
| 1222 |
| "empty" |
| 1223 |
; |
| 1224 |
|
| 1225 |
Symbols |
| 1226 |
: Symbol |
| 1227 |
| Symbols Symbol |
| 1228 |
; |
| 1229 |
\end{Verbatim} |
| 1230 |
|
| 1231 |
An action literal is any string of characters enclosed in \verb|"<<"| \verb|">>"|. The contents of the action literal is invoke as an expression when the associated production body has been recognised by the parser. The action expression must return a tuple of type \verb| (interface{}, error)|. If the second parameter is not \verb|nil| the parser terminates and returns the error to its caller. If the second parameter is \verb|nil| the parser associates first parameter with the recognise syntax production as its attribute. |
| 1232 |
|
| 1233 |
\begin{Verbatim}[frame=single] |
| 1234 |
g_sdt_lit |
| 1235 |
: '<' '<' . {.} '>' '>' |
| 1236 |
; |
| 1237 |
\end{Verbatim} |
| 1238 |
|
| 1239 |
gocc recognises the following terminal syntax symbols: |
| 1240 |
|
| 1241 |
\begin{longtable}{ll} |
| 1242 |
\verb|prodId| & The identifier of a syntax production defined in the grammar. \\ |
| 1243 |
\verb|tokId| & The identifier of lexical production defined in the grammar. \\ |
| 1244 |
\verb|string_lit| & A string literal value, e.g.: \verb|"a string"| \\ |
| 1245 |
\end{longtable} |
| 1246 |
|
| 1247 |
\begin{Verbatim}[frame=single] |
| 1248 |
Symbol |
| 1249 |
: prodId |
| 1250 |
| tokId |
| 1251 |
| string_lit |
| 1252 |
; |
| 1253 |
\end{Verbatim} |
| 1254 |
|
| 1255 |
A string literal can be any valid go raw string (e.g.: \verb|`a raw string`|) or interpreted string (e.g.: \verb|"an interpreted string"|). |
| 1256 |
|
| 1257 |
\begin{Verbatim}[frame=single] |
| 1258 |
string_lit |
| 1259 |
: _raw_string |
| 1260 |
| _interpreted_string |
| 1261 |
; |
| 1262 |
|
| 1263 |
_raw_string |
| 1264 |
: '`' {.} '`' |
| 1265 |
; |
| 1266 |
|
| 1267 |
_interpreted_string |
| 1268 |
: '"' { _unicode_value | _byte_value } '"' |
| 1269 |
; |
| 1270 |
\end{Verbatim} |
| 1271 |
|
| 1272 |
|
| 1273 |
|
| 1274 |
|
| 1275 |
\nocite{Parsing, Modern Compiler Design, Dragon Book, ABNF} |
| 1276 |
\begin{thebibliography}{99} |
| 1277 |
\bibitem{Parsing} |
| 1278 |
Dick Grune and Ceriel J.H. Jacobs. |
| 1279 |
\newblock {\em Parsing Techniques. A Practical Guide. Second Edition}. |
| 1280 |
\newblock Monographs in Computer Science, Springer, 2008 |
| 1281 |
|
| 1282 |
\bibitem{Modern Compiler Design} |
| 1283 |
Dick Grune, Kees van Reeuwijk, Henri E. Bal, Ceriel J.H. Jacobs and Koen Langendoen. |
| 1284 |
\newblock {\em Modern Compiler Design. Second Edition}. |
| 1285 |
\newblock Springer 2012 |
| 1286 |
|
| 1287 |
\bibitem{Dragon Book} |
| 1288 |
Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman. |
| 1289 |
\newblock {\em Compilers. Principles, Techniques, \& Tools. Second Edition}. |
| 1290 |
\newblock Addison Wesley, 2007 |
| 1291 |
|
| 1292 |
\bibitem{ABNF} |
| 1293 |
D. Crocker, Ed. |
| 1294 |
\newblock{\em Augmented BNF for Syntax Specifications: ABNF} |
| 1295 |
\newblock RFC 5234, January 2008 |
| 1296 |
|
| 1297 |
\bibitem{gospec} |
| 1298 |
{\em The Go Language Specification} |
| 1299 |
\newblock \url{http://golang.org/ref/spec} |
| 1300 |
|
| 1301 |
|
| 1302 |
\end{thebibliography} |
| 1303 |
|
| 1304 |
|
| 1305 |
\end{document} |