Table Of ContentVerificación de algoritmos y
estructuras de datos en Dafny
Verifying Algorithms and Data Structures in Dafny
Rubén Rafael Rubio Cuéllar
Doble Grado en Ingeniería Informática y Matemáticas
Departamento de Sistemas Informáticos y Computación
Facultad de Informática
Universidad Complutense de Madrid
Trabajo de fin de grado
Madrid, 17 de junio de 2016
Directores:
Narciso Martí Oliet
Isabel Pita Andreu
Alberto Verdejo López
«WhenApollowaspursuingthevirginDaphne,
daughteroftheriverPeneus,shebeggedfor
protectionfromEarth,whoreceivedher,and
changedherintoalaureltree. Apollobrokea
branchfromitandplaceditonhishead.»
—Fabulæ,CaiusJuliusHyginus(64a.C.–17)
The additional material, including the source code of the Dafny programs that have been
developed,isavailableintheattachedCDandinhttps://github.com/ningit/vaed.
This work is licensed under the Creative Commons Attribution-ShareAlike
4.0 International License. To view a copy of this license, visit http://
creativecommons.org/licenses/by-sa/4.0/.
TheassociatedcodeislicensedundertheGNUGeneralPublicLicence3. Visit
http://www.gnu.org/copyleft/gpl.htmltogetacopyofthislicence.
AUTORIZACIÓNPARALADIFUSIÓNDELTRABAJOFINDEGRADOYSUDEPÓSITOENEL
REPOSITORIOINSTITUCIONALE-PRINTSCOMPLUTENSE
Losabajofirmantes,alumnoytutoresdelTrabajoFindeGrado(TFG)enelDobleGradoenIngeniería
Informática y Matemáticas de la Facultad de Informática, autorizan a la Universidad Complutense de
Madrid(UCM)adifundiryutilizarconfinesacadémicos,nocomercialesymencionandoexpresamente
a su autor el Trabajo Fin de Grado (TFG) cuyos datos se detallan a continuación. Así mismo autorizan
a la Universidad Complutense de Madrid a que sea depositado en acceso abierto en el repositorio in-
stitucional con el objeto de incrementar la difusión, uso e impacto del TFG en Internet y garantizar su
preservaciónyaccesoalargoplazo.
TÍTULOdelTFG:VerificacióndealgoritmosyestructurasdedatosenDafny
Cursoacadémico: 2015/2016
Nombredelalumno:
RubénRafaelRubioCuéllar
TutoresdelTFGydepartamentoalquepertenece:
NarcisoMartíOliet
IsabelPitaAndreu
AlbertoVerdejoLópez
(DepartamentodeSistemasInformáticasyComputación)
Firmadelalumno Firmadelostutores
Contents
Listoffigures iii
Resumen/Abstract v
1 Introduction 1
1.1 Thefoundations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Automaticprogramverification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Workplan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 TheDafnysystem 5
2.1 Briefdescriptionoftheverificationarchitecture . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Languagesyntaxandsemanticsoverview . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 Documentationandreferenceresources . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.4 Dafnyconfigurationandoptionsusedinthisproject . . . . . . . . . . . . . . . . . . . . . 10
2.5 Auxiliarytoolswehavedeveloped . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3 Verifyingiterativeandrecursiveprograms 13
3.1 Initialdifficulties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 Otherfeaturesworthmentioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.1 Calculations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.2 Reductioadabsurdum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2.3 Incrementalprogramandproofbuilding. . . . . . . . . . . . . . . . . . . . . . . . 19
3.2.4 Matchingtriggers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.2.5 Functionaltypesandgenerics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2.6 Automatedinduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3 Adetailedexample:Euclideanalgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.4 Anexampleindepth:limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4 Datastructures 29
4.1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.1 Class,traitsandgenerics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.1.2 Dynamicframes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
i
ii CONTENTS
4.1.3 Inductivedatatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.1.4 Modulesandrefinement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.2 Datastructuresrepresentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.2.1 Allocatedmemoryanddynamicframes . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2.2 Collectionsandgenerics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2.3 Autocontracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.3 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.5 Binaryheaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5 Algorithms 45
5.1 Floyd-Warshallalgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.1.1 Specificationoutline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.1.2 Verificationoutline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.1.3 UsingthealgorithmfromC# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.2 Dijkstra’salgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
6 Conclusions 53
7 Conclusiones 55
A Dafnyprogramexamples 57
A.1 Aniterativeandrecursivebinarysearch:er5.12.dfy . . . . . . . . . . . . . . . . . . . . . 57
A.2 Euclideanalgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
A.2.1 er2.11.dfy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
A.2.2 aritmnl.dfy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
A.3 Sinecalculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
A.3.1 er4.4.dfy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
A.3.2 er4.4aux.dfy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
A.4 Floyd-Warshallalgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
A.5 Dijkstra’salgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
B Attachedmaterial 93
Bibliography 95
Index 97
List of Figures
1.1 “Flowchartofprogramtocompute𝑆 =∑𝑛𝑗=1𝑎𝑗 (𝑛≥0)”from[Flo67] . . . . . . . . . . . 2
2.1 VisualStudioDafnyextensionandBoogieVerificationDebugger . . . . . . . . . . . . . . 6
2.2 EmacsDafnymode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Dafnysystemarchitecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Dafnyconsolebeautifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.1 Abstractionfunctionandrepresentationinvariant,forADTdescribedinSection4.5 . . . 32
4.2 Stackexamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.3 ClassStacknodesillustration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.4 Listillustration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.5 Binaryheapillustration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
5.1 Examplegraphwithitsresult(map2.txt) . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.2 Dijkstra’snodesillustration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
iii
iv LISTOFFIGURES
Resumen
La verificación formal de un programa es la demostración de que este funciona de acuerdo a una
descripción del comportamiento esperado en toda posible ejecución. La especificación de lo deseado
puedeutilizartécnicasdiversasyentrarenmayoromenordetalle,peroparaganarseeltítulodeformal
estahadesermatemáticamenterigurosa.
Elestudioyejerciciomanualdealgunadeesastécnicasformapartedelcurrículocomúnalosestudios
degradodelaFacultaddeInformáticaydelitinerariodeCienciasdelaComputacióndelaFacultadde
CienciasMatemáticasdelaUniversidadComplutensedeMadrid,comoeselcasodelaverificacióncon
pre-ypostcondicionesológicadeHoare.
Enelpresentetrabajoseexploralaautomatizacióndeestosmétodosmedianteellenguajeyverifica-
dorDafny,conelqueseespecificanyverificanalgoritmosyestructurasdedatosdediversacomplejidad.
Dafny es un lenguaje de programación diseñado para integrar la especificación y permitir la verifi-
cación automática de sus programas, con la ayuda del programador y de un demostrador de teoremas
en la sombra. Dafny es un proyecto en desarrollo activo aunque suficientemente maduro, que genera
programasejecutables.
Palabras claves: algoritmos, estructuras de datos, especificación, verificación automática, lógica de
Hoare,Dafny
Abstract
Theformalverificationofaprogramistheproofthatitworksaccordingtoadescriptionofitsexpected
behaviour in any possible execution. The specification of what is desired can use different techniques
andgointomoreorlessdetail,buttowintheformaltitleitmustbemathematicallyrigorous.
The study and manual exercise of some of those techniques is part of the common curriculum of
the degree studies at the School of Computer Science and of the Computer Science itinerary at the
School of Mathematics at the Universidad Complutense de Madrid, such as verification with pre- and
postconditionsorHoarelogic.
In the current work, the automation of those methods is explored through the language and ver-
ifier Dafny, with has been used to specify and verify some algorithms and data structures of diverse
complexity.
Dafny is a programming language designed to integrate specification and allow automatic verifica-
tion of its programs, with the help of the programmer and a theorem prover in the shade. Dafny is in
activedevelopmentbutmatureenoughanditgeneratesexecutableprograms.
Keywords: algorithms,datastructures,specification,automaticverification,Hoarelogic,Dafny
v
vi LISTOFFIGURES
Description:http://www.gnu.org/copyleft/gpl.html to get a copy of this licence. Madrid (UCM) a difundir y utilizar con fines académicos, no comerciales y .. El estudio y ejercicio manual de alguna de esas técnicas forma parte del currículo común a los .. The tool is able to generate a .pdf listing all Daf