




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































Series Editors
David Gries, Department of Computer Science, Cornell University, Ithaca, NY, USA Orit Hazzan, Faculty of Education in Technology and Science, Technion—Israel Institute of Technology, Haifa, Israel
Formal Languages
and Compilation
123
Stefano Crespi Reghizzi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano Milan, Italy
Luca Breveglieri Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano Milan, Italy
Angelo Morzenti Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano Milan, Italy
ISSN 1868-0941 ISSN 1868-095X (electronic) Texts in Computer Science ISBN 978-3-030-04878-5 ISBN 978-3-030-04879-2 (eBook) https://doi.org/10.1007/978-3-030-04879-
Library of Congress Control Number: 2018965427
1 st^ & 2nd^ editions: © Springer-Verlag London 2009, 2013 3 rd^ edition: © Springer Nature Switzerland AG 2019 This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, express or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.
This Springer imprint is published by the registered company Springer Nature Switzerland AG The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
advantage of the improvements and simplifications made possible by decades of both extensive use and theoretical polishing, to avoid the irritating variants and repetitions that are found in the historical fundamental papers. Moving from these premises, we decided to present, in a simple minimalist way, the principles and methods currently used in designing syntax-directed applications such as parsing and regular expression matching. Thus, we have substantially improved the stan- dard presentation of parsing algorithms for both regular expressions and grammars, by unifying the concepts and notations used in various approaches, and by extending method coverage with a reduced definitional apparatus. An example that expert readers should appreciate is the unification of top-down and bottom-up parsing algorithms within a new rigorous yet practical framework. In this way, the reduced effort and space needed to cover classical concepts has made room for new advanced methods typically not present in similar textbooks. First, we have introduced in this edition a new efficient algorithm for string matching using regular expressions, which are increasingly important in such applications as Web browsing and data filtering. Second, our presentation of parsing algorithms focuses on the more expressive extended BNF grammars, which are the de facto standard in language reference manuals. Third, we present a parallel parsing algorithm that takes advantage of the many processing units of modern multi-core devices to speed up the syntax analysis of large files. At last, we mention the addition in this edition of the recent formal models of input-driven automata and languages (also known as visibly pushdown model), which suits the mark-up languages (such as XML and JSON) and has been developed also in other domains to formally verify critical systems. The presentation is illustrated by many small yet realistic examples, to ease the understanding of the theory and the transfer to application. Theoretical models of automata, transducers, and formal grammars are extensively used, whenever practical motivations exist. Algorithms are described in a pseudo-code to avoid the disturbing details of a programming language, yet they are straightforward to convert into executable procedures, and for some, we have made available their code on the Web. The book is not restricted to syntax. The study of translations, semantic func- tions (attribute grammars), and static program analysis by data flow equations enlarges the understanding of the compilation process and covers the essentials of a syntax-directed translator. A large collection of problems and solutions is available at the authors’ course site. This book should be welcome by those willing to teach or learn the essential concepts of syntax-directed compilation, without needing to rely on software tools and implementations. We believe that learning by doing is not always the best approach and that an overcommitment to practical work may sometimes obscure the conceptual foundations. In the case of formal languages, the elegance and essentiality of the underlying theory allows students to acquire the fundamental paradigms of language structures, to avoid pitfalls such as ambiguity, and to ade- quately map structure to meaning. In this field, many if not all relevant algorithms
vi Preface
are simple enough to be practiced by paper and pencil. Of course, students should be encouraged to enroll in a hands-on laboratory and to experiment syntax-directed tools (like flex and bison) on realistic cases. The authors thank the colleagues Alessandro Barenghi and Marcello Bersani, who have taught compilers to computer engineering students by using this book. The first author remembers the late Antonio Grasselli, the computer science pioneer who first fascinated him with the subject of this book, combining linguistic, mathematical, and technological aspects.
Milan, Italy April 2019
Stefano Crespi Reghizzi Luca Breveglieri Angelo Morzenti
Preface vii
1
The information technology revolution was made possible by the invention of elec- tronic digital machines, yet without programming languages their use would have been restricted to the few people able to write binary machine code. A programming language as a text contains features coming both from human languages and from mathematical logic. The translation from a programming language to machine code is known as compilation.^1 Language compilation is a very complex process, which would be impossible to master without systematic design methods. Such methods and their theoretical foundations are the argument of this book. They make up a con- sistent and largely consolidated body of concepts and algorithms, which are applied not just in compilers, but also in other fields. Automata theory is pervasive in all the branches of informatics, to model situations or phenomena classifiable as time and space discrete systems. Formal grammars, on the other hand, are originated in linguistic research, and together with automata, they are widely applied in document processing and in data representation and searching, in particular for the Web. Coming to the prerequisites, the reader should have a good background in pro- gramming, though a detailed knowledge of a specific programming language is not required, because our presentation of algorithms relies on self-explanatory pseudo- code. The reader is expected to be familiar with basic mathematical theories and notations, namely from set theory, algebra and logic. The above prerequisites are typically met by computer science/engineering or mathematics students with a uni- versity education of two or more years.
(^1) This term may sound strange; it originates in the early approach to the compilation of correspon-
dence tables between a command in the language and a series of machine operations.
© Springer Nature Switzerland AG 2019 S. Crespi Reghizzi et al., Formal Languages and Compilation , Texts in Computer Science, https://doi.org/10.1007/978-3-030-04879-2_
1
1.2 Compiler Parts and Corresponding Concepts 3
and at the end it rejects or accepts the input depending on the result of the analysis. By a minimalist abstract approach, such recognition algorithms are conveniently described as mathematical machines or automata, in the tradition of the well-known Turing machine. Different automaton types correspond to the various families of formal languages, and the types practically relevant for compilation are considered in the following two chapters. Chapter 3 covers finite automata, which are machines with a finite random access memory. They are the recognizers of the languages defined by regular expressions. Within compilation, they are used for lexical analysis or scanning, to extract from the source text the keywords, numbers, identifiers and in general the pieces of text that encode the lexical units of the language, called lexemes or tokens. The basic models of finite automata, deterministic and nondeterministic, real-time and with spontaneous moves are presented along with the transformations between different models. The algorithms for converting a finite automaton into a regular expression and conversely are well covered. The other main topics of Chap. 3 are: the string matching problem for ambiguous regular expressions, and the use of Boolean operations, intersection and complement, in the regular expressions. Chapter 4 is devoted to the recognition problem for the languages defined by context-free grammars, which is the backbone of syntax-directed translators and justifies the salient length of the chapter. The chapter starts with the model of nondeterministic pushdown automata and its direct correspondence to context-free grammars. The deterministic version of the model follows, which defines the leading family of deterministic languages. As a special case, the input-driven or visibly pushdown automata have been included, because of their relevance for markup languages such as XML and JSON. A rich choice of parsing algorithms is presented. First, there is a unified modern presentation of the deterministic parsers, both bottom-up (or LR ( 1 )) and top-down (or LL ( 1 )), for context-free grammars extended with regular languages. The third deterministic parser is the operator-precedence method, which is here presented in the parallel version suitable for multi-core computers. The last parsing method by Earley is the most general and accepts any context-free language. Chapter 4 includes comparisons of the different language families suitable for each parsing method, a discussion of grammar transformations, and the basic concepts on error handling by parsers. The ultimate job of a compiler is to translate a source text into another language. The compiler module responsible for finalizing the verification of the source language rules and for producing the translation is called the semantic analyzer. It operates on the structural representation, the syntax tree, produced by the parser. The formal translation models and the methods used to implement semantic ana- lyzers are illustrated in Chap. 5. Actually, we describe two kinds of transformations. First, the pure syntactic translations are modeled by transducers that are either finite automata or pushdown automata extended with an output, and that compute a string. Second, the semantic translations are performed by functions or methods that oper- ate on the syntax tree of the source text and may produce as output not just a string, but any sort of data values. Semantic translations are specified by a practical semi- formal extension to context-free grammars, which is called attribute grammar. This
4 1 Introduction
approach, by combining the accuracy of formal syntax and the flexibility of pro- gramming, conveniently expresses the typical analysis and transformation of syntax trees that is required by compilers. To give a concrete idea of compilation, typical simple examples are included: the type consistency check between the variables declared and used in a program- ming language, the translation of high-level statements into machine instructions and semantics-directed parsing. For sure, compilers do much more than syntax-directed translation. Static program analysis is an important example: it consists in examining a program to determine, ahead of execution, some properties, or to detect errors not detected by syntactic and semantic analysis. The purpose is to improve the robustness, reliability and efficiency of the program. An example of error detection is the identification of uninitialized variables used in the arithmetic expressions. For code improvement, an example is the elimination of useless assignment statements. Chapter 5 terminates with an introduction to the static analysis of programs mod- eled by their control-flow graph, viewed as a finite automaton. Several interesting problems can be formalized and statically analyzed by a common approach based on flow equations and their solution by iterative approximations converging to the least fixed point. Last, the book comes with an up-to-date essential bibliography at the end of each chapter and is accompanied by a detailed index.
6 2 Syntax
other words, it should be possible for a computer to check that the sentences are grammatically correct, and to determine their meaning. Meaning, however, is a difficult and controversial notion. For our purposes, the meaning of a sentence can be taken to be the translation into another language, which is known to the computer or to a well-established software system. For instance, the meaning of a Java program is its translation into the machine language of the computer executing the program. In this book, the term formal language is used in a narrower sense, which excludes semantics. In the field of syntax, a formal language is a mathematical structure, defined on top of an alphabet, by means of certain axiomatic rules (formal grammar) or by using abstract machines such as the famous one due to A. Turing. The notions and methods of formal language are analogous to those used in number theory and in logic. Thus, formal language theory is primarily concerned with the form or syntax of sentences, not with meaning, at least not directly. A string (or text) is either valid or illegal, that is, it either belongs to the formal language or it does not. Such a theory makes a first important step toward the ultimate goal: the study of language translation and meaning, which will however require additional methods.
In this book, a language is a one-dimensional communication medium, made by sequences of symbolic elements of an alphabet, called terminal characters. Actually, people often refer to language as other non-textual communication media, which are more or less formalized by means of rules. Thus, iconic languages focus on road traf- fic signs or video display icons. Musical language is concerned with sounds, rhythm, and harmony. Architects and industrial designers of buildings and things are inter- ested in their spatial relations, which they describe as the language of design. Early child drawings are often considered as sentences of a pictorial language, which can be partially formalized in accordance with developmental psychology theories. Cer- tainly, the formal approach to syntax to be developed has some interest for nontextual languages too, which however are out of scope for this book. Within computer science, the term language applies, as said, to a text made by a set of characters orderly written from, say, left to right. In addition, the term is used to refer to other discrete structures, such as graphs, trees, or arrays of pixels describing a digital picture. Formal language theories have been proposed and used more or less successfully also for such nontextual languages.^2 Reverting to the main stream of textual languages, a frequent request directed to the specialist is to define and specify an artificial language. The specification may have several uses: as a language reference manual for future users, as an official
(^2) Just three examples and their references: graph grammars and languages [2], tree languages [3,4], and picture (or two-dimensional) languages [5,6].
2.1 Introduction 7
standard definition, or as a contractual document for compiler designers to ensure consistency of specification and implementation. It is not an easy task to write a complete and rigorous definition of a language. Of course, the exhaustive approach, to list all the possible sentences or phrases, is unfea- sible because the possibilities are infinitely many, since the length of the sentences is usually unbounded. As a native language speaker, a programmer is not constrained by any strict limit on the length of the phrases he writes. The ensuing problem to represent an infinite number of cases by a finite description can be addressed by an enumeration procedure, as in logic. When executed, the procedure generates longer and longer sentences, in an unending process if the language to be modeled is not finite. This chapter presents a simple and established manner to express the rules of the enumeration procedure in the form of rules of a generative grammar (or syntax).
The chapter starts with the basic components of language theory: alphabet, string, and operations, such as concatenation and repetition, on strings and sets of strings. The first model presented are the regular expressions, which define the family of regular languages. Then the lists are introduced as a fundamental and pervasive syntax structure in all the kinds of languages. From the exemplification of list variants, the idea of linguistic abstraction grows out naturally. This is a powerful reasoning tool to reduce the varieties of existing languages to a few paradigms. After discussing the limits of regular languages, the chapter moves to context-free grammars. Following the basic definitions, the presentation focuses on structural properties, namely equivalence, ambiguity, and recursion. Exemplifica- tion continues with important linguistic paradigms such as hierarchical lists, paren- thesized structures, polish notations, and operator precedence expressions. Their combination produces the variety of forms to be found in artificial languages. Then the classification of some common forms of ambiguity and corresponding remedies is offered as a practical guide for grammar designers. Various rule transformations (normal forms) are introduced, which should famil- iarize the reader with the modifications, to adjust a grammar without affecting the language, often needed for the analysis algorithms studied in Chap. 4. Returning to regular languages from the grammar perspective, the chapter evi- dences the greater descriptive capacity of context-free grammars. The comparison of regular and context-free languages continues by considering the operations that may cause a language to exit or remain in one or the other family. Alphabetical transformations anticipate the operations studied in Chap. 5 as translations. A dis- cussion about the unavoidable regularities found in very long strings completes the theoretical picture. The last section mentions the Chomsky classification of grammar types and exem- plifies context-sensitive grammars, stressing the difficulty of such rarely used model and discussing some recent attempts at more expressive grammar models.