on master help sign in
Merge upstream
commit865343d7b00265557503cba230d26fec3fdf2e3b authorKyarigwo <bwielinga@iprimus.com.au> dateWed 11 Jan 2017, 19:16 (10 years ago) parent717e854a308de2
155 files changed+2852−1519
.travis.yml+9−3 CHANGELOG.md+40−1 CONTRIBUTORS+200−40 docs/conf.py+3−3 docs/listing/idris-prompt-helloworld.txt+1−1 docs/listing/idris-prompt-interp.txt+1−1 docs/listing/idris-prompt-start.txt+1−1 docs/reference/compilation.rst+23−7 docs/reference/documenting.rst+8−1 docs/reference/misc.rst+1−1 docs/reference/packages.rst+8−1 docs/tutorial/index.rst−1 docs/tutorial/packages.rst+101−15 docs/tutorial/syntax.rst+1−1 docs/tutorial/testing.rst−85 idris.cabal+9−2 libs/base/Control/Isomorphism.idr+5 libs/base/Data/Complex.idr+11−3 libs/base/Data/List/Views.idr+1−3 libs/base/Data/String/Views.idr+2 libs/base/Debug/Error.idr+3−6 libs/base/System.idr+35−4 libs/contrib/CFFI/Types.idr+3−1 libs/effects/Effect/Exception.idr+1−2 libs/prelude/Builtins.idr+7 libs/prelude/Prelude.idr+11−3 libs/prelude/Prelude/Nat.idr+13−8 libs/prelude/Prelude/Strings.idr+19−14 libs/pruviloj/Pruviloj/Induction.idr+3−1 main/Main.hs+16−4 man/idris.1+16−2 mkpkg.sh+44−6 rts/idris_bitstring.c+8−8 rts/idris_gmp.c+1−1 rts/idris_gmp.h+1−1 rts/idris_rts.c+24−19 rts/idris_rts.h+13−10 src/IRTS/CodegenC.hs+2−1 src/IRTS/Compiler.hs+15−5 src/IRTS/Lang.hs+2 src/IRTS/Portable.hs+4−4 src/IRTS/System.hs+6−1 src/Idris/ASTUtils.hs+1−1 src/Idris/AbsSyntax.hs+54−44 src/Idris/AbsSyntaxTree.hs+48−27 src/Idris/Apropos.hs+2−2 src/Idris/CaseSplit.hs+4−4 src/Idris/CmdOptions.hs+3−1 src/Idris/Core/Binary.hs+31−11 src/Idris/Core/CaseTree.hs+63−7 src/Idris/Core/DeepSeq.hs+1 src/Idris/Core/Elaborate.hs+39−36 src/Idris/Core/Evaluate.hs+129−77 src/Idris/Core/Execute.hs+5−4 src/Idris/Core/ProofState.hs+75−60 src/Idris/Core/ProofTerm.hs+11−11 src/Idris/Core/TT.hs+113−53 src/Idris/Core/Typecheck.hs+142−103 src/Idris/Core/Unify.hs+40−40 src/Idris/Core/WHNF.hs+70−25 src/Idris/Coverage.hs+302−256 src/Idris/DataOpts.hs+1−1 src/Idris/Delaborate.hs+21−20 src/Idris/Docs.hs+3−3 src/Idris/Elab/Clause.hs+70−34 src/Idris/Elab/Data.hs+8−4 src/Idris/Elab/Implementation.hs+6−6 src/Idris/Elab/Interface.hs+8−8 src/Idris/Elab/Record.hs+4−4 src/Idris/Elab/Rewrite.hs+7−7 src/Idris/Elab/Term.hs+146−101 src/Idris/Elab/Transform.hs+3−3 src/Idris/Elab/Type.hs+9−4 src/Idris/Elab/Utils.hs+66−33 src/Idris/ElabDecls.hs+13−8 src/Idris/Erasure.hs+7−7 src/Idris/ErrReverse.hs+2−2 src/Idris/Error.hs+6 src/Idris/IBC.hs+29−17 src/Idris/IdrisDoc.hs+2−2 src/Idris/Info.hs+5 src/Idris/Interactive.hs+8−8 src/Idris/Main.hs+5−2 src/Idris/Package.hs+42−37 src/Idris/Parser.hs+15−8 src/Idris/Parser/Expr.hs+31−27 src/Idris/Parser/Helpers.hs+3−3 src/Idris/PartialEval.hs+14−14 src/Idris/Primitives.hs+5−5 src/Idris/ProofSearch.hs+8−8 src/Idris/Prover.hs+12−12 src/Idris/REPL.hs+25−15 src/Idris/REPL/Commands.hs+1 src/Idris/REPL/Parser.hs+8−1 src/Idris/Reflection.hs+20−13 src/Idris/Termination.hs+10−10 src/Idris/Transforms.hs+2−2 src/Idris/TypeSearch.hs+4−4 stack-shell.nix+1−1 stack.yaml+2−2 test/TestData.hs+6−3 test/TestRun.hs+14−8 test/basic018/expected+1−1 test/basic019/basic019.idr+10 test/basic019/expected+12 test/basic019/run+4 test/dsl001/expected+4−4 test/dsl001/input+1−1 test/dsl001/test001.idr+2 test/dsl002/Resimp.idr+1 test/dsl003/DSLPi.idr+2 test/dsl004/Door0.idr+3−1 test/dsl004/Door1.idr+2 test/dsl004/Door2.idr+2 test/dsl004/Door3.idr+2 test/dsl004/IOu.idr+2 test/interactive010/expected+2−2 test/meta001/Finite.idr+2 test/meta002/AgdaStyleReflection.idr+1−1 test/meta002/DataDef.idr+2 test/meta002/Deriving.idr+2 test/meta002/Tacs.idr+1 test/meta002/expected+2−2 test/meta003/BadDef.idr+2 test/meta003/expected+1−1 test/meta004/expected+1−1 test/meta004/meta004.idr+2 test/pkg008/expected+13 test/pkg008/maths.ipkg+9 test/pkg008/run+9 test/pkg008/src/NumOps.idr+9 test/pkg008/src/Test.idr+21 test/proof002/Reflect.idr+1 test/proof002/expected+3−3 test/pruviloj001/pruviloj001.idr+1 test/regression001/coverage001.idr+79 test/regression001/eff001.idr+39 test/regression001/run+5−1 test/sourceLocation001/SourceLoc.idr+1 test/sourceLocation001/expected+8−8 test/tactics001/Tactics.idr+5−3 test/totality019/expected+2 test/totality019/run+4 test/totality019/totality019.idr+14 test/totality019/totality019a.idr+81 test/unique001/unique001.idr+2 test/unique004/expected+10−10 test/unique004/unique001a.idr+2 test/unique004/unique001b.idr+2 test/unique004/unique001c.idr+1 test/unique004/unique001d.idr+1 test/unique004/unique001e.idr+1 test/unique004/unique002.idr+2 test/unique004/unique002a.idr+2 test/unique004/unique003.idr+2
.travis.yml+9−3
@@ -35,6 +35,11 @@ matrix:
3535 - env: CABALVER="1.24" GHCVER="8.0.1" TESTS="test_c"
3636 compiler: ": #GHC 8.0.1"
3737 addons: {apt: {packages: [cabal-install-1.24,ghc-8.0.1,cppcheck,hscolour], sources: [hvr-ghc]}}
38+ allow_failures:
39+ - os: osx
40+ env: CABALVER="1.24" GHCVER="8.0.1" TESTS="test_c"
41+ compiler: ": #GHC 8.0.1"
42+ fast-finish: true
3843
3944cache:
4045 directories:
@@ -56,9 +61,8 @@ before_install:
5661 - env
5762 - if [[ $TRAVIS_OS_NAME == 'osx' ]];
5863 then
59− brew update; brew install ghc; brew install cabal-install;
60− brew install libffi; brew install pkg-config; brew install cppcheck;
61− brew install gnu-sed;
64+ brew outdated pkgconfig || brew install pkgconfig;
65+ brew install ghc cabal-install libffi cppcheck gnu-sed;
6266 export PATH=$HOME/.cabal/bin:$PATH;
6367 export SED=gsed;
6468 export ZCAT=gzcat;
@@ -66,6 +70,8 @@ before_install:
6670 fi
6771
6872install:
73+ - which cabal
74+ - which ghc
6975 - cabal --version
7076 - echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]"
7177 - if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ];
CHANGELOG.md+40−1
@@ -1,4 +1,42 @@
1−# New in 0.13:
1+# New in 0.99.1:
2+
3+## Language updates
4+
5+* Language pragmas now required for the less stable existing features, in
6+ addition to the existing `TypeProviders` and `ErrorReflection`:
7+ + `ElabReflection`, which must be enabled to use `%runElab`
8+ + `UniquenessTypes`, which must be enabled to use `UniqueType`
9+ + `DSLNotation`, which must be enabled to define a `dsl` block
10+ + `FirstClassReflection`, which must be enabled to define a `%reflection`
11+ function
12+
13+* New language extension `LinearTypes`:
14+ + This allows adding a /multiplicity/ to a binder which says how often it
15+ is allowed to be used; either 0 or 1 (if unstated, multiplicity is "many")
16+ + The typing rules follow Conor McBride's paper "I Got Plenty o' Nuttin'"
17+ + This is highly experimental, unfinished, not at all polished. and there
18+ are still lots of details to sort out. Some features don't quite work
19+ properly yet. But it is there to play with for the brave!
20+
21+## Tool Updates
22+
23++ Idris' output has been updated to more accurately reflect its
24+ progress through the compiler i.e. Type Checking; Totality Checking;
25+ IBC Generation; Compiling; and Code Generation. To control the
26+ loudness of the reporting three verbosity levels are introduced:
27+ `--V0`, `--V1`, and `--V2`. The old aliases of `-V` and `--verbose`
28+ persist.
29+
30+## Library Updates
31+
32++ Terminating programs has been improved with more appropriate
33+ functions (`exitWith`, `exitFailure`, and `exitSuccess`) and a data
34+ structure (`ExitCode`) to capture a program's return code.
35+
36++ Casting a `String` to an `Int`, `Integer` or a `Double` now ignores leading
37+ and trailing whitespace. Previously only leading whitespace was ignored.
38+
39+# New in 0.99:
240
341## Language updates
442
@@ -62,6 +100,7 @@
62100
63101## Miscellaneous updates
64102
103+* New, faster, better, implementation of the coverage checker
65104* The test suite now uses [tasty-golden](https://hackage.haskell.org/package/tasty-golden). New tests must be registered in `test/TestData.hs`, as explained in the relevant `README.md`.
66105* Added OSX and Windows continous integration with Travis and Appveyor.
67106
CONTRIBUTORS+200−40
@@ -1,56 +1,216 @@
11Thanks to the following for their help and contributions:
22
3−Ozgur Akgun
3+a3gis
4+Aaron Craelius
5+Adam Sandberg Eriksson
6+Adam Schønemann
7+Adolfo Ochagavía
48Ahmad Salim Al-Sibahi
5−Edward Chadwick Amsden
6−Michael R. Bernstein
7−Jan Bessai
8−Nicola Botta
9−Edwin Brady
10−Vitaly Bragilevsky
11−Jakob Brünker
9+Aistis Raulinaitis
10+Alex Feldman-Crough
11+Alexander Berntsen
12+Alexander Shabalin
1213Alyssa Carter
14+Andreas Bogk
15+Andreas Reuleaux
16+Andrei Dziahel
17+Andrew Cann
18+Andrew Stewart Gibson
19+Andy Morris
20+Anthony Cantor
21+Anthony---faineance
22+Apostolis Xekoukoulotakis
23+Athan Clark
24+Bartosz Przygoda
25+Ben Gamari
26+Ben Sherman
27+ben-schulz
28+Benjamin Hodgson
29+Benjamin Saunders
30+Björn Aili
31+bmastenbrook
32+Brent Yorgey
33+Brian Koropoff
34+Brian McKenna
35+Bryn Keller
36+Calvin Beck
37+Carsten König
1338Carter Charbonneau
39+Casper M. H. Holmgreen
40+cchantep
41+Cezar Ionescu
42+Chao-Hong Chen
43+Chetan Taralekar
44+Chris Allen
45+Christopher Schwaab
46+Cliff Harvey
47+Cliff L. Biffle
48+Colin Adams
49+comco
50+Craig McLaughlin
51+cswords
52+Daniel Waterworth
53+Daniël Heres
54+Darin Morrison
55+David Feuer
56+David Kraeutmann
1457David Raymond Christiansen
15−Aaron Craelius
16−Jason Dagit
17−Adam Sandberg Eriksson
18−Guglielmo Fachini
19−Simon Fowler
58+defanor
59+Dennis Griffith
60+Dirk Ullrich
61+Dmitry Bushev
62+Dmitry Tsygankov
63+Dominic Mulligan
64+Dominik Peteler
65+Echo Nolan
66+Eduard Nicodei
67+Edward Amsden
68+Edward O'Callaghan
69+Edwin Brady
70+Eric Casteleijn
71+Eric Mertens
72+Eric Walkingshaw
73+Eric Weinstein
74+Erkin Batu Altunbaş
75+Ertugrul Söylemez
76+EvanR
77+Fabian Thorand
78+fiendfan1
79+Franklin Chen
80+Frederic Koehler
81+Friedrich von Never
82+Gabe McArthur
83+Gabor Greif
84+Gabriel Garcia
85+George Leontiev
86+Gleb Alexeyev
2087Google
21−Zack Grannan
22−Sean Hunt
23−Cezar Ionescu
88+Greg Anderson
89+Greg Pfeil
90+Guglielmo Fachini
91+Hannes Mehnert
2492Heath Johns
93+Heather
94+Hector A. Escobedo IV
95+identical snowflake
96+Ignas Vyšniauskas
97+Ilan Godik
98+Imuli
2599Irene Knapp
26−Paul Koerbitz
27−Niklas Larsson
28−Shea Levy
100+Jack Henahan
101+Jacob Mitchell
102+Jakob Brünker
103+Jan Bessai
104+Jan de Muijnck-Hughes
105+Jan Doms
106+Jan Stolarek
107+Jason Dagit
108+Jason Gross
109+Jean-Remi Desjardins
110+Jeff Hemphill
111+Jefferson Carpenter
112+Jens Petersen
113+Jeremy W. Sherman
114+jhegedus42
115+joe9
116+Johannes Griebler
117+John Connor
118+John Dobronszki
119+John Wiegley
120+Jon Atack
121+Jonas Westerlund
122+Jonathan Sterling
123+Joseph Huang
124+Josh Vera
125+JP Smith
126+Juliusz Chroboczek
127+Jurriën Stutterheim
128+Jürgen Peters
129+Karlos Kaeeikaas
130+Kester Tong
131+lambdadomain
132+Langston Barrett
133+Leif Warner
134+Leon Schoorl
135+Luke Palmer
136+Mark Farrell
137+Markus Klink
138+Markus Pfeiffer
29139Mathnerd314
30−Hannes Mehnert
140+Mattias Lundell
141+Matvey B. Aksenov
142+Matúš Tejiščák
143+Maxim Ivanov
31144Mekeor Melire
32145Melissa Mozifian
33−Jan de Muijnck-Hughes
34−Dominic Mulligan
35−Echo Nolan
36−Tom Prince
37−raichoo
146+Melvar Chen
147+Michael A. Smith
148+Michael Bernstein
149+Michael Gilliland
150+Michael Hensler
151+Michael Maloney
152+Michael McGirr
153+Michael Thompson
154+Michael Weiss
155+Miikka Koskinen
156+Mitchell Rosen
157+Miëtek Bak
158+Mort Yao
159+Nathan Dinsmore
160+Nicola Botta
161+Niklas Larsson
162+Norbert Melzer
163+Oskar Wickström
164+Ozgur Akgun
165+Patrik Jansson
166+Paul Koerbitz
167+Per Fredelius
168+Peter Minten
38169Philip Rasmussen
39−Aistis Raulinaitis
170+PoroCYon
171+raichoo
40172Reynir Reynisson
173+Ricky Elrod
174+Robert Clipsham
175+Robert Edström
176+Ross Meikleham
177+Ryan Scott
178+Sam Elliott
179+Sam T
180+Saurabh Rawat
181+Sean Hunt
182+Sebastian de Bellefon
183+Sebastian Dröge
41184Seo Sanghyeon
42−Benjamin Saunders
43−Alexander Shabalin
44−Jeremy W. Sherman
45−Timo Petteri Sinnemäki
46−JP Smith
185+Sergei Trofimovich
186+Shane Pearman
187+Shea Levy
188+Simon Fowler
47189startling
48−Chetan T
49−Matúš Tejiščák
50−Dirk Ullrich
51−Leif Warner
52−Daniel Waterworth
53−Eric Weinstein
54−Jonas Westerlund
55−Björn Aili
56−Zheng Jihui
190+Stefan Bleibinhaus
191+stepcut
192+Stephen Drodge
193+Steven Shaw
194+Stuart Gale
195+suhorng
196+Sune Alkærsig
197+Sven Koschnicke
198+tdidriksen
199+Tenor Biel
200+Thomas Cooper
201+Tim Dysinger
202+Tim McGilchrist
203+Timo Petteri Sinnemäki
204+Tom Prince
205+TorosFanny
206+Trevor Elliott
207+uwap
208+Vitaly Bragilevsky
209+Vyacheslav Shebanov
210+xged
211+XIE Yuheng
212+Yacine Hmito
213+Zack Grannan
214+Zheng Jihui
215+zjhmale
216+Сухарик
docs/conf.py+3−3
@@ -33,7 +33,7 @@ on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
3333# ones.
3434extensions = [
3535 'sphinx.ext.todo',
36− 'sphinx.ext.pngmath',
36+ 'sphinx.ext.pngmath', # imgmath is not supported on readthedocs.
3737 'sphinx.ext.ifconfig',
3838]
3939
@@ -59,9 +59,9 @@ author = u'The Idris Community'
5959# built documents.
6060#
6161# The short X.Y version.
62−version = '0.12.3'
62+version = '0.99'
6363# The full version, including alpha/beta/rc tags.
64−release = '0.12.3'
64+release = '0.99'
6565
6666# The language for content autogenerated by Sphinx. Refer to documentation
6767# for a list of supported languages.
docs/listing/idris-prompt-helloworld.txt+1−1
@@ -1,7 +1,7 @@
11$ idris hello.idr
22 ____ __ _
33 / _/___/ /____(_)____
4− / // __ / ___/ / ___/ Version 0.12.3
4+ / // __ / ___/ / ___/ Version 0.99
55 _/ // /_/ / / / (__ ) http://www.idris-lang.org/
66 /___/\__,_/_/ /_/____/ Type :? for help
77
docs/listing/idris-prompt-interp.txt+1−1
@@ -1,7 +1,7 @@
11$ idris interp.idr
22 ____ __ _
33 / _/___/ /____(_)____
4− / // __ / ___/ / ___/ Version 0.12.3
4+ / // __ / ___/ / ___/ Version 0.99
55 _/ // /_/ / / / (__ ) http://www.idris-lang.org/
66 /___/\__,_/_/ /_/____/ Type :? for help
77
docs/listing/idris-prompt-start.txt+1−1
@@ -1,7 +1,7 @@
11$ idris
22 ____ __ _
33 / _/___/ /____(_)____
4− / // __ / ___/ / ___/ Version 0.12.3
4+ / // __ / ___/ / ___/ Version 0.99
55 _/ // /_/ / / / (__ ) http://www.idris-lang.org/
66/___/\__,_/_/ /_/____/ Type :? for help
77
docs/reference/compilation.rst+23−7
@@ -1,6 +1,6 @@
1−***********************
2−Compilation and Logging
3−***********************
1+************************************
2+Compilation, Logging, and Reporting
3+************************************
44
55This section provides information about the Idris compilation process, and
66provides details over how you can follow the process through logging.
@@ -41,11 +41,27 @@ With Idris you can ask it to terminate the compilation process after type checki
4141
4242Use of this option will still result in the generation of the Idris binary ``.ibc`` files, and is suitable if you do not wish to generate code from one of the supported backends.
4343
44−Logging Output
45−==============
44+Reporting Compilation Process
45+=============================
4646
47−The internal operation of Idris is captured using a category based logger.
48−Currently, the logging infrastructure has support for the following categories:
47+During compilation the reporting of Idris' progress can be controlled
48+by setting a verbosity level.
49+
50++ ``-V``, or alternatively ``--verbose`` and ``--V0``, will report which file Idris is currently type checking.
51++ ``--V1`` will additionally report: Parsing, IBC Generation, and Code
52+ Generation.
53++ ``--V2`` will additionally report: Totality Checking, Universe
54+ Checking, and the individual steps prior to code generation.
55+
56+
57+By default Idris' progress reporting is set to quiet-``-q``, or ``--quiet``.
58+
59+Logging Internal Operation
60+===========================
61+
62+For those that develop on the Idris compiler, the internal operation
63+of Idris is captured using a category based logger. Currently, the
64+logging infrastructure has support for the following categories:
4965
5066+ Parser
5167+ Elaborator
docs/reference/documenting.rst+8−1
@@ -61,7 +61,14 @@ italics correctly). A comprehensive set of examples is given below.
6161 ||| Add some numbers.
6262 |||
6363 ||| Addition is really great. This paragraph is not part of the overview.
64− ||| Still the same paragraph. Lists are also nifty:
64+ ||| Still the same paragraph.
65+ |||
66+ ||| You can even provide examples which are inlined in the documentation:
67+ ||| ```idris example
68+ ||| add 4 5
69+ ||| ```
70+ |||
71+ ||| Lists are also nifty:
6572 ||| * Really nifty!
6673 ||| * Yep!
6774 ||| * The name `add` is a **bold** choice
docs/reference/misc.rst+1−1
@@ -273,7 +273,7 @@ That is, ``{x}`` behaves like ``{x=x}``.
273273
274274
275275Existence of an implementation
276−========================
276+==============================
277277
278278In order to show that an implementation of some interface is defined for some
279279type, one could use the ``%implementation`` keyword:
docs/reference/packages.rst+8−1
@@ -97,7 +97,7 @@ external ``C`` libraries, the following options are available:
9797 which must be present for the package to be usable.
9898
9999+ ``objs = <objs>``, which takes a comma separated list of additional
100− files to be installed (object files, headers), perhaps generated
100+ files to be installed (object files, headers), perhaps generated
101101 by the ``Makefile``.
102102
103103Testing
@@ -112,6 +112,11 @@ The following option is available:
112112.. IMPORTANT::
113113 The modules containing the test functions must also be added to the list of modules.
114114
115+Comments
116+---------
117+
118+Package files support comments using the standard Idris singleline ``--`` and multiline ``{- -}`` format.
119+
115120Using Package files
116121===================
117122
@@ -127,6 +132,8 @@ Given an Idris package file ``text.ipkg`` it can be used with the Idris compiler
127132
128133+ ``idris --mkdoc test.ipkg`` will build HTML documentation for your package in the folder ``test_doc`` in your project's root directory.
129134
135++ ``idris --installdoc test.ipkg`` will install the packages documentation into Idris' central documentation folder located at ``idris --docdir``.
136+
130137+ ``idris --checkpkg test.ipkg`` will type check all modules in the package only. This differs from build that type checks **and** generates code.
131138
132139+ ``idris --testpkg test.ipkg`` will compile and run any embedded tests you have specified in the ``tests`` parameter.
docs/tutorial/index.rst−1
@@ -24,7 +24,6 @@ This is the Idris Tutorial. It will teach you about programming in the Idris Lan
2424 interfaces
2525 modules
2626 packages
27− testing
2827 interp
2928 views
3029 theorems
docs/tutorial/packages.rst+101−15
@@ -31,14 +31,18 @@ package file would be::
3131
3232
3333Other examples of package files can be found in the ``libs`` directory
34−of the main Idris repository, and in `third-party libraries <https://github.com/idris-lang/Idris-dev/wiki/Libraries>`_.
35−More details including a complete listing of available fields can be found in :ref:`ref-sect-packages`.
34+of the main Idris repository, and in `third-party libraries
35+<https://github.com/idris-lang/Idris-dev/wiki/Libraries>`_.
3636
3737
3838Using Package files
3939===================
4040
41−Given an Idris package file ``maths.ipkg`` it can be used with the Idris compiler as follows:
41+
42+Idris itself is aware about packages, and special commands are
43+available to help with, for example, building packages, installing
44+packages, and cleaning packages. For instance, given the ``maths``
45+package from earlier we can use Idris as follows:
4246
4347+ ``idris --build maths.ipkg`` will build all modules in the package
4448
@@ -48,20 +52,102 @@ Given an Idris package file ``maths.ipkg`` it can be used with the Idris compile
4852+ ``idris --clean maths.ipkg`` will delete all intermediate code and
4953 executable files generated when building.
5054
51−+ ``idris --mkdoc maths.ipkg`` will build HTML documentation for your
52− package in the folder ``maths_doc`` in your project's root
53− directory.
54−
55−+ ``idris --checkpkg maths.ipkg`` will type check all modules in the
56− package only. This differs from build that type checks **and**
57− generates code.
58−
59−+ ``idris --testpkg maths.ipkg`` will compile and run any embedded
60− tests you have specified in the ``tests`` parameter. More
61− information about testing is given in the next section.
62−
6355Once the maths package has been installed, the command line option
6456``--package maths`` makes it accessible (abbreviated to ``-p maths``).
6557For example::
6658
6759 idris -p maths Main.idr
60+
61+
62+Testing Idris Packages
63+======================
64+
65+The integrated build system includes a simple testing framework.
66+This framework collects functions listed in the ``ipkg`` file under ``tests``.
67+All test functions must return ``IO ()``.
68+
69+
70+When you enter ``idris --testpkg yourmodule.ipkg``,
71+the build system creates a temporary file in a fresh environment on your machine
72+by listing the ``tests`` functions under a single ``main`` function.
73+It compiles this temporary file to an executable and then executes it.
74+
75+
76+The tests themselves are responsible for reporting their success or failure.
77+Test functions commonly use ``putStrLn`` to report test results.
78+The test framework does not impose any standards for reporting and consequently
79+does not aggregate test results.
80+
81+
82+For example, lets take the following list of functions that are defined in a module called ``NumOps`` for a sample package ``maths``.
83+
84+.. name: Math/NumOps.idr
85+.. code-block:: idris
86+
87+ module Maths.NumOps
88+
89+ %access export -- to make functions under test visible
90+
91+ double : Num a => a -> a
92+ double a = a + a
93+
94+ triple : Num a => a -> a
95+ triple a = a + double a
96+
97+A simple test module, with a qualified name of ``Test.NumOps`` can be declared as
98+
99+.. name: Math/TestOps.idr
100+.. code-block:: idris
101+
102+ module Test.NumOps
103+
104+ import Maths.NumOps
105+
106+ %access export -- to make the test functions visible
107+
108+ assertEq : Eq a => (given : a) -> (expected : a) -> IO ()
109+ assertEq g e = if g == e
110+ then putStrLn "Test Passed"
111+ else putStrLn "Test Failed"
112+
113+ assertNotEq : Eq a => (given : a) -> (expected : a) -> IO ()
114+ assertNotEq g e = if not (g == e)
115+ then putStrLn "Test Passed"
116+ else putStrLn "Test Failed"
117+
118+ testDouble : IO ()
119+ testDouble = assertEq (double 2) 4
120+
121+ testTriple : IO ()
122+ testTriple = assertNotEq (triple 2) 5
123+
124+
125+The functions ``assertEq`` and ``assertNotEq`` are used to run expected passing, and failing, equality tests.
126+The actual tests are ``testDouble`` and ``testTriple``, and are declared in the ``maths.ipkg`` file as follows::
127+
128+ package maths
129+
130+ modules = Maths.NumOps
131+ , Test.NumOps
132+
133+ tests = Test.NumOps.testDouble
134+ , Test.NumOps.testTriple
135+
136+
137+The testing framework can then be invoked using ``idris --testpkg maths.ipkg``::
138+
139+ > idris --testpkg maths.ipkg
140+ Type checking ./Maths/NumOps.idr
141+ Type checking ./Test/NumOps.idr
142+ Type checking /var/folders/63/np5g0d5j54x1s0z12rf41wxm0000gp/T/idristests144128232716531729.idr
143+ Test Passed
144+ Test Passed
145+
146+Note how both tests have reported success by printing ``Test Passed``
147+as we arranged for with the ``assertEq`` and ``assertNoEq`` functions.
148+
149+More information
150+================
151+
152+More details, including a complete listing of available fields, can be
153+found in the reference manual in :ref:`ref-sect-packages`.
docs/tutorial/syntax.rst+1−1
@@ -92,7 +92,7 @@ forms. For example, a ``for`` loop binds a variable on each iteration:
9292
9393.. code-block:: idris
9494
95− syntax for {x} in [xs] ":" [body] = forLoop xs (\x => body)
95+ syntax for {x} "in" [xs] ":" [body] = forLoop xs (\x => body)
9696
9797 main : IO ()
9898 main = do for x in [1..10]:
docs/tutorial/testing.rstdeleted−85
@@ -1,85 +0,0 @@
1−.. _tut-sect-testing:
2−
3−**********************
4−Testing Idris Packages
5−**********************
6−
7−The integrated build system includes a simple testing framework.
8−This framework collects functions listed in the ``ipkg`` file under ``tests``.
9−All test functions must return ``IO ()``.
10−
11−
12−When you enter ``idris --testpkg yourmodule.ipkg``,
13−the build system creates a temporary file in a fresh environment on your machine
14−by listing the ``tests`` functions under a single ``main`` function.
15−It compiles this temporary file to an executable and then executes it.
16−
17−
18−The tests themselves are responsible for reporting their success or failure.
19−Test functions commonly use ``putStrLn`` to report test results.
20−The test framework does not impose any standards for reporting and consequently
21−does not aggregate test results.
22−
23−
24−For example, lets take the following list of functions that are defined in a module called ``NumOps`` for a sample package ``maths``.
25−
26−.. name: Math/NumOps.idr
27−.. code-block:: idris
28−
29− module Maths.NumOps
30−
31− double : Num a => a -> a
32− double a = a + a
33−
34− triple : Num a => a -> a
35− triple a = a + double a
36−
37−A simple test module, with a qualified name of ``Test.NumOps`` can be declared as
38−
39−.. name: Math/TestOps.idr
40−.. code-block:: idris
41−
42− module Test.NumOps
43−
44− import Maths.NumOps
45−
46− assertEq : Eq a => (given : a) -> (expected : a) -> IO ()
47− assertEq g e = if g == e
48− then putStrLn "Test Passed"
49− else putStrLn "Test Failed"
50−
51− assertNotEq : Eq a => (given : a) -> (expected : a) -> IO ()
52− assertNotEq g e = if not (g == e)
53− then putStrLn "Test Passed"
54− else putStrLn "Test Failed"
55−
56− testDouble : IO ()
57− testDouble = assertEq (double 2) 4
58−
59− testTriple : IO ()
60− testTriple = assertNotEq (triple 2) 5
61−
62−
63−The functions ``assertEq`` and ``assertNotEq`` are used to run expected passing, and failing, equality tests.
64−The actual tests are ``testDouble`` and ``testTriple``, and are declared in the ``maths.ipkg`` file as follows::
65−
66− package maths
67−
68− modules = Maths.NumOps
69− , Test.NumOps
70−
71− tests = Test.NumOps.testDouble
72− , Test.NumOps.testTriple
73−
74−
75−The testing framework can then be invoked using ``idris --testpkg maths.ipkg``::
76−
77− > idris --testpkg maths.ipkg
78− Type checking ./Maths/NumOps.idr
79− Type checking ./Test/NumOps.idr
80− Type checking /var/folders/63/np5g0d5j54x1s0z12rf41wxm0000gp/T/idristests144128232716531729.idr
81− Test Passed
82− Test Passed
83−
84−Note how both tests have reported success by printing ``Test Passed``
85−as we arranged for with the ``assertEq`` and ``assertNoEq`` functions.
idris.cabal+9−2
@@ -1,5 +1,5 @@
11Name: idris
2−Version: 0.12.3
2+Version: 0.99
33License: BSD3
44License-file: LICENSE
55Author: Edwin Brady
@@ -289,7 +289,6 @@ Library
289289 , vector < 0.12
290290 , vector-binary-instances < 0.3
291291 , zip-archive > 0.2.3.5 && < 0.4
292− , safe == 0.3.9
293292 , fsnotify >= 0.2 && < 2.2
294293 , async < 2.2
295294
@@ -302,6 +301,14 @@ Library
302301 else
303302 build-depends: process < 1.5
304303
304+ -- safe 0.3.10 is having issues with cabal 1.20 and ghc 7.6.3, the
305+ -- hvr ghc ppa doesn't provide a new enough cabal library. Temporary
306+ -- fix until hvr ghc ppa is fixed or we deprecate support for 7.6.3.
307+ if impl(ghc < 7.8.4)
308+ build-depends: safe == 0.3.9
309+ else
310+ build-depends: safe >= 0.3.9
311+
305312 Extensions: MultiParamTypeClasses
306313 , DeriveFoldable
307314 , DeriveTraversable
libs/base/Control/Isomorphism.idr+5
@@ -2,6 +2,7 @@ module Control.Isomorphism
22
33import Syntax.PreorderReasoning
44import Data.Fin
5+import Control.Category
56
67%default total
78%access public export
@@ -32,6 +33,10 @@ isoTrans (MkIso to from toFrom fromTo) (MkIso to' from' toFrom' fromTo') =
3233 (from (to x)) ={ fromTo x }=
3334 x QED)
3435
36+Category Iso where
37+ id = isoRefl
38+ (.) = flip isoTrans
39+
3540||| Isomorphism is symmetric
3641isoSym : Iso a b -> Iso b a
3742isoSym (MkIso to from toFrom fromTo) = MkIso from to fromTo toFrom
libs/base/Data/Complex.idr+11−3
@@ -63,15 +63,23 @@ conjugate (r:+i) = (r :+ (0-i))
6363implementation Functor Complex where
6464 map f (r :+ i) = f r :+ f i
6565
66−-- We can't do "implementation Num a => Num (Complex a)" because
67−-- we need "abs" which needs "magnitude" which needs "sqrt" which needs Double
68−implementation Num (Complex Double) where
66+-- We can do "implementation Neg a => Num (Complex a)" because
67+-- we don't need "abs", only (-)
68+implementation Neg a => Num (Complex a) where
6969 (+) (a:+b) (c:+d) = ((a+c):+(b+d))
7070 (*) (a:+b) (c:+d) = ((a*c-b*d):+(b*c+a*d))
7171 fromInteger x = (fromInteger x:+0)
7272
73+-- We can't do "implementation Neg a => Neg (Complex a)" because
74+-- we need "abs" which needs "magnitude" which needs "sqrt" which needs Double
7375implementation Neg (Complex Double) where
7476 negate = map negate
7577 (-) (a:+b) (c:+d) = ((a-c):+(b-d))
7678 abs (a:+b) = (magnitude (a:+b):+0)
7779
80+-- As soon as abs moves out of Neg (issue #3500), the following would become a
81+-- valid instance:
82+
83+-- implementation Neg a => Neg (Complex a) where
84+-- negate = map negate
85+-- (-) (a:+b) (c:+d) = ((a-c):+(b-d))
libs/base/Data/List/Views.idr+1−3
@@ -187,7 +187,7 @@ public export
187187data VList : List a -> Type where
188188 VNil : VList []
189189 VOne : VList [x]
190− VCons : {x : a} -> {y : a} -> {xs : List a} ->
190+ VCons : {x : a} -> {y : a} -> .{xs : List a} ->
191191 (rec : VList xs) -> VList (x :: xs ++ [y])
192192
193193total
@@ -225,5 +225,3 @@ vList xs with (splitBalanced xs)
225225 vList (ys ++ zs) | (MkSplitBal prf)
226226 = toVList ys (snocList zs) prf
227227
228−
229−
libs/base/Data/String/Views.idr+2
@@ -1,5 +1,7 @@
11module Data.String.Views
22
3+%access public export
4+
35||| View for traversing a String one character at a time
46data StrList : String -> Type where
57 SNil : StrList ""
libs/base/Debug/Error.idr+3−6
@@ -12,9 +12,6 @@ error : {default (%runElab sourceLocation) loc : SourceLocation} ->
1212 (message : String) ->
1313 a
1414error {loc = FileLoc filename (line, col) _} message =
15− believe_me . unsafePerformIO $
16− do let place = filename ++ " line " ++ show line ++ " column " ++ show col
17− let message' = place ++ ": " ++ message
18− putStrLn message'
19− exit 1
20−
15+ let place = filename ++ " line " ++ show line ++ " column " ++ show col
16+ message' = place ++ ": " ++ message in
17+ idris_crash message'
libs/base/System.idr+35−4
@@ -1,5 +1,7 @@
11module System
22
3+import Data.So
4+
35%include C "unistd.h"
46%default partial
57%access public export
@@ -52,11 +54,41 @@ getEnvironment = getAllPairs 0 []
5254 then pure $ reverse $ map splitEq acc
5355 else getAllPairs (n + 1) (envPair :: acc)
5456
57+||| Programs can either terminate successfully, or end in a caught
58+||| failure.
59+data ExitCode : Type where
60+ ||| Terminate successfully.
61+ ExitSuccess : ExitCode
62+ ||| Program terminated for some prescribed reason.
63+ |||
64+ ||| @errNo A non-zero numerical value indicating failure.
65+ ||| @prf Proof that the int value is non-zero.
66+ ExitFailure : (errNo : Int)
67+ -> {auto prf : So (not $ errNo == 0)}
68+ -> ExitCode
69+
5570||| Quit with a particular exit code
56−exit : Int -> IO ()
57−exit code = foreign FFI_C "exit" (Int -> IO ()) code
71+exit : Int -> IO a
72+exit code = believe_me $ foreign FFI_C "exit" (Int -> IO ()) code
73+
74+||| Terminate the program with an `ExitCode`. This code indicates the
75+||| success of the program's execution, and returns the success code
76+||| to the program's caller.
77+|||
78+||| @code The `ExitCode` for program.
79+exitWith : (code : ExitCode) -> IO a
80+exitWith ExitSuccess = exit 0
81+exitWith (ExitFailure errNo) = exit errNo
5882
59−||| Get the numbers of seconds since 1st January 1970, 00:00 UTC
83+||| Exit the program indicating failure.
84+exitFailure : IO a
85+exitFailure = exitWith (ExitFailure 1)
86+
87+||| Exit the program after a successful run.
88+exitSuccess : IO a
89+exitSuccess = exitWith ExitSuccess
90+
91+||| Get the numbers of seconds since 1st January 1970, 00:00 UTC
6092time : IO Integer
6193time = do MkRaw t <- foreign FFI_C "idris_time" (IO (Raw Integer))
6294 pure t
@@ -66,4 +98,3 @@ usleep i = foreign FFI_C "usleep" (Int -> IO ()) i
6698
6799system : String -> IO Int
68100system cmd = foreign FFI_C "system" (String -> IO Int) cmd
69−
libs/contrib/CFFI/Types.idr+3−1
@@ -126,13 +126,15 @@ offsetsPacked xs = offsets' xs [] 0
126126 offsets' [] acc _ = reverse acc
127127 offsets' (x::xs) acc pos = offsets' xs (pos::acc) (sizeOf x)
128128
129+%language ElabReflection -- needed for 'error', which finds a line number
130+
129131private
130132indexOrFail : Nat -> List a -> a
131133indexOrFail i xs = case index' i xs of
132134 Just x => x
133135 Nothing => error "Out of bounds access"
134136
135−||| The offset of a firld in a composite type
137+||| The offset of a field in a composite type
136138export
137139offset : Composite -> Nat -> Int
138140offset (STRUCT xs) i = indexOrFail i (offsetsStruct xs)
libs/effects/Effect/Exception.idr+1−2
@@ -17,7 +17,7 @@ implementation Handler (Exception a) List where
1717
1818implementation Show a => Handler (Exception a) IO where
1919 handle _ (Raise e) k = do printLn e
20− believe_me (exit 1)
20+ (exit 1)
2121
2222implementation Handler (Exception a) (IOExcept a) where
2323 handle _ (Raise e) k = ioe_fail e
@@ -30,4 +30,3 @@ EXCEPTION t = MkEff () (Exception t)
3030
3131raise : a -> Eff b [EXCEPTION a]
3232raise err = call $ Raise err
33−
libs/prelude/Builtins.idr+7
@@ -2,6 +2,7 @@
22
33%access public export
44%default total
5+%language UniquenessTypes
56
67||| The canonical single-element type, also known as the trivially
78||| true proposition.
@@ -177,6 +178,12 @@ assert_total x = x
177178assert_unreachable : a
178179-- compiled as primitive
179180
181+||| Abort immediately with an error message
182+idris_crash : (msg : String) -> a
183+-- compiled as primitive
184+
185+%used idris_crash msg
186+
180187||| Subvert the type checker. This function is abstract, so it will not reduce in
181188||| the type checker. Use it with care - it can result in segfaults or worse!
182189export
libs/prelude/Prelude.idr+11−3
@@ -37,6 +37,8 @@ import public Language.Reflection.Errors
3737%access public export
3838%default total
3939
40+%language ElabReflection
41+
4042-- Things that can't be elsewhere for import cycle reasons
4143-- See comment after declaration of void in Builtins.idr
4244-- for explanation of this definition's location
@@ -144,9 +146,14 @@ natRange n = List.reverse (go n)
144146 where go Z = []
145147 go (S n) = n :: go n
146148
149+
147150-- predefine Nat versions of Enum, so we can use them in the default impls
151+countFrom : Num n => n -> n -> Stream n
152+countFrom start diff = start :: countFrom (start + diff) diff
153+
148154total natEnumFromThen : Nat -> Nat -> Stream Nat
149−natEnumFromThen n next = n :: natEnumFromThen next (minus next n)
155+natEnumFromThen n next = countFrom n (minus next n)
156+
150157total natEnumFromTo : Nat -> Nat -> List Nat
151158natEnumFromTo n m = if n <= m
152159 then go n m
@@ -195,7 +202,7 @@ Enum Integer where
195202 succ n = n + 1
196203 toNat n = cast n
197204 fromNat n = cast n
198− enumFromThen n inc = n :: enumFromThen (inc + n) inc
205+ enumFromThen n inc = countFrom n (inc - n)
199206 enumFromTo n m = if n <= m
200207 then go n m
201208 else List.reverse $ go m n
@@ -224,7 +231,8 @@ Enum Int where
224231 go' acc (S k) m = go' (m :: acc) k (m - 1)
225232 go : Int -> Int -> List Int
226233 go n m = go' [] (cast {to = Nat} (m - n)) m
227− enumFromThen n inc = n :: enumFromThen (inc + n) inc
234+ enumFromThen n inc = countFrom n (inc - n)
235+
228236 enumFromThenTo n next m = if n == m then [n]
229237 else if next - n == 0 || next - n < 0 /= m - n < 0 then []
230238 else go (natRange (S (divNatNZ (cast {to=Nat} (abs (m - n))) (S (cast {to=Nat} ((abs (next - n)) - 1))) SIsNotZ)))
libs/prelude/Prelude/Nat.idr+13−8
@@ -91,6 +91,12 @@ hyper (S pn) a (S pb) = hyper pn a (hyper (S pn) a pb)
9191-- Comparisons
9292--------------------------------------------------------------------------------
9393
94+||| Proofs that `n` or `m` is not equal to Z
95+data NotBothZero : (n, m : Nat) -> Type where
96+ LeftIsNotZero : NotBothZero (S n) m
97+ RightIsNotZero : NotBothZero n (S m)
98+
99+
94100||| Proofs that `n` is less than or equal to `m`
95101||| @ n the smaller number
96102||| @ m the larger number
@@ -386,16 +392,15 @@ log2 (S n) = log2NZ (S n) SIsNotZ
386392--------------------------------------------------------------------------------
387393-- GCD and LCM
388394--------------------------------------------------------------------------------
389−partial
390−gcd : Nat -> Nat -> Nat
391−gcd a Z = a
392−gcd a b = assert_total (gcd b (a `modNat` b))
395+gcd : (a: Nat) -> (b: Nat) -> .{auto ok: NotBothZero a b} -> Nat
396+gcd a Z = a
397+gcd Z b = b
398+gcd a (S b) = assert_total $ gcd (S b) (modNatNZ a (S b) SIsNotZ)
393399
394−partial
395400lcm : Nat -> Nat -> Nat
396−lcm _ Z = Z
397−lcm Z _ = Z
398−lcm x y = divNat (x * y) (gcd x y)
401+lcm _ Z = Z
402+lcm Z _ = Z
403+lcm a (S b) = assert_total $ divNat (a * (S b)) (gcd a (S b))
399404
400405
401406--------------------------------------------------------------------------------
libs/prelude/Prelude/Strings.idr+19−14
@@ -45,7 +45,8 @@ foldl1 f (x::xs) = foldl f x xs
4545||| ```
4646partial
4747strHead : String -> Char
48−strHead = prim__strHead
48+strHead "" = idris_crash "Prelude.Strings: attempt to take the head of an empty string"
49+strHead x = prim__strHead x
4950
5051||| Returns the characters specified after the head of the string.
5152|||
@@ -59,7 +60,8 @@ strHead = prim__strHead
5960||| ```
6061partial
6162strTail : String -> String
62−strTail = prim__strTail
63+strTail "" = idris_crash "Prelude.Strings: attempt to take the tail of an empty string"
64+strTail xs = prim__strTail xs
6365
6466||| Adds a character to the front of the specified string.
6567|||
@@ -72,6 +74,18 @@ strTail = prim__strTail
7274strCons : Char -> String -> String
7375strCons = prim__strCons
7476
77+||| Returns the length of the string.
78+|||
79+||| ```idris example
80+||| length ""
81+||| ```
82+||| ```idris example
83+||| length "ABC"
84+||| ```
85+length : String -> Nat
86+length = fromInteger . prim__zextInt_BigInt . prim_lenString
87+
88+
7589||| Returns the nth character (starting from 0) of the specified string.
7690|||
7791||| Precondition: '0 < i < length s' for 'strIndex s i'.
@@ -81,7 +95,9 @@ strCons = prim__strCons
8195||| ```
8296partial
8397strIndex : String -> Int -> Char
84−strIndex = prim__strIndex
98+strIndex x i = if (i < 0 || i >= cast (length x))
99+ then idris_crash "Prelude.Strings: String index out of bounds"
100+ else prim__strIndex x i
85101
86102||| Reverses the elements within a String.
87103|||
@@ -297,17 +313,6 @@ unlines' (l::ls) = l ++ '\n' :: unlines' ls
297313unlines : List String -> String
298314unlines = pack . unlines' . map unpack
299315
300−||| Returns the length of the string.
301−|||
302−||| ```idris example
303−||| length ""
304−||| ```
305−||| ```idris example
306−||| length "ABC"
307−||| ```
308−length : String -> Nat
309−length = fromInteger . prim__zextInt_BigInt . prim_lenString
310−
311316||| Returns a substring of a given string
312317|||
313318||| @ index The (zero based) index of the string to extract. If this is
libs/pruviloj/Pruviloj/Induction.idr+3−1
@@ -132,7 +132,9 @@ induction subj =
132132 (_, ty) <- check !getEnv subj
133133 ty' <- forget ty
134134 case headName ty' of
135− Nothing => fail [TermPart ty, TextPart "is not an inductive family"]
135+ Nothing =>
136+ fail [TermPart ty,
137+ TextPart "is not a datatype declared with the data keyword"]
136138 Just fam =>
137139 do let elim = elimN fam
138140 (_,_,elimTy) <- (lookupTyExact elim) <|> (do deriveElim fam elim
main/Main.hs+16−4
@@ -1,5 +1,11 @@
11module Main where
22
3+import System.Exit ( ExitCode(..), exitWith, exitSuccess )
4+
5+import Control.Monad ( unless, when, (>=>) )
6+import Data.Maybe ( fromMaybe )
7+import Data.Foldable ( foldrM )
8+
39import Idris.AbsSyntax
410import Idris.CmdOptions
511import Idris.Error
@@ -9,8 +15,8 @@ import Idris.Package
915
1016import Util.System (setupBundledCC)
1117
12−import Control.Monad (when)
13−import System.Exit (exitSuccess)
18+import Util.System ( setupBundledCC )
19+import System.Exit ( ExitCode(..), exitWith)
1420
1521processShowOptions :: [Opt] -> Idris ()
1622processShowOptions opts = runIO $ do
@@ -33,7 +39,7 @@ processClientOptions :: [Opt] -> Idris ()
3339processClientOptions opts = check opts getClient $ \fs -> case fs of
3440 [] -> ifail "No --client argument. This indicates a bug. Please report."
3541 (c : _) -> do
36− setVerbose False
42+ setVerbose 0
3743 setQuiet True
3844 case getPort opts of
3945 Just DontListen -> ifail "\"--client\" and \"--port none\" are incompatible"
@@ -49,7 +55,13 @@ processPackageOptions opts = do
4955 check opts getPkgMkDoc $ \fs -> runIO $ do
5056 mapM_ (documentPkg opts) fs
5157 check opts getPkgTest $ \fs -> runIO $ do
52− mapM_ (testPkg opts) fs
58+
59+ codes <- mapM (testPkg opts) fs
60+ -- check if any of the tests exited with an exit code other
61+ -- than zero; if they did, exit with exit code 1
62+ unless (null $ filter (/= ExitSuccess) codes) $
63+ exitWith (ExitFailure 1)
64+
5365 check opts getPkg $ \fs -> runIO $ do
5466 mapM_ (buildPkg opts (WarnOnly `elem` opts)) fs
5567 check opts getPkgREPL $ \fs -> case fs of
man/idris.1+16−2
@@ -1,6 +1,6 @@
11.\" Manpage for Idris.
22.\" Contact <> to correct errors or typos.
3−.TH man 1 "25 March 2016" "0.12.3" "Idris man page"
3+.TH man 1 "28 November 2016" "0.99" "Idris man page"
44.SH NAME
55idris -\ a general purpose pure functional programming language with dependent types.
66.SH SYNOPSIS
@@ -13,17 +13,29 @@ specified precisely in the type. It is compiled, with eager
1313evaluation. Its features are influenced by Haskell and ML.
1414
1515+ Full dependent types with dependent pattern matching
16+
1617+ Simple case expressions, where-clauses, with-rule
18+
1719+ Pattern matching let- and lambda-bindings
20+
1821+ Overloading via Interfaces (Type class-like), Monad comprehensions
22+
1923+ do-notation, idiom brackets
24+
2025+ Syntactic conveniences for lists, tuples, dependent pairs
26+
2127+ Totality checking
28+
2229+ Coinductive types
30+
2331+ Indentation significant syntax, Extensible syntax
32+
2433+ Tactic based theorem proving (influenced by Coq)
34+
2535+ Cumulative universes
36+
2637+ Simple Foreign Function Interface
38+
2739+ Hugs style interactive environment
2840
2941It is important to note that Idris is first and foremost a research tool
@@ -56,7 +68,9 @@ should not necessarily be seen as production ready nor for industrial use.
5668 --listlibs Display installed libraries
5769 --libdir Display library directory
5870 --include Display the includes flags
59− -V,--verbose Loud verbosity
71+ --V2 Loudest verbosity
72+ --V1 Louder verbosity
73+ -V, --V0, --verbose Loud verbosity
6074 --ibcsubdir FILE Write IBC files into sub directory
6175 -i,--idrispath ARG Add directory to the list of import paths
6276 --sourcepath ARG Add directory to the list of source search paths
mkpkg.sh+44−6
@@ -1,26 +1,64 @@
11#!/bin/sh
22
3−VERSION=$1
3+set -euo pipefail
44
5−echo "Building version-$VERSION\n\n"
6−echo "Have you: set the release flag, checked the demos and the tutorial?"
7−read $foo
5+if [ "$#" -lt 1 ]; then
6+ echo "Usage $0 [version number] ?[idris bin location]"
7+ echo ""
8+ echo "The first argument is the version number"
9+ echo ""
10+ echo "The second argument is optional, and used to point to a"
11+ echo "custom location in which idris was recently built i.e."
12+ echo "withing .stack-work or .cabal-sandbox. The location must"
13+ echo "be given relative to the project root of a package in the "
14+ echo "libs/ directory."
15+ exit 1
16+fi
17+
18+VERSION=${1:-}
19+
20+echo "==> Building version-$VERSION"
21+echo ""
22+echo "Q: Have you: (a) set the release flag & (b) checked the demos and the tutorial?"
23+read ${FOO:-}
824
925git tag v$VERSION -a
1026
27+echo "==> Building Source Distribution"
1128cabal sdist
1229
1330# Generate Idris library docs and put them in lib_docs.tar.gz in the root
14−make lib_doc
31+echo "==> Generating API Documentation."
32+echo "==> Determining version of Idris to use."
33+if [ -z ${2+x} ];
34+then
35+ echo "==> Using default location.";
36+ make lib_doc
37+else
38+ echo "==> Using custom location.";
39+ make -C libs IDRIS=$2 doc
40+fi
41+
1542DOCDIR=`mktemp -d /tmp/docsXXXXX`
43+
1644cp -r libs/base/base_doc "$DOCDIR"
1745cp -r libs/prelude/prelude_doc "$DOCDIR"
1846cp -r libs/effects/effects_doc "$DOCDIR"
1947cp -r libs/contrib/contrib_doc "$DOCDIR"
48+
2049tar -czvf lib_docs.tar.gz -C "$DOCDIR" prelude_doc base_doc effects_doc contrib_doc
2150
51+echo "==> Building Binaries"
2252cabal configure --prefix=/usr/local
53+
2354cabal build
55+
56+echo "==> Creating Package"
57+mkdir -p /tmp/idris-pkg/
58+
2459cabal copy --destdir=/tmp/idris-pkg/
25−pkgbuild --id org.idris-lang --root /tmp/idris-pkg/ idris-$VERSION.pkg
2660
61+pkgbuild --identifier org.idris-lang \
62+ --version "v$VERSION" \
63+ --root /tmp/idris-pkg/ \
64+ idris-$VERSION.pkg
rts/idris_bitstring.c+8−8
@@ -823,37 +823,37 @@ VAL idris_b64T32(VM *vm, VAL a) {
823823}
824824
825825VAL idris_peekB8(VM* vm, VAL ptr, VAL offset) {
826− return MKB8(vm, *(uint8_t*)(GETPTR(ptr) + GETINT(offset)));
826+ return MKB8(vm, *(uint8_t*)((char *)GETPTR(ptr) + GETINT(offset)));
827827}
828828
829829VAL idris_pokeB8(VAL ptr, VAL offset, VAL data) {
830− *(uint8_t*)(GETPTR(ptr) + GETINT(offset)) = GETBITS8(data);
830+ *(uint8_t*)((char *)GETPTR(ptr) + GETINT(offset)) = GETBITS8(data);
831831 return MKINT(0);
832832}
833833
834834VAL idris_peekB16(VM* vm, VAL ptr, VAL offset) {
835− return MKB16(vm, *(uint16_t*)(GETPTR(ptr) + GETINT(offset)));
835+ return MKB16(vm, *(uint16_t*)((char *)GETPTR(ptr) + GETINT(offset)));
836836}
837837
838838VAL idris_pokeB16(VAL ptr, VAL offset, VAL data) {
839− *(uint16_t*)(GETPTR(ptr) + GETINT(offset)) = GETBITS16(data);
839+ *(uint16_t*)((char *)GETPTR(ptr) + GETINT(offset)) = GETBITS16(data);
840840 return MKINT(0);
841841}
842842
843843VAL idris_peekB32(VM* vm, VAL ptr, VAL offset) {
844− return MKB32(vm, *(uint32_t*)(GETPTR(ptr) + GETINT(offset)));
844+ return MKB32(vm, *(uint32_t*)((char *)GETPTR(ptr) + GETINT(offset)));
845845}
846846
847847VAL idris_pokeB32(VAL ptr, VAL offset, VAL data) {
848− *(uint32_t*)(GETPTR(ptr) + GETINT(offset)) = GETBITS32(data);
848+ *(uint32_t*)((char *)GETPTR(ptr) + GETINT(offset)) = GETBITS32(data);
849849 return MKINT(0);
850850}
851851
852852VAL idris_peekB64(VM* vm, VAL ptr, VAL offset) {
853− return MKB64(vm, *(uint64_t*)(GETPTR(ptr) + GETINT(offset)));
853+ return MKB64(vm, *(uint64_t*)((char *)GETPTR(ptr) + GETINT(offset)));
854854}
855855
856856VAL idris_pokeB64(VAL ptr, VAL offset, VAL data) {
857− *(uint64_t*)(GETPTR(ptr) + GETINT(offset)) = GETBITS64(data);
857+ *(uint64_t*)((char *)GETPTR(ptr) + GETINT(offset)) = GETBITS64(data);
858858 return MKINT(0);
859859}
rts/idris_gmp.c+1−1
@@ -14,7 +14,7 @@
1414// much space is needed (or find another way of preventing copying)
1515#define IDRIS_MAXGMP 65536
1616
17−void init_gmpalloc() {
17+void init_gmpalloc(void) {
1818 mp_set_memory_functions(idris_alloc, idris_realloc, idris_free);
1919}
2020
rts/idris_gmp.h+1−1
@@ -8,7 +8,7 @@
88#endif
99
1010// Set memory allocation functions
11−void init_gmpalloc();
11+void init_gmpalloc(void);
1212
1313VAL MKBIGI(int val);
1414VAL MKBIGC(VM* vm, char* bigint);
rts/idris_rts.c+24−19
@@ -70,7 +70,7 @@ VM* init_vm(int stack_size, size_t heap_size,
7070 return vm;
7171}
7272
73−VM* idris_vm() {
73+VM* idris_vm(void) {
7474 VM* vm = init_vm(4096000, 4096000, 1);
7575 init_threadkeys();
7676 init_threaddata(vm);
@@ -95,12 +95,12 @@ void close_vm(VM* vm) {
9595}
9696
9797#ifdef HAS_PTHREAD
98−void create_key() {
98+void create_key(void) {
9999 pthread_key_create(&vm_key, (void*)free_key);
100100}
101101#endif
102102
103−void init_threadkeys() {
103+void init_threadkeys(void) {
104104#ifdef HAS_PTHREAD
105105 static pthread_once_t key_once = PTHREAD_ONCE_INIT;
106106 pthread_once(&key_once, create_key);
@@ -113,7 +113,7 @@ void init_threaddata(VM *vm) {
113113#endif
114114}
115115
116−void init_signals() {
116+void init_signals(void) {
117117#if (__linux__ || __APPLE__ || __FreeBSD__ || __DragonFly__)
118118 signal(SIGPIPE, SIG_IGN);
119119#endif
@@ -173,7 +173,7 @@ void idris_requireAlloc(size_t size) {
173173#endif
174174}
175175
176−void idris_doneAlloc() {
176+void idris_doneAlloc(void) {
177177#ifdef HAS_PTHREAD
178178 VM* vm = pthread_getspecific(vm_key);
179179 int lock = vm->processes > 0;
@@ -191,7 +191,7 @@ void* idris_alloc(size_t size) {
191191 Closure* cl = (Closure*) allocate(sizeof(Closure)+size, 0);
192192 SETTY(cl, CT_RAWDATA);
193193 cl->info.size = size;
194− return (void*)cl+sizeof(Closure);
194+ return (void*)((char *)cl+sizeof(Closure));
195195}
196196
197197void* idris_realloc(void* old, size_t old_size, size_t size) {
@@ -449,36 +449,36 @@ void idris_poke(void* ptr, i_int offset, uint8_t data) {
449449
450450
451451VAL idris_peekPtr(VM* vm, VAL ptr, VAL offset) {
452− void** addr = GETPTR(ptr) + GETINT(offset);
452+ void** addr = (void **)((char *)GETPTR(ptr) + GETINT(offset));
453453 return MKPTR(vm, *addr);
454454}
455455
456456VAL idris_pokePtr(VAL ptr, VAL offset, VAL data) {
457− void** addr = GETPTR(ptr) + GETINT(offset);
457+ void** addr = (void **)((char *)GETPTR(ptr) + GETINT(offset));
458458 *addr = GETPTR(data);
459459 return MKINT(0);
460460}
461461
462462VAL idris_peekDouble(VM* vm, VAL ptr, VAL offset) {
463− return MKFLOAT(vm, *(double*)(GETPTR(ptr) + GETINT(offset)));
463+ return MKFLOAT(vm, *(double*)((char *)GETPTR(ptr) + GETINT(offset)));
464464}
465465
466466VAL idris_pokeDouble(VAL ptr, VAL offset, VAL data) {
467− *(double*)(GETPTR(ptr) + GETINT(offset)) = GETFLOAT(data);
467+ *(double*)((char *)GETPTR(ptr) + GETINT(offset)) = GETFLOAT(data);
468468 return MKINT(0);
469469}
470470
471471VAL idris_peekSingle(VM* vm, VAL ptr, VAL offset) {
472− return MKFLOAT(vm, *(float*)(GETPTR(ptr) + GETINT(offset)));
472+ return MKFLOAT(vm, *(float*)((char *)GETPTR(ptr) + GETINT(offset)));
473473}
474474
475475VAL idris_pokeSingle(VAL ptr, VAL offset, VAL data) {
476− *(float*)(GETPTR(ptr) + GETINT(offset)) = GETFLOAT(data);
476+ *(float*)((char *)GETPTR(ptr) + GETINT(offset)) = GETFLOAT(data);
477477 return MKINT(0);
478478}
479479
480480void idris_memmove(void* dest, void* src, i_int dest_offset, i_int src_offset, i_int size) {
481− memmove(dest + dest_offset, src + src_offset, size);
481+ memmove((char *)dest + dest_offset, (char *)src + src_offset, size);
482482}
483483
484484VAL idris_castIntStr(VM* vm, VAL i) {
@@ -595,6 +595,11 @@ VAL idris_readStr(VM* vm, FILE* h) {
595595 return ret;
596596}
597597
598+void idris_crash(char* msg) {
599+ fprintf(stderr, "%s\n", msg);
600+ exit(1);
601+}
602+
598603VAL idris_strHead(VM* vm, VAL str) {
599604 return idris_strIndex(vm, str, 0);
600605}
@@ -1041,7 +1046,7 @@ void idris_freeMsg(Msg* msg) {
10411046 free(msg);
10421047}
10431048
1044−int idris_errno() {
1049+int idris_errno(void) {
10451050 return errno;
10461051}
10471052
@@ -1051,7 +1056,7 @@ char* idris_showerror(int err) {
10511056
10521057VAL* nullary_cons;
10531058
1054−void init_nullaries() {
1059+void init_nullaries(void) {
10551060 int i;
10561061 VAL cl;
10571062 nullary_cons = malloc(256 * sizeof(VAL));
@@ -1063,7 +1068,7 @@ void init_nullaries() {
10631068 }
10641069}
10651070
1066−void free_nullaries() {
1071+void free_nullaries(void) {
10671072 int i;
10681073 for(i = 0; i < 256; ++i) {
10691074 free(nullary_cons[i]);
@@ -1074,7 +1079,7 @@ void free_nullaries() {
10741079int __idris_argc;
10751080char **__idris_argv;
10761081
1077−int idris_numArgs() {
1082+int idris_numArgs(void) {
10781083 return __idris_argc;
10791084}
10801085
@@ -1082,12 +1087,12 @@ const char* idris_getArg(int i) {
10821087 return __idris_argv[i];
10831088}
10841089
1085−void idris_disableBuffering() {
1090+void idris_disableBuffering(void) {
10861091 setvbuf(stdin, NULL, _IONBF, 0);
10871092 setvbuf(stdout, NULL, _IONBF, 0);
10881093}
10891094
1090−void stackOverflow() {
1095+void stackOverflow(void) {
10911096 fprintf(stderr, "Stack overflow");
10921097 exit(-1);
10931098}
rts/idris_rts.h+13−10
@@ -161,11 +161,11 @@ Stats terminate(VM* vm);
161161
162162// Create a new VM, set up everything with sensible defaults (use when
163163// calling Idris from C)
164−VM* idris_vm();
164+VM* idris_vm(void);
165165void close_vm(VM* vm);
166166
167167// Set up key for thread-local data - called once from idris_main
168−void init_threadkeys();
168+void init_threadkeys(void);
169169
170170// Functions all take a pointer to their VM, and previous stack base,
171171// and return nothing.
@@ -278,7 +278,7 @@ void* allocate(size_t size, int outerlock);
278278// may take a lock if other threads are running).
279279
280280void idris_requireAlloc(size_t size);
281−void idris_doneAlloc();
281+void idris_doneAlloc(void);
282282
283283// public interface to allocation (note that this may move other pointers
284284// if allocating beyond the limits given by idris_requireAlloc!)
@@ -299,14 +299,14 @@ void idris_free(void* ptr, size_t size);
299299
300300#define NULL_CON(x) nullary_cons[x]
301301
302−int idris_errno();
302+int idris_errno(void);
303303char* idris_showerror(int err);
304304
305305extern VAL* nullary_cons;
306−void init_nullaries();
307−void free_nullaries();
306+void init_nullaries(void);
307+void free_nullaries(void);
308308
309−void init_signals();
309+void init_signals(void);
310310
311311void* vmThread(VM* callvm, func f, VAL arg);
312312void* idris_stopThread(VM* vm);
@@ -364,6 +364,9 @@ VAL idris_pokeDouble(VAL ptr, VAL offset, VAL data);
364364VAL idris_peekSingle(VM* vm, VAL ptr, VAL offset);
365365VAL idris_pokeSingle(VAL ptr, VAL offset, VAL data);
366366
367+// Crash with a message (used for partial primitives)
368+void idris_crash(char* msg);
369+
367370// String primitives
368371VAL idris_concat(VM* vm, VAL l, VAL r);
369372VAL idris_strlt(VM* vm, VAL l, VAL r);
@@ -391,16 +394,16 @@ VAL idris_systemInfo(VM* vm, VAL index);
391394extern int __idris_argc;
392395extern char **__idris_argv;
393396
394−int idris_numArgs();
397+int idris_numArgs(void);
395398const char *idris_getArg(int i);
396399
397400// disable stdin/stdout buffering
398−void idris_disableBuffering();
401+void idris_disableBuffering(void);
399402
400403// Handle stack overflow.
401404// Just reports an error and exits.
402405
403−void stackOverflow();
406+void stackOverflow(void);
404407
405408// I think these names are nicer for an API...
406409
src/IRTS/CodegenC.hs+2−1
@@ -617,6 +617,7 @@ doOp v (LIntCh ITNative) args = v ++ creg (last args)
617617doOp v (LIntCh ITChar) args = doOp v (LIntCh ITNative) args
618618
619619doOp v LSystemInfo [x] = v ++ "idris_systemInfo(vm, " ++ creg x ++ ")"
620+doOp v LCrash [x] = "idris_crash(GETSTR(" ++ creg x ++ "))"
620621doOp v LNoOp args = v ++ creg (last args)
621622
622623-- Pointer primitives (declared as %extern in Builtins.idr)
@@ -673,7 +674,7 @@ doOp v (LExternal pk) [] | pk == sUN "prim__sizeofPtr"
673674doOp v (LExternal mpt) [p] | mpt == sUN "prim__asPtr"
674675 = v ++ "MKPTR(vm, GETMPTR("++ creg p ++"))"
675676doOp v (LExternal offs) [p, n] | offs == sUN "prim__ptrOffset"
676− = v ++ "MKPTR(vm, GETPTR(" ++ creg p ++ ") + GETINT(" ++ creg n ++ "))"
677+ = v ++ "MKPTR(vm, (void *)((char *)GETPTR(" ++ creg p ++ ") + GETINT(" ++ creg n ++ ")))"
677678doOp _ op args = error $ "doOp not implemented (" ++ show (op, args) ++ ")"
678679
679680
src/IRTS/Compiler.hs+15−5
@@ -52,8 +52,10 @@ import System.Process
5252
5353-- | Compile to simplified forms and return CodegenInfo
5454compile :: Codegen -> FilePath -> Maybe Term -> Idris CodegenInfo
55−compile codegen f mtm
56− = do checkMVs -- check for undefined metavariables
55+compile codegen f mtm = do
56+ logCodeGen 1 "Compiling Output."
57+ iReport 2 "Compiling Output."
58+ checkMVs -- check for undefined metavariables
5759 checkTotality -- refuse to compile if there are totality problems
5860 exports <- findExports
5961 let rootNames = case mtm of
@@ -89,9 +91,11 @@ compile codegen f mtm
8991 let ctxtIn = addAlist tagged emptyContext
9092
9193 logCodeGen 1 "Defunctionalising"
94+ iReport 3 "Defunctionalising"
9295 let defuns_in = defunctionalise nexttag ctxtIn
9396 logCodeGen 5 $ show defuns_in
9497 logCodeGen 1 "Inlining"
98+ iReport 3 "Inlining"
9599 let defuns = inline defuns_in
96100 logCodeGen 5 $ show defuns
97101 logCodeGen 1 "Resolving variables for CG"
@@ -108,7 +112,8 @@ compile codegen f mtm
108112 Just f -> runIO $ writeFile f (dumpDefuns defuns)
109113 triple <- Idris.AbsSyntax.targetTriple
110114 cpu <- Idris.AbsSyntax.targetCPU
111− logCodeGen 1 "Building output"
115+ logCodeGen 1 "Generating Code."
116+ iReport 2 "Generating Code."
112117 case checked of
113118 OK c -> do return $ CodegenInfo f outty triple cpu
114119 hdrs impdirs objs libs flags
@@ -258,6 +263,11 @@ irTerm top vs env tm@(App _ f a) = do
258263 | u == txt "assert_unreachable"
259264 -> return $ LError $ "ABORT: Reached an unreachable case in " ++ show top
260265
266+ (P _ (UN u) _, [_, msg])
267+ | u == txt "idris_crash"
268+ -> do msg' <- irTerm top vs env msg
269+ return $ LOp LCrash [msg']
270+
261271 -- TMP HACK - until we get inlining.
262272 (P _ (UN r) _, [_, _, _, _, _, arg])
263273 | r == txt "replace"
@@ -456,14 +466,14 @@ irTerm top vs env tm@(App _ f a) = do
456466 | otherwise = n
457467
458468 used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist)
459− fst4 (x,_,_,_,_) = x
469+ fst4 (x,_,_,_,_,_) = x
460470
461471irTerm top vs env (P _ n _) = return $ LV (Glob n)
462472irTerm top vs env (V i)
463473 | i >= 0 && i < length env = return $ LV (Glob (env!!i))
464474 | otherwise = ifail $ "bad de bruijn index: " ++ show i
465475
466−irTerm top vs env (Bind n (Lam _) sc) = LLam [n'] <$> irTerm top vs (n':env) sc
476+irTerm top vs env (Bind n (Lam _ _) sc) = LLam [n'] <$> irTerm top vs (n':env) sc
467477 where
468478 n' = uniqueName n env
469479
src/IRTS/Lang.hs+2
@@ -92,6 +92,8 @@ data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy
9292 | LPar -- evaluate argument anywhere, possibly on another
9393 -- core or another machine. 'id' is a valid implementation
9494 | LExternal Name
95+ | LCrash
96+
9597 | LNoOp
9698 deriving (Show, Eq, Generic)
9799
src/IRTS/Portable.hs+4−4
@@ -29,7 +29,7 @@ data CodegenFile = CGFile {
2929
3030-- Update the version when the format changes
3131formatVersion :: Int
32−formatVersion = 1
32+formatVersion = 2
3333
3434writePortable :: Handle -> CodegenInfo -> IO ()
3535writePortable file ci = do
@@ -236,13 +236,13 @@ instance ToJSON SExp where
236236 toJSON (SApp tail name exps) = object ["SApp" .= (tail, name, exps)]
237237 toJSON (SLet lv a b) = object ["SLet" .= (lv, a, b)]
238238 toJSON (SUpdate lv exp) = object ["SUpdate" .= (lv, exp)]
239− toJSON (SProj lv i) = object ["DProj" .= (lv, i)]
239+ toJSON (SProj lv i) = object ["SProj" .= (lv, i)]
240240 toJSON (SCon lv i name vars) = object ["SCon" .= (lv, i, name, vars)]
241241 toJSON (SCase ct lv alts) = object ["SCase" .= (ct, lv, alts)]
242− toJSON (SChkCase lv alts) = object ["DChkCase" .= (lv, alts)]
242+ toJSON (SChkCase lv alts) = object ["SChkCase" .= (lv, alts)]
243243 toJSON (SConst c) = object ["SConst" .= c]
244244 toJSON (SForeign fd ret exps) = object ["SForeign" .= (fd, ret, exps)]
245− toJSON (SOp prim vars) = object ["DOp" .= (prim, vars)]
245+ toJSON (SOp prim vars) = object ["SOp" .= (prim, vars)]
246246 toJSON SNothing = object ["SNothing" .= Null]
247247 toJSON (SError s) = object ["SError" .= s]
248248
src/IRTS/System.hs+6−1
@@ -6,7 +6,7 @@ License : BSD3
66Maintainer : The Idris Community.
77-}
88{-# LANGUAGE CPP #-}
9−module IRTS.System( getDataFileName
9+module IRTS.System( getIdrisDataFileByName
1010 , getCC
1111 , getLibFlags
1212 , getIdrisDataDir
@@ -42,6 +42,11 @@ getIdrisDataDir = do
4242 return ddir
4343 Just ddir -> return ddir
4444
45+getIdrisDataFileByName :: String -> IO FilePath
46+getIdrisDataFileByName fn = do
47+ dir <- getIdrisDataDir
48+ return $ dir </> fn
49+
4550overrideIdrisSubDirWith :: String -- ^ Sub directory in `getDataDir` location.
4651 -> String -- ^ Environment variable to get new location from.
4752 -> IO FilePath
src/Idris/ASTUtils.hs+1−1
@@ -148,7 +148,7 @@ opts_idrisCmdline =
148148--
149149-- This has a terrible name, but I'm not sure of a better one that
150150-- isn't confusingly close to tt_ctxt
151−known_terms :: Field IState (Ctxt (Def, Injectivity, Accessibility, Totality, MetaInformation))
151+known_terms :: Field IState (Ctxt (Def, RigCount, Injectivity, Accessibility, Totality, MetaInformation))
152152known_terms = Field (definitions . tt_ctxt)
153153 (\v state -> state {tt_ctxt = (tt_ctxt state) {definitions = v}})
154154
src/Idris/AbsSyntax.hs+54−44
@@ -142,14 +142,10 @@ addImported pub f
142142 putIState $ i { idris_imported = nub $ (f, pub) : idris_imported i }
143143
144144addLangExt :: LanguageExt -> Idris ()
145−addLangExt TypeProviders = do i <- getIState
146− putIState $ i {
147− idris_language_extensions = TypeProviders : idris_language_extensions i
148− }
149−addLangExt ErrorReflection = do i <- getIState
150− putIState $ i {
151− idris_language_extensions = ErrorReflection : idris_language_extensions i
152− }
145+addLangExt e = do i <- getIState
146+ putIState $ i {
147+ idris_language_extensions = e : idris_language_extensions i
148+ }
153149
154150-- | Transforms are organised by the function being applied on the lhs
155151-- of the transform, to make looking up appropriate transforms quicker
@@ -389,7 +385,7 @@ allNames ns n = do i <- getIState
389385 case getCGAllNames i n of
390386 Just ns -> return ns
391387 Nothing -> case lookupCtxtExact n (idris_callgraph i) of
392− Just ci ->
388+ Just ci ->
393389 do more <- mapM (allNames (n:ns)) (calls ci)
394390 let ns' = nub (n : concat more)
395391 addCGAllNames i n ns'
@@ -1028,17 +1024,31 @@ targetCPU :: Idris String
10281024targetCPU = do i <- getIState
10291025 return (opt_cpu (idris_options i))
10301026
1031−verbose :: Idris Bool
1032−verbose = do i <- getIState
1033− -- Quietness overrides verbosity
1034− return (not (opt_quiet (idris_options i)) &&
1035− opt_verbose (idris_options i))
1027+verbose :: Idris Int
1028+verbose = do
1029+ i <- getIState
1030+ -- Quietness overrides verbosity
1031+ let quiet = opt_quiet $ idris_options i
1032+ if quiet
1033+ then return $ 0
1034+ else return $ (opt_verbose $ idris_options i)
1035+
1036+setVerbose :: Int -> Idris ()
1037+setVerbose t = do
1038+ i <- getIState
1039+ let opts = idris_options i
1040+ let opt' = opts { opt_verbose = t }
1041+ putIState $ i { idris_options = opt' }
10361042
1037−setVerbose :: Bool -> Idris ()
1038−setVerbose t = do i <- getIState
1039− let opts = idris_options i
1040− let opt' = opts { opt_verbose = t }
1041− putIState $ i { idris_options = opt' }
1043+iReport :: Int -> String -> Idris ()
1044+iReport level msg = do
1045+ verbosity <- verbose
1046+ i <- getIState
1047+ when (level <= verbosity) $
1048+ case idris_outputmode i of
1049+ RawOutput h -> runIO $ hPutStrLn h msg
1050+ IdeMode n h -> runIO . hPutStrLn h $ convSExp "write-string" msg n
1051+ return ()
10421052
10431053typeInType :: Idris Bool
10441054typeInType = do i <- getIState
@@ -1296,8 +1306,8 @@ expandParams dec ps ns infs tm = en 0 tm
12961306
12971307 nseq x y = nsroot x == nsroot y
12981308
1299− enTacImp ql (TacImp aos st scr) = TacImp aos st (en ql scr)
1300− enTacImp ql other = other
1309+ enTacImp ql (TacImp aos st scr rig) = TacImp aos st (en ql scr) rig
1310+ enTacImp ql other = other
13011311
13021312expandParamsD :: Bool -> -- True = RHS only
13031313 IState ->
@@ -1465,10 +1475,10 @@ addStatics n tm ptm =
14651475 putIState $ i { idris_statics = addDef n stpos (idris_statics i) }
14661476 addIBC (IBCStatic n)
14671477 where
1468− initStatics (Bind n (Pi _ ty _) sc) (PPi p n' fc t s)
1478+ initStatics (Bind n (Pi _ _ ty _) sc) (PPi p n' fc t s)
14691479 | n /= n' = let (static, dynamic) = initStatics sc (PPi p n' fc t s) in
14701480 (static, (n, ty) : dynamic)
1471− initStatics (Bind n (Pi _ ty _) sc) (PPi p n' fc _ s)
1481+ initStatics (Bind n (Pi _ _ ty _) sc) (PPi p n' fc _ s)
14721482 = let (static, dynamic) = initStatics (instantiate (P Bound n ty) sc) s in
14731483 if pstatic p == Static then ((n, ty) : static, dynamic)
14741484 else if (not (searchArg p))
@@ -1484,16 +1494,16 @@ addStatics n tm ptm =
14841494 getNamePos i ps (P _ n _ : as)
14851495 | i `elem` ps = n : getNamePos (i + 1) ps as
14861496 getNamePos i ps (_ : as) = getNamePos (i + 1) ps as
1487− getParamNames ist (Bind t (Pi _ (P _ n _) _) sc)
1497+ getParamNames ist (Bind t (Pi _ _ (P _ n _) _) sc)
14881498 = n : getParamNames ist sc
14891499 getParamNames ist _ = []
14901500
1491− getNamesFrom i ps (Bind n (Pi _ _ _) sc)
1501+ getNamesFrom i ps (Bind n (Pi _ _ _ _) sc)
14921502 | i `elem` ps = n : getNamesFrom (i + 1) ps sc
14931503 | otherwise = getNamesFrom (i + 1) ps sc
14941504 getNamesFrom i ps sc = []
14951505
1496− freeArgNames (Bind n (Pi _ ty _) sc)
1506+ freeArgNames (Bind n (Pi _ _ ty _) sc)
14971507 = nub $ freeNames ty ++ freeNames sc -- treat '->' as fn here
14981508 freeArgNames tm = let (_, args) = unApply tm in
14991509 concatMap freeNames args
@@ -1501,11 +1511,11 @@ addStatics n tm ptm =
15011511 -- if a name appears in an interface or tactic implicit index, it doesn't
15021512 -- affect its 'uniquely inferrable' from a static status since these are
15031513 -- resolved by searching.
1504− searchArg (Constraint _ _) = True
1505− searchArg (TacImp _ _ _) = True
1514+ searchArg (Constraint _ _ _) = True
1515+ searchArg (TacImp _ _ _ _) = True
15061516 searchArg _ = False
15071517
1508− staticList sts (Bind n (Pi _ _ _) sc) = (n `elem` sts) : staticList sts sc
1518+ staticList sts (Bind n (Pi _ _ _ _) sc) = (n `elem` sts) : staticList sts sc
15091519 staticList _ _ = []
15101520
15111521-- Dealing with implicit arguments
@@ -1537,14 +1547,14 @@ addUsingConstraints syn fc t
15371547 -- if all of args in ns, then add it
15381548 doAdd (UConstraint c args : cs) ns t
15391549 | all (\n -> elem n ns) args
1540− = PPi (Constraint [] Dynamic) (sMN 0 "cu") NoFC
1550+ = PPi (Constraint [] Dynamic RigW) (sMN 0 "cu") NoFC
15411551 (mkConst c args) (doAdd cs ns t)
15421552 | otherwise = doAdd cs ns t
15431553
15441554 mkConst c args = PApp fc (PRef fc [] c)
15451555 (map (PExp 0 [] (sMN 0 "carg") . PRef fc []) args)
15461556
1547− getConstraints (PPi (Constraint _ _) _ _ c sc)
1557+ getConstraints (PPi (Constraint _ _ _) _ _ c sc)
15481558 = getcapp c ++ getConstraints sc
15491559 getConstraints (PPi _ _ _ c sc) = getConstraints sc
15501560 getConstraints _ = []
@@ -1613,25 +1623,25 @@ getUnboundImplicits i t tm = getImps t (collectImps tm)
16131623 scopedimpl (Just i) = not (toplevel_imp i)
16141624 scopedimpl _ = False
16151625
1616− getImps (Bind n (Pi i _ _) sc) imps
1626+ getImps (Bind n (Pi _ i _ _) sc) imps
16171627 | scopedimpl i = getImps sc imps
1618− getImps (Bind n (Pi _ t _) sc) imps
1628+ getImps (Bind n (Pi _ _ t _) sc) imps
16191629 | Just (p, t') <- lookup n imps = argInfo n p t' : getImps sc imps
16201630 where
1621− argInfo n (Imp opt _ _ _ _) Placeholder
1631+ argInfo n (Imp opt _ _ _ _ _) Placeholder
16221632 = (True, PImp 0 True opt n Placeholder)
1623− argInfo n (Imp opt _ _ _ _) t'
1633+ argInfo n (Imp opt _ _ _ _ _) t'
16241634 = (False, PImp (getPriority i t') True opt n t')
1625− argInfo n (Exp opt _ _) t'
1635+ argInfo n (Exp opt _ _ _) t'
16261636 = (InaccessibleArg `elem` opt,
16271637 PExp (getPriority i t') opt n t')
1628− argInfo n (Constraint opt _) t'
1638+ argInfo n (Constraint opt _ _) t'
16291639 = (InaccessibleArg `elem` opt,
16301640 PConstraint 10 opt n t')
1631− argInfo n (TacImp opt _ scr) t'
1641+ argInfo n (TacImp opt _ scr _) t'
16321642 = (InaccessibleArg `elem` opt,
16331643 PTacImplicit 10 opt n scr t')
1634− getImps (Bind n (Pi _ t _) sc) imps = impBind n t : getImps sc imps
1644+ getImps (Bind n (Pi _ _ t _) sc) imps = impBind n t : getImps sc imps
16351645 where impBind n t = (True, PImp 1 True [] n Placeholder)
16361646 getImps sc tm = []
16371647
@@ -1714,13 +1724,13 @@ implicitise auto syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
17141724 = do (decls, ns) <- get
17151725 let isn = nub (implNamesIn uvars ty)
17161726 put (decls, nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
1717− imps top env (PPi (Imp l _ _ _ _) n _ ty sc)
1727+ imps top env (PPi (Imp l _ _ _ _ _) n _ ty sc)
17181728 = do let isn = nub (implNamesIn uvars ty) `dropAll` [n]
17191729 (decls , ns) <- get
17201730 put (PImp (getPriority ist ty) True l n Placeholder : decls,
17211731 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
17221732 imps True (n:env) sc
1723− imps top env (PPi (Exp l _ _) n _ ty sc)
1733+ imps top env (PPi (Exp l _ _ _) n _ ty sc)
17241734 = do let isn = nub (implNamesIn uvars ty ++ case sc of
17251735 (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n]
17261736 _ -> [])
@@ -1728,7 +1738,7 @@ implicitise auto syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
17281738 put (PExp (getPriority ist ty) l n Placeholder : decls,
17291739 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
17301740 imps True (n:env) sc
1731− imps top env (PPi (Constraint l _) n _ ty sc)
1741+ imps top env (PPi (Constraint l _ _) n _ ty sc)
17321742 = do let isn = nub (implNamesIn uvars ty ++ case sc of
17331743 (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n]
17341744 _ -> [])
@@ -1736,7 +1746,7 @@ implicitise auto syn ignore ist tm = -- trace ("INCOMING " ++ showImp True tm) $
17361746 put (PConstraint 10 l n Placeholder : decls,
17371747 nub (ns ++ (isn `dropAll` (env ++ map fst (getImps decls)))))
17381748 imps True (n:env) sc
1739− imps top env (PPi (TacImp l _ scr) n _ ty sc)
1749+ imps top env (PPi (TacImp l _ scr _) n _ ty sc)
17401750 = do let isn = nub (implNamesIn uvars ty ++ case sc of
17411751 (PRef _ _ x) -> namesIn uvars ist sc `dropAll` [n]
17421752 _ -> [])
@@ -2136,7 +2146,7 @@ stripUnmatchable :: IState -> PTerm -> PTerm
21362146stripUnmatchable i (PApp fc fn args) = PApp fc fn (fmap (fmap su) args) where
21372147 su :: PTerm -> PTerm
21382148 su tm@(PRef fc hl f)
2139− | (Bind n (Pi _ t _) sc :_) <- lookupTy f (tt_ctxt i)
2149+ | (Bind n (Pi _ _ t _) sc :_) <- lookupTy f (tt_ctxt i)
21402150 = Placeholder
21412151 | (TType _ : _) <- lookupTy f (tt_ctxt i),
21422152 not (implicitable f)
src/Idris/AbsSyntaxTree.hs+48−27
@@ -91,7 +91,7 @@ data IOption = IOption {
9191 , opt_showimp :: Bool -- ^ show implicits
9292 , opt_errContext :: Bool
9393 , opt_repl :: Bool
94− , opt_verbose :: Bool
94+ , opt_verbose :: Int
9595 , opt_nobanner :: Bool
9696 , opt_quiet :: Bool
9797 , opt_codegen :: Codegen
@@ -120,7 +120,7 @@ defaultOpts = IOption { opt_logLevel = 0
120120 , opt_showimp = False
121121 , opt_errContext = False
122122 , opt_repl = True
123− , opt_verbose = True
123+ , opt_verbose = 0
124124 , opt_nobanner = False
125125 , opt_quiet = False
126126 , opt_codegen = Via IBCFormat "c"
@@ -184,7 +184,9 @@ ppOption opt = PPOption {
184184ppOptionIst :: IState -> PPOption
185185ppOptionIst = ppOption . idris_options
186186
187−data LanguageExt = TypeProviders | ErrorReflection
187+data LanguageExt = TypeProviders | ErrorReflection | UniquenessTypes
188+ | DSLNotation | ElabReflection | FCReflection
189+ | LinearTypes
188190 deriving (Show, Eq, Read, Ord, Generic)
189191
190192-- | The output mode in use
@@ -335,6 +337,7 @@ primDefs = [ sUN "unsafePerformPrimIO"
335337 , sUN "mkForeignPrim"
336338 , sUN "void"
337339 , sUN "assert_unreachable"
340+ , sUN "idris_crash"
338341 ]
339342
340343-- information that needs writing for the current module's .ibc file
@@ -510,7 +513,7 @@ data Opt = Filename String
510513 | NoCoverage
511514 | ErrContext
512515 | ShowImpl
513− | Verbose
516+ | Verbose Int
514517 | Port REPLPort -- ^ REPL TCP port
515518 | IBCSubDir String
516519 | ImportDir String
@@ -597,17 +600,21 @@ data Plicity = Imp { pargopts :: [ArgOpt]
597600 , pparam :: Bool
598601 , pscoped :: Maybe ImplicitInfo -- ^ Nothing, if top level
599602 , pinsource :: Bool -- ^ Explicitly written in source
603+ , pcount :: RigCount
600604 }
601605 | Exp { pargopts :: [ArgOpt]
602606 , pstatic :: Static
603607 , pparam :: Bool -- ^ this is a param (rather than index)
608+ , pcount :: RigCount
604609 }
605610 | Constraint { pargopts :: [ArgOpt]
606− , pstatic :: Static
611+ , pstatic :: Static
612+ , pcount :: RigCount
607613 }
608614 | TacImp { pargopts :: [ArgOpt]
609615 , pstatic :: Static
610616 , pscript :: PTerm
617+ , pcount :: RigCount
611618 }
612619 deriving (Show, Eq, Ord, Data, Generic, Typeable)
613620
@@ -616,24 +623,24 @@ deriving instance Binary Plicity
616623!-}
617624
618625is_scoped :: Plicity -> Maybe ImplicitInfo
619−is_scoped (Imp _ _ _ s _) = s
620−is_scoped _ = Nothing
626+is_scoped (Imp _ _ _ s _ _) = s
627+is_scoped _ = Nothing
621628
622629-- Top level implicit
623−impl = Imp [] Dynamic False (Just (Impl False True False)) False
630+impl = Imp [] Dynamic False (Just (Impl False True False)) False RigW
624631-- Machine generated top level implicit
625−impl_gen = Imp [] Dynamic False (Just (Impl False True True)) False
632+impl_gen = Imp [] Dynamic False (Just (Impl False True True)) False RigW
626633
627634-- Scoped implicits
628−forall_imp = Imp [] Dynamic False (Just (Impl False False True)) False
629−forall_constraint = Imp [] Dynamic False (Just (Impl True False True)) False
635+forall_imp = Imp [] Dynamic False (Just (Impl False False True)) False RigW
636+forall_constraint = Imp [] Dynamic False (Just (Impl True False True)) False RigW
630637
631−expl = Exp [] Dynamic False
632−expl_param = Exp [] Dynamic True
638+expl = Exp [] Dynamic False RigW
639+expl_param = Exp [] Dynamic True RigW
633640
634−constraint = Constraint [] Static
641+constraint = Constraint [] Static RigW
635642
636−tacimpl t = TacImp [] Dynamic t
643+tacimpl t = TacImp [] Dynamic t RigW
637644
638645data FnOpt = Inlinable -- ^ always evaluate when simplifying
639646 | TotalFn | PartialFn | CoveringFn
@@ -1617,8 +1624,8 @@ getInferTerm (App _ (App _ _ _) tm) = tm
16171624getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
16181625
16191626getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1620− where toTy (Lam t) = Pi Nothing t (TType (UVar [] 0))
1621− toTy (PVar t) = PVTy t
1627+ where toTy (Lam r t) = Pi r Nothing t (TType (UVar [] 0))
1628+ toTy (PVar _ t) = PVTy t
16221629 toTy b = b
16231630getInferType (App _ (App _ _ ty) _) = ty
16241631
@@ -1813,7 +1820,15 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
18131820 depth d . bracket p startPrec . group . align $
18141821 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
18151822 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1816− prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1823+ prettySe d p bnd (PPi (Exp l s _ rig) n _ ty sc)
1824+ | Rig0 <- rig =
1825+ depth d . bracket p startPrec . group $
1826+ enclose lparen rparen (group . align $ text "0" <+> prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1827+ st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1828+ | Rig1 <- rig =
1829+ depth d . bracket p startPrec . group $
1830+ enclose lparen rparen (group . align $ text "1" <+> prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1831+ st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
18171832 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
18181833 || ppopt_pinames ppo && uname n =
18191834 depth d . bracket p startPrec . group $
@@ -1833,24 +1848,28 @@ pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
18331848 case s of
18341849 Static -> text "%static" <> space
18351850 _ -> empty
1836− prettySe d p bnd (PPi (Imp l s _ fa _) n _ ty sc)
1851+ prettySe d p bnd (PPi (Imp l s _ fa _ rig) n _ ty sc)
18371852 | ppopt_impl ppo =
18381853 depth d . bracket p startPrec $
1839− lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1854+ lbrace <> showRig rig n <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
18401855 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
18411856 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
18421857 where
1858+ showRig Rig0 n = text "0" <+> prettyBindingOf n True
1859+ showRig Rig1 n = text "1" <+> prettyBindingOf n True
1860+ showRig _ n = prettyBindingOf n True
1861+
18431862 st =
18441863 case s of
18451864 Static -> text "%static" <> space
18461865 _ -> empty
1847− prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1866+ prettySe d p bnd (PPi (Constraint _ _ rig) n _ ty sc) =
18481867 depth d . bracket p startPrec $
18491868 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1850− prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch{}])) n _ ty sc) =
1869+ prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch{}]) rig) n _ ty sc) =
18511870 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
18521871 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1853− prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1872+ prettySe d p bnd (PPi (TacImp _ _ s rig) n _ ty sc) =
18541873 depth d . bracket p startPrec $
18551874 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
18561875 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
@@ -2378,7 +2397,7 @@ allNamesIn tm = nub $ ni 0 [] tm
23782397 ni i env (PUnquote tm) = ni (i - 1) env tm
23792398 ni i env tm = concatMap (ni i env) (children tm)
23802399
2381− niTacImp i env (TacImp _ _ scr) = ni i env scr
2400+ niTacImp i env (TacImp _ _ scr _) = ni i env scr
23822401 niTacImp _ _ _ = []
23832402
23842403
@@ -2414,7 +2433,7 @@ boundNamesIn tm = S.toList (ni 0 S.empty tm)
24142433 niTms i set [] = set
24152434 niTms i set (x : xs) = niTms i (ni i set x) xs
24162435
2417− niTacImp i set (TacImp _ _ scr) = ni i set scr
2436+ niTacImp i set (TacImp _ _ scr _) = ni i set scr
24182437 niTacImp i set _ = set
24192438
24202439-- Return names which are valid implicits in the given term (type).
@@ -2470,6 +2489,8 @@ implicitNamesIn uvars ist tm
24702489 ni 0 env (PIfThenElse _ c t f) = mapM_ (ni 0 env) [c, t, f]
24712490 ni 0 env (PLam fc n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
24722491 ni 0 env (PPi p n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2492+ ni 0 env (PLet fc n _ ty val sc) = do ni 0 env ty;
2493+ ni 0 env val; ni 0 (n:env) sc
24732494 ni 0 env (PRewrite _ _ l r _) = do ni 0 env l; ni 0 env r
24742495 ni 0 env (PTyped l r) = do ni 0 env l; ni 0 env r
24752496 ni 0 env (PPair _ _ _ l r) = do ni 0 env l; ni 0 env r
@@ -2523,7 +2544,7 @@ namesIn uvars ist tm = nub $ ni 0 [] tm
25232544
25242545 ni i env tm = concatMap (ni i env) (children tm)
25252546
2526− niTacImp i env (TacImp _ _ scr) = ni i env scr
2547+ niTacImp i env (TacImp _ _ scr _) = ni i env scr
25272548 niTacImp _ _ _ = []
25282549
25292550-- Return which of the given names are used in the given term.
@@ -2558,7 +2579,7 @@ usedNamesIn vars ist tm = nub $ ni 0 [] tm
25582579
25592580 ni i env tm = concatMap (ni i env) (children tm)
25602581
2561− niTacImp i env (TacImp _ _ scr) = ni i env scr
2582+ niTacImp i env (TacImp _ _ scr _) = ni i env scr
25622583 niTacImp _ _ _ = []
25632584
25642585-- Return the list of inaccessible (= dotted) positions for a name.
src/Idris/Apropos.hs+2−2
@@ -72,8 +72,8 @@ instance Apropos Def where
7272 isApropos str (CaseOp _ ty ty' _ _ _) = isApropos str ty
7373
7474instance Apropos (Binder (TT Name)) where
75− isApropos str (Lam ty) = str == T.pack "\\" || isApropos str ty
76− isApropos str (Pi _ ty _) = str == T.pack "->" || isApropos str ty
75+ isApropos str (Lam _ ty) = str == T.pack "\\" || isApropos str ty
76+ isApropos str (Pi _ _ ty _) = str == T.pack "->" || isApropos str ty
7777 isApropos str (Let ty val) = str == T.pack "let" || isApropos str ty || isApropos str val
7878 isApropos str (NLet ty val) = str == T.pack "let" || isApropos str ty || isApropos str val
7979 isApropos str _ = False -- these shouldn't occur in defined libraries
src/Idris/CaseSplit.hs+4−4
@@ -212,7 +212,7 @@ argTys ist (PRef fc hls n)
212212 [ty] -> let ty' = normalise (tt_ctxt ist) [] ty in
213213 map (tyName . snd) (getArgTys ty') ++ repeat Nothing
214214 _ -> repeat Nothing
215− where tyName (Bind _ (Pi _ _ _) _) = Just (sUN "->")
215+ where tyName (Bind _ (Pi _ _ _ _) _) = Just (sUN "->")
216216 tyName t | (P _ d _, [_, ty]) <- unApply t,
217217 d == sUN "Delayed" = tyName ty
218218 | (P _ n _, _) <- unApply t = Just n
@@ -408,14 +408,14 @@ getClause l fn un fp
408408 return (showLHSName un ++ " " ++ ap ++ "= ?"
409409 ++ showRHSName un ++ "_rhs")
410410 where mkApp :: IState -> PTerm -> [Name] -> String
411− mkApp i (PPi (Exp _ _ False) (MN _ _) _ ty sc) used
411+ mkApp i (PPi (Exp _ _ False _) (MN _ _) _ ty sc) used
412412 = let n = getNameFrom i used ty in
413413 show n ++ " " ++ mkApp i sc (n : used)
414− mkApp i (PPi (Exp _ _ False) (UN n) _ ty sc) used
414+ mkApp i (PPi (Exp _ _ False _) (UN n) _ ty sc) used
415415 | thead n == '_'
416416 = let n = getNameFrom i used ty in
417417 show n ++ " " ++ mkApp i sc (n : used)
418− mkApp i (PPi (Exp _ _ False) n _ _ sc) used
418+ mkApp i (PPi (Exp _ _ False _) n _ _ sc) used
419419 = show n ++ " " ++ mkApp i sc (n : used)
420420 mkApp i (PPi _ _ _ _ sc) used = mkApp i sc used
421421 mkApp i _ _ = ""
src/Idris/CmdOptions.hs+3−1
@@ -134,7 +134,9 @@ parseFlags = many $
134134 <|> flag' ShowDocDir (long "docdir" <> help "Display idrisdoc install directory")
135135 <|> flag' ShowIncs (long "include" <> help "Display the includes flags")
136136
137− <|> flag' Verbose (short 'V' <> long "verbose" <> help "Loud verbosity")
137+ <|> flag' (Verbose 3) (long "V2" <> help "Loudest verbosity")
138+ <|> flag' (Verbose 2) (long "V1" <> help "Louder verbosity")
139+ <|> flag' (Verbose 1) (short 'V' <> long "V0" <>long "verbose" <> help "Loud verbosity")
138140
139141 <|> (IBCSubDir <$> strOption (long "ibcsubdir" <> metavar "FILE" <> help "Write IBC files into sub directory"))
140142 <|> (ImportDir <$> strOption (short 'i' <> long "idrispath" <> help "Add directory to the list of import paths"))
src/Idris/Core/Binary.hs+31−11
@@ -490,6 +490,19 @@ instance Binary Raw where
490490 return (RUType x1)
491491 _ -> error "Corrupted binary data for Raw"
492492
493+instance Binary RigCount where
494+ put x = case x of
495+ Rig0 -> putWord8 0
496+ Rig1 -> putWord8 1
497+ RigW -> putWord8 2
498+ get = do i <- getWord8
499+ case i of
500+ 0 -> return Rig0
501+ 1 -> return Rig1
502+ 2 -> return RigW
503+ _ -> error "Corrupted binary data for RigCount"
504+
505+
493506instance Binary ImplicitInfo where
494507 put x
495508 = case x of
@@ -502,12 +515,14 @@ instance Binary ImplicitInfo where
502515instance (Binary b) => Binary (Binder b) where
503516 put x
504517 = case x of
505− Lam x1 -> do putWord8 0
506− put x1
507− Pi x1 x2 x3 -> do putWord8 1
508− put x1
509− put x2
510− put x3
518+ Lam x1 x2 -> do putWord8 0
519+ put x1
520+ put x2
521+ Pi x1 x2 x3 x4 -> do putWord8 1
522+ put x1
523+ put x2
524+ put x3
525+ put x4
511526 Let x1 x2 -> do putWord8 2
512527 put x1
513528 put x2
@@ -523,19 +538,22 @@ instance (Binary b) => Binary (Binder b) where
523538 Guess x1 x2 -> do putWord8 6
524539 put x1
525540 put x2
526− PVar x1 -> do putWord8 7
527− put x1
541+ PVar x1 x2 -> do putWord8 7
542+ put x1
543+ put x2
528544 PVTy x1 -> do putWord8 8
529545 put x1
530546 get
531547 = do i <- getWord8
532548 case i of
533549 0 -> do x1 <- get
534− return (Lam x1)
550+ x2 <- get
551+ return (Lam x1 x2)
535552 1 -> do x1 <- get
536553 x2 <- get
537554 x3 <- get
538− return (Pi x1 x2 x3)
555+ x4 <- get
556+ return (Pi x1 x2 x3 x4)
539557 2 -> do x1 <- get
540558 x2 <- get
541559 return (Let x1 x2)
@@ -552,7 +570,8 @@ instance (Binary b) => Binary (Binder b) where
552570 x2 <- get
553571 return (Guess x1 x2)
554572 7 -> do x1 <- get
555− return (PVar x1)
573+ x2 <- get
574+ return (PVar x1 x2)
556575 8 -> do x1 <- get
557576 return (PVTy x1)
558577 _ -> error "Corrupted binary data for Binder"
@@ -639,6 +658,7 @@ instance {- (Binary n) => -} Binary (TT Name) where
639658 TType x1 -> do putWord8 7
640659 put x1
641660 Impossible -> putWord8 8
661+ Inferred x1 -> put x1 -- drop the 'Inferred'
642662 UType x1 -> do putWord8 10
643663 put x1
644664 get
src/Idris/Core/CaseTree.hs+63−7
@@ -244,14 +244,18 @@ type CaseBuilder a = ReaderT ErasureInfo (State CS) a
244244runCaseBuilder :: ErasureInfo -> CaseBuilder a -> (CS -> (a, CS))
245245runCaseBuilder ei bld = runState $ runReaderT bld ei
246246
247−data Phase = CompileTime | RunTime
247+data Phase = CoverageCheck [Int] -- list of positions explicitly given
248+ | CompileTime
249+ | RunTime
248250 deriving (Show, Eq)
249251
250252-- Generate a simple case tree
251253-- Work Right to Left
252254
253255simpleCase :: Bool -> SC -> Bool ->
254− Phase -> FC -> [Int] ->
256+ Phase -> FC ->
257+ -- Following two can be empty lists when Phase = CoverageCheck
258+ [Int] -> -- Inaccessible argument positions
255259 [(Type, Bool)] -> -- (Argument type, whether it's canonical)
256260 [([Name], Term, Term)] ->
257261 ErasureInfo ->
@@ -291,7 +295,7 @@ simpleCase tc defcase reflect phase fc inacc argtys cs erInfo
291295 -- Check that all pattern variables are reachable by a case split
292296 -- Otherwise, they won't make sense on the RHS.
293297 chkAccessible (avs, l, c)
294− | phase == RunTime || reflect = return (l, c)
298+ | phase /= CompileTime || reflect = return (l, c)
295299 | otherwise = do mapM_ (acc l) avs
296300 return (l, c)
297301
@@ -345,6 +349,7 @@ isConstType _ _ = False
345349
346350data Pat = PCon Bool Name Int [Pat]
347351 | PConst Const
352+ | PInferred Pat
348353 | PV Name Type
349354 | PSuc Pat -- special case for n+1 on Integer
350355 | PReflected Name [Pat]
@@ -383,10 +388,11 @@ toPat reflect tc = map $ toPat' []
383388
384389 toPat' [] (P Bound n ty) = PV n ty
385390 toPat' args (App _ f a) = toPat' (a : args) f
391+ toPat' args (Inferred tm) = PInferred (toPat' args tm)
386392 toPat' [] (Constant x) | isTypeConst x = PTyPat
387393 | otherwise = PConst x
388394
389− toPat' [] (Bind n (Pi _ t _) sc)
395+ toPat' [] (Bind n (Pi _ _ t _) sc)
390396 | reflect && noOccurrence n sc
391397 = PReflected (sUN "->") [toPat' [] t, toPat' [] sc]
392398
@@ -438,6 +444,20 @@ order :: Phase -> [(Name, Bool)] -> [Clause] -> [Bool] -> ([Name], [Clause])
438444-- order CompileTime ns cs _ = (map fst ns, cs)
439445order _ [] cs cans = ([], cs)
440446order _ ns' [] cans = (map fst ns', [])
447+order (CoverageCheck pos) ns' cs cans
448+ = let ns_out = pick 0 [] (map fst ns')
449+ cs_out = map pickClause cs in
450+ (ns_out, cs_out)
451+ where
452+ pickClause (pats, def) = (pick 0 [] pats, def)
453+
454+ -- Order the list so that things in a position in 'pos' are in the first
455+ -- part, then all the other things later. Otherwise preserve order.
456+ pick i skipped [] = reverse skipped
457+ pick i skipped (x : xs)
458+ | i `elem` pos = x : pick (i + 1) skipped xs
459+ | otherwise = pick (i + 1) (x : skipped) xs
460+
441461order phase ns' cs cans
442462 = let patnames = transpose (map (zip ns') (map (zip cans) (map fst cs)))
443463 -- only sort the arguments where there is no clash in
@@ -484,6 +504,41 @@ order phase ns' cs cans
484504 numNames xs (_ : ps) = numNames xs ps
485505 numNames xs [] = length xs
486506
507+-- Reorder the patterns in the clause so that the PInferred patterns come
508+-- last. Also strip 'PInferred' from the top level patterns so that we can
509+-- go ahead and match.
510+orderByInf :: [Name] -> [Clause] -> ([Name], [Clause])
511+orderByInf vs cs = let alwaysInf = getInf cs in
512+ (selectInf alwaysInf vs,
513+ map deInf (map (selectExp alwaysInf) cs))
514+ where
515+ getInf [] = []
516+ getInf [(pats, def)] = infPos 0 pats
517+ getInf ((pats, def) : cs) = infPos 0 pats `intersect` getInf cs
518+
519+ selectExp :: [Int] -> Clause -> Clause
520+ selectExp infs (pats, def)
521+ = let (notInf, inf) = splitPats 0 infs [] [] pats in
522+ (notInf ++ inf, def)
523+
524+ selectInf :: [Int] -> [a] -> [a]
525+ selectInf infs ns = let (notInf, inf) = splitPats 0 infs [] [] ns in
526+ notInf ++ inf
527+
528+ splitPats i infpos notInf inf [] = (reverse notInf, reverse inf)
529+ splitPats i infpos notInf inf (p : ps)
530+ | i `elem` infpos = splitPats (i + 1) infpos notInf (p : inf) ps
531+ | otherwise = splitPats (i + 1) infpos (p : notInf) inf ps
532+
533+ infPos i [] = []
534+ infPos i (PInferred p : ps) = i : infPos (i + 1) ps
535+ infPos i (_ : ps) = infPos (i + 1) ps
536+
537+ deInf (pats, def) = (map deInfPat pats, def)
538+
539+ deInfPat (PInferred p) = p
540+ deInfPat p = p
541+
487542match :: [Name] -> [Clause] -> SC -- error case
488543 -> CaseBuilder SC
489544match [] (([], ret) : xs) err
@@ -492,8 +547,9 @@ match [] (([], ret) : xs) err
492547 case snd ret of
493548 Impossible -> return ImpossibleCase
494549 tm -> return $ STerm tm -- run out of arguments
495−match vs cs err = do let ps = partition cs
496− mixture vs ps err
550+match vs cs err = do let (vs', de_inf) = orderByInf vs cs
551+ ps = partition de_inf
552+ mixture vs' ps err
497553
498554mixture :: [Name] -> [Partition] -> SC -> CaseBuilder SC
499555mixture vs [] err = return err
@@ -767,7 +823,7 @@ prune proj (Case up n alts) = case alts' of
767823prune _ t = t
768824
769825stripLambdas :: CaseDef -> CaseDef
770−stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
826+stripLambdas (CaseDef ns (STerm (Bind x (Lam _ _) sc)) tm)
771827 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
772828stripLambdas x = x
773829
src/Idris/Core/DeepSeq.hs+1
@@ -40,6 +40,7 @@ instance NFData ConstraintFC
4040instance NFData Err
4141instance NFData ErrorReportPart
4242instance NFData ImplicitInfo
43+instance NFData RigCount
4344instance (NFData b) => NFData (Binder b)
4445instance NFData UExp
4546instance NFData NameType
src/Idris/Core/Elaborate.hs+39−36
@@ -24,6 +24,7 @@ import Idris.Core.ProofTerm (bound_in, bound_in_term, getProofTerm, mkProofTerm,
2424import Idris.Core.TT
2525import Idris.Core.Typecheck
2626import Idris.Core.Unify
27+import Idris.Core.WHNF
2728
2829import Util.Pretty hiding (fill)
2930
@@ -98,7 +99,7 @@ setNextName :: Elab' aux ()
9899setNextName = do env <- get_env
99100 ES (p, a) s e <- get
100101 let pargs = map fst (getArgTys (ptype p))
101− initNextNameFrom (pargs ++ map fst env)
102+ initNextNameFrom (pargs ++ map fstEnv env)
102103
103104initNextNameFrom :: [Name] -> Elab' aux ()
104105initNextNameFrom ns = do ES (p, a) s e <- get
@@ -326,7 +327,7 @@ checkInjective (tm, l, r) = do ctxt <- get_context
326327 isInj ctxt (App _ f a) = isInj ctxt f
327328 isInj ctxt (Constant _) = True
328329 isInj ctxt (TType _) = True
329− isInj ctxt (Bind _ (Pi _ _ _) sc) = True
330+ isInj ctxt (Bind _ (Pi _ _ _ _) sc) = True
330331 isInj ctxt _ = False
331332
332333-- | get implementation argument names
@@ -422,8 +423,11 @@ computeLet n = processTactic' (ComputeLet n)
422423simplify :: Elab' aux ()
423424simplify = processTactic' Simplify
424425
425−hnf_compute :: Elab' aux ()
426−hnf_compute = processTactic' HNF_Compute
426+whnf_compute :: Elab' aux ()
427+whnf_compute = processTactic' WHNF_Compute
428+
429+whnf_compute_args :: Elab' aux ()
430+whnf_compute_args = processTactic' WHNF_ComputeArgs
427431
428432eval_in :: Raw -> Elab' aux ()
429433eval_in t = processTactic' (EvalIn t)
@@ -437,8 +441,8 @@ intro n = processTactic' (Intro n)
437441introTy :: Raw -> Maybe Name -> Elab' aux ()
438442introTy ty n = processTactic' (IntroTy ty n)
439443
440−forall :: Name -> Maybe ImplicitInfo -> Raw -> Elab' aux ()
441−forall n i t = processTactic' (Forall n i t)
444+forall :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> Elab' aux ()
445+forall n r i t = processTactic' (Forall n r i t)
442446
443447letbind :: Name -> Raw -> Raw -> Elab' aux ()
444448letbind n t v = processTactic' (LetBind n t v)
@@ -459,18 +463,17 @@ equiv :: Raw -> Elab' aux ()
459463equiv tm = processTactic' (Equiv tm)
460464
461465-- | Turn the current hole into a pattern variable with the provided
462−-- name, made unique if MN
466+-- name, made unique if not the same as the head of the hole queue
463467patvar :: Name -> Elab' aux ()
464468patvar n@(SN _) = do apply (Var n) []; solve
465469patvar n = do env <- get_env
466470 hs <- get_holes
467− if (n `elem` map fst env) then do apply (Var n) []; solve
468− else do n' <- case n of
469− UN _ -> return $! n
470− MN _ _ -> unique_hole n
471− NS _ _ -> return $! n
472− x -> return $! n
473− processTactic' (PatVar n')
471+ if (n `elem` map fstEnv env) then do apply (Var n) []; solve
472+ else do n' <- case hs of
473+ (h : hs) -> if n == h then return n
474+ else unique_hole n
475+ _ -> unique_hole n
476+ processTactic' (PatVar n)
474477
475478-- | Turn the current hole into a pattern variable with the provided
476479-- name, but don't make MNs unique.
@@ -478,11 +481,11 @@ patvar' :: Name -> Elab' aux ()
478481patvar' n@(SN _) = do apply (Var n) [] ; solve
479482patvar' n = do env <- get_env
480483 hs <- get_holes
481− if (n `elem` map fst env) then do apply (Var n) [] ; solve
484+ if (n `elem` map fstEnv env) then do apply (Var n) [] ; solve
482485 else processTactic' (PatVar n)
483486
484−patbind :: Name -> Elab' aux ()
485−patbind n = processTactic' (PatBind n)
487+patbind :: Name -> RigCount -> Elab' aux ()
488+patbind n r = processTactic' (PatBind n r)
486489
487490focus :: Name -> Elab' aux ()
488491focus n = processTactic' (Focus n)
@@ -575,9 +578,9 @@ prepare_apply fn imps =
575578 -- Count arguments to check if we need to normalise the type
576579 let usety = if argsOK (finalise ty) imps
577580 then finalise ty
578− else normalise ctxt env (finalise ty)
581+ else whnfArgs ctxt env (finalise ty)
579582 claims <- -- trace (show (fn, imps, ty, map fst env, normalise ctxt env (finalise ty))) $
580− mkClaims usety imps [] (map fst env)
583+ mkClaims usety imps [] (map fstEnv env)
581584 ES (p, a) s prev <- get
582585 -- reverse the claims we made so that args go left to right
583586 let n = length (filter not imps)
@@ -586,7 +589,7 @@ prepare_apply fn imps =
586589 return $! claims
587590 where
588591 argsOK :: Type -> [a] -> Bool
589− argsOK (Bind n (Pi _ _ _) sc) (i : is) = argsOK sc is
592+ argsOK (Bind n (Pi _ _ _ _) sc) (i : is) = argsOK sc is
590593 argsOK _ (i : is) = False
591594 argsOK _ [] = True
592595
@@ -595,13 +598,13 @@ prepare_apply fn imps =
595598 -> [(Name, Name)] -- ^ Accumulator for produced claims
596599 -> [Name] -- ^ Hypotheses
597600 -> Elab' aux [(Name, Name)] -- ^ The names of the arguments and their holes, resp.
598− mkClaims (Bind n' (Pi _ t_in _) sc) (i : is) claims hs =
601+ mkClaims (Bind n' (Pi _ _ t_in _) sc) (i : is) claims hs =
599602 do let t = rebind hs t_in
600603 n <- getNameFrom (mkMN n')
601604-- when (null claims) (start_unify n)
602605 let sc' = instantiate (P Bound n t) sc
603606 env <- get_env
604− claim n (forgetEnv (map fst env) t)
607+ claim n (forgetEnv (map fstEnv env) t)
605608 when i (movelast n)
606609 mkClaims sc' is ((n', n) : claims) hs
607610 mkClaims t [] claims _ = return $! (reverse claims)
@@ -709,7 +712,7 @@ apply_elab n args =
709712 priOrder _ Nothing = GT
710713 priOrder (Just (x, _)) (Just (y, _)) = compare x y
711714
712− doClaims (Bind n' (Pi _ t _) sc) (i : is) claims =
715+ doClaims (Bind n' (Pi _ _ t _) sc) (i : is) claims =
713716 do n <- unique_hole (mkMN n')
714717 when (null claims) (start_unify n)
715718 let sc' = instantiate (P Bound n t) sc
@@ -745,14 +748,14 @@ checkPiGoal n
745748 = do g <- goal
746749 ctxt <- get_context
747750 env <- get_env
748− case (normalise ctxt env g) of
749− Bind _ (Pi _ _ _) _ -> return ()
751+ case (whnf ctxt env g) of
752+ Bind _ (Pi _ _ _ _) _ -> return ()
750753 _ -> do a <- getNameFrom (sMN 0 "__pargTy")
751754 b <- getNameFrom (sMN 0 "__pretTy")
752755 f <- getNameFrom (sMN 0 "pf")
753756 claim a RType
754757 claim b RType
755− claim f (RBind n (Pi Nothing (Var a) RType) (Var b))
758+ claim f (RBind n (Pi RigW Nothing (Var a) RType) (Var b))
756759 movelast a
757760 movelast b
758761 fill (Var f)
@@ -772,7 +775,7 @@ infer_app infer fun arg str =
772775 s <- getNameFrom (sMN 0 "is")
773776 claim a RType
774777 claim b RType
775− claim f (RBind (sMN 0 "_aX") (Pi Nothing (Var a) RType) (Var b))
778+ claim f (RBind (sMN 0 "_aX") (Pi RigW Nothing (Var a) RType) (Var b))
776779 tm <- get_term
777780 start_unify s
778781 -- if 'infer' is set, we're assuming it's a simply typed application
@@ -820,10 +823,10 @@ dep_app fun arg str =
820823 focus s; attack;
821824 ctxt <- get_context
822825 env <- get_env
823− case normalise ctxt env fty of
826+ case whnf ctxt env fty of
824827 -- if f gives a function type, unify our argument type with
825828 -- f's expected argument type
826− Bind _ (Pi _ argty _) _ -> unifyGoal (forget argty)
829+ Bind _ (Pi _ _ argty _) _ -> unifyGoal (forget argty)
827830 -- Can't infer a type for 'f', so fail here (and drop back to
828831 -- simply typed application where we infer the type for f)
829832 _ -> fail "Can't make type"
@@ -842,11 +845,11 @@ dep_app fun arg str =
842845
843846-- Abstract over an argument of unknown type, giving a name for the hole
844847-- which we'll fill with the argument type too.
845−arg :: Name -> Maybe ImplicitInfo -> Name -> Elab' aux ()
846−arg n i tyhole = do ty <- unique_hole tyhole
847− claim ty RType
848− movelast ty
849− forall n i (Var ty)
848+arg :: Name -> RigCount -> Maybe ImplicitInfo -> Name -> Elab' aux ()
849+arg n r i tyhole = do ty <- unique_hole tyhole
850+ claim ty RType
851+ movelast ty
852+ forall n r i (Var ty)
850853
851854-- try a tactic, if it adds any unification problem, return an error
852855no_errors :: Elab' aux () -> Maybe Err -> Elab' aux ()
@@ -866,7 +869,7 @@ no_errors tac err
866869 case reverse ps' of
867870 ((x, y, _, env, inerr, while, _) : _) ->
868871 let (xp, yp) = getProvenance inerr
869− env' = map (\(x, b) -> (x, binderTy b)) env in
872+ env' = map (\(x, rig, b) -> (x, binderTy b)) env in
870873 lift $ tfail $
871874 case err of
872875 Nothing -> CantUnify False (x, xp) (y, yp) inerr env' 0
@@ -1010,7 +1013,7 @@ debugElaborator msg = do ps <- fmap proof get
10101013 getHoleInfo h = do focus h
10111014 g <- goal
10121015 env <- get_env
1013− return (h, g, env)
1016+ return (h, g, envBinders env)
10141017
10151018qshow :: Fails -> String
10161019qshow fs = show (map (\ (x, y, _, _, _, _, _) -> (x, y)) fs)
src/Idris/Core/Evaluate.hs+129−77
@@ -11,20 +11,23 @@ Maintainer : The Idris Community.
1111
1212module Idris.Core.Evaluate(normalise, normaliseTrace, normaliseC,
1313 normaliseAll, normaliseBlocking, toValue, quoteTerm,
14− rt_simplify, simplify, specialise, unfold, convEq, convEq',
14+ rt_simplify, simplify, inlineSmall,
15+ specialise, unfold, convEq, convEq',
1516 Def(..), CaseInfo(..), CaseDefs(..),
1617 Accessibility(..), Injectivity, Totality(..), PReason(..), MetaInformation(..),
1718 Context, initContext, ctxtAlist, next_tvar,
18− addToCtxt, setAccess, setInjective, setTotal, setMetaInformation, addCtxtDef, addTyDecl,
19+ addToCtxt, setAccess, setInjective, setTotal, setRigCount,
20+ setMetaInformation, addCtxtDef, addTyDecl,
1921 addDatatype, addCasedef, simplifyCasedef, addOperator,
2022 lookupNames, lookupTyName, lookupTyNameExact, lookupTy, lookupTyExact,
2123 lookupP, lookupP_all, lookupDef, lookupNameDef, lookupDefExact, lookupDefAcc, lookupDefAccExact, lookupVal,
22− mapDefCtxt,
24+ mapDefCtxt, tcReducible,
2325 lookupTotal, lookupTotalExact, lookupInjectiveExact,
26+ lookupRigCount, lookupRigCountExact,
2427 lookupNameTotal, lookupMetaInformation, lookupTyEnv, isTCDict,
2528 isCanonical, isDConName, canBeDConName, isTConName, isConName, isFnName,
2629 Value(..), Quote(..), initEval, uniqueNameCtxt, uniqueBindersCtxt, definitions,
27− isUniverse) where
30+ isUniverse, linearCheck, linearCheckArg) where
2831
2932import Idris.Core.CaseTree
3033import Idris.Core.TT
@@ -71,6 +74,16 @@ data Value = VP NameType Name Value
7174-- | VLazy Env [Value] Term
7275 | VTmp Int
7376
77+canonical :: Value -> Bool
78+canonical (VP (DCon _ _ _) _ _) = True
79+canonical (VApp f a) = canonical f
80+canonical (VConstant _) = True
81+canonical (VType _) = True
82+canonical (VUType _) = True
83+canonical VErased = True
84+canonical _ = False
85+
86+
7487instance Show Value where
7588 show x = show $ evalState (quote 100 x) initEval
7689
@@ -148,16 +161,9 @@ simplify ctxt env t
148161
149162-- | Like simplify, but we only reduce functions that are marked as okay to
150163-- inline, and don't reduce lets
151−inline :: Context -> Env -> TT Name -> TT Name
152−inline ctxt env t
153− = evalState (do val <- eval False ctxt [(sUN "lazy", 0),
154− (sUN "force", 0),
155− (sUN "Force", 0),
156− (sUN "assert_smaller", 0),
157− (sUN "assert_total", 0),
158− (sUN "par", 0),
159− (sUN "prim__syntactic_eq", 0),
160− (sUN "fork", 0)]
164+inlineSmall :: Context -> Env -> TT Name -> TT Name
165+inlineSmall ctxt env t
166+ = evalState (do val <- eval False ctxt []
161167 (map finalEntry env) (finalise t)
162168 [Simplify False]
163169 quote 0 val) initEval
@@ -193,13 +199,13 @@ unfold ctxt env ns t
193199
194200-- unbindEnv env (quote 0 (eval ctxt (bindEnv env t)))
195201
196−finalEntry :: (Name, Binder (TT Name)) -> (Name, Binder (TT Name))
197−finalEntry (n, b) = (n, fmap finalise b)
202+finalEntry :: (Name, RigCount, Binder (TT Name)) -> (Name, RigCount, Binder (TT Name))
203+finalEntry (n, r, b) = (n, r, fmap finalise b)
198204
199205bindEnv :: EnvTT n -> TT n -> TT n
200206bindEnv [] tm = tm
201−bindEnv ((n, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm)
202−bindEnv ((n, b):bs) tm = Bind n b (bindEnv bs tm)
207+bindEnv ((n, r, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm)
208+bindEnv ((n, r, b):bs) tm = Bind n b (bindEnv bs tm)
203209
204210unbindEnv :: EnvTT n -> TT n -> TT n
205211unbindEnv [] tm = tm
@@ -260,6 +266,8 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
260266 atRepl = AtREPL `elem` opts
261267 unfold = Unfold `elem` opts
262268
269+ noFree = all canonical . map snd
270+
263271 -- returns 'True' if the function should block
264272 -- normal evaluation should return false
265273 blockSimplify (CaseInfo inl always dict) n stk
@@ -276,21 +284,21 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
276284 | otherwise = cases_compiletime cd
277285
278286 ev ntimes stk top env (P _ n ty)
279− | Just (Let t v) <- lookup n genv = ev ntimes stk top env v
287+ | Just (Let t v) <- lookupBinder n genv = ev ntimes stk top env v
280288 ev ntimes_in stk top env (P Ref n ty)
281289 = do let limit = if simpl then 100 else 10000
282290 (u, ntimes) <- usable spec unfold limit n ntimes_in
283− let red = u && (tcReducible n ctxt || spec || atRepl
291+ let red = u && (tcReducible n ctxt || spec || (atRepl && noFree env)
284292 || runtime || unfold
285293 || sUN "assert_total" `elem` stk)
286294 if red then
287− do let val = lookupDefAcc n (spec || unfold || atRepl || runtime) ctxt
295+ do let val = lookupDefAccExact n (spec || unfold || (atRepl && noFree env) || runtime) ctxt
288296 case val of
289− [(Function _ tm, Public)] ->
297+ Just (Function _ tm, Public) ->
290298 ev ntimes (n:stk) True env tm
291− [(TyDecl nt ty, _)] -> do vty <- ev ntimes stk True env ty
292− return $ VP nt n vty
293− [(CaseOp ci _ _ _ _ cd, acc)]
299+ Just (TyDecl nt ty, _) -> do vty <- ev ntimes stk True env ty
300+ return $ VP nt n vty
301+ Just (CaseOp ci _ _ _ _ cd, acc)
294302 | (acc == Public || acc == Hidden) &&
295303-- || sUN "assert_total" `elem` stk) &&
296304 null (fst (cases_compiletime cd)) -> -- unoptimised version
@@ -331,7 +339,7 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
331339 return $ VBind True n (Let t' v') (\x -> return sc')
332340 ev ntimes stk top env (Bind n b sc)
333341 = do b' <- vbind env b
334− let n' = uniqueName n (map fst genv ++ map fst env)
342+ let n' = uniqueName n (map fstEnv genv ++ map fst env)
335343 return $ VBind True -- (vinstances 0 sc < 2)
336344 n' b' (\x -> ev ntimes stk False ((n', x):env) sc)
337345 where vbind env t
@@ -353,7 +361,7 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
353361 evApply ntimes' stk top env [l',t',arg'] d'
354362 -- Treat "assert_total" specially, as long as it's defined!
355363 ev ntimes stk top env (App _ (App _ (P _ n@(UN at) _) _) arg)
356− | [(CaseOp _ _ _ _ _ _, _)] <- lookupDefAcc n (spec || atRepl || runtime) ctxt,
364+ | Just (CaseOp _ _ _ _ _ _, _) <- lookupDefAccExact n (spec || (atRepl && noFree env)|| runtime) ctxt,
357365 at == txt "assert_total" && not (simpl || unfold)
358366 = ev ntimes (n : stk) top env arg
359367 ev ntimes stk top env (App _ f a)
@@ -372,6 +380,7 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
372380 ev ntimes stk top env (Constant c) = return $ VConstant c
373381 ev ntimes stk top env Erased = return VErased
374382 ev ntimes stk top env Impossible = return VImpossible
383+ ev ntimes stk top env (Inferred tm) = ev ntimes stk top env tm
375384 ev ntimes stk top env (TType i) = return $ VType i
376385 ev ntimes stk top env (UType u) = return $ VUType u
377386
@@ -381,9 +390,9 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
381390 = apply ntimes stk top env f args
382391
383392 reapply ntimes stk top env f@(VP Ref n ty) args
384− = let val = lookupDefAcc n (spec || atRepl || runtime) ctxt in
393+ = let val = lookupDefAccExact n (spec || (atRepl && noFree env) || runtime) ctxt in
385394 case val of
386− [(CaseOp ci _ _ _ _ cd, acc)] ->
395+ Just (CaseOp ci _ _ _ _ cd, acc) ->
387396 let (ns, tree) = getCases cd in
388397 do c <- evCase ntimes n (n:stk) top env ns args tree
389398 case c of
@@ -396,20 +405,20 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
396405 = reapply ntimes stk top env f (a : args)
397406 reapply ntimes stk top env v args = return v
398407
399− apply ntimes stk top env (VBind True n (Lam t) sc) (a:as)
408+ apply ntimes stk top env (VBind True n (Lam _ t) sc) (a:as)
400409 = do a' <- sc a
401410 app <- apply ntimes stk top env a' as
402411 wknV 1 app
403412 apply ntimes_in stk top env f@(VP Ref n ty) args
404413 = do let limit = if simpl then 100 else 10000
405414 (u, ntimes) <- usable spec unfold limit n ntimes_in
406− let red = u && (tcReducible n ctxt || spec || atRepl
415+ let red = u && (tcReducible n ctxt || spec || (atRepl && noFree env)
407416 || unfold || runtime
408417 || sUN "assert_total" `elem` stk)
409418 if red then
410− do let val = lookupDefAcc n (spec || unfold || atRepl || runtime) ctxt
419+ do let val = lookupDefAccExact n (spec || unfold || (atRepl && noFree env) || runtime) ctxt
411420 case val of
412− [(CaseOp ci _ _ _ _ cd, acc)]
421+ Just (CaseOp ci _ _ _ _ cd, acc)
413422 | acc == Public || acc == Hidden ->
414423 -- unoptimised version
415424 let (ns, tree) = getCases cd in
@@ -420,7 +429,7 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
420429 case c of
421430 (Nothing, _) -> return $ unload env (VP Ref n ty) args
422431 (Just v, rest) -> evApply ntimes stk top env rest v
423− [(Operator _ i op, _)] ->
432+ Just (Operator _ i op, _) ->
424433 if (i <= length args)
425434 then case op (take i args) of
426435 Nothing -> return $ unload env (VP Ref n ty) args
@@ -513,7 +522,7 @@ eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where
513522 | Just v <- findDefault alts = return $ Just (amap, v)
514523 chooseAlt env _ (VP _ n _, args) alts amap
515524 | Just (ns, sc) <- findFn n alts = return $ Just (updateAmap (zip ns args) amap, sc)
516− chooseAlt env _ (VBind _ _ (Pi i s k) t, []) alts amap
525+ chooseAlt env _ (VBind _ _ (Pi _ i s k) t, []) alts amap
517526 | Just (ns, sc) <- findFn (sUN "->") alts
518527 = do t' <- t (VV 0) -- we know it's not in scope or it's not a pattern
519528 return $ Just (updateAmap (zip ns [s, t']) amap, sc)
@@ -629,17 +638,17 @@ convEq ctxt holes topx topy = ceq [] topx topy where
629638 | x `elem` holes || y `elem` holes = return True
630639 | x == y || (x, y) `elem` ps || (y,x) `elem` ps = return True
631640 | otherwise = sameDefs ps x y
632− ceq ps x (Bind n (Lam t) (App _ y (V 0)))
641+ ceq ps x (Bind n (Lam _ t) (App _ y (V 0)))
633642 = ceq ps x (substV (P Bound n t) y)
634− ceq ps (Bind n (Lam t) (App _ x (V 0))) y
643+ ceq ps (Bind n (Lam _ t) (App _ x (V 0))) y
635644 = ceq ps (substV (P Bound n t) x) y
636− ceq ps x (Bind n (Lam t) (App _ y (P Bound n' _)))
645+ ceq ps x (Bind n (Lam _ t) (App _ y (P Bound n' _)))
637646 | n == n' = ceq ps x y
638− ceq ps (Bind n (Lam t) (App _ x (P Bound n' _))) y
647+ ceq ps (Bind n (Lam _ t) (App _ x (P Bound n' _))) y
639648 | n == n' = ceq ps x y
640649
641− ceq ps (Bind n (PVar t) sc) y = ceq ps sc y
642− ceq ps x (Bind n (PVar t) sc) = ceq ps x sc
650+ ceq ps (Bind n (PVar _ t) sc) y = ceq ps sc y
651+ ceq ps x (Bind n (PVar _ t) sc) = ceq ps x sc
643652 ceq ps (Bind n (PVTy t) sc) y = ceq ps sc y
644653 ceq ps x (Bind n (PVTy t) sc) = ceq ps x sc
645654
@@ -655,7 +664,7 @@ convEq ctxt holes topx topy = ceq [] topx topy where
655664 where
656665 ceqB ps (Let v t) (Let v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
657666 ceqB ps (Guess v t) (Guess v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
658− ceqB ps (Pi i v t) (Pi i' v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
667+ ceqB ps (Pi r i v t) (Pi r' i' v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t')
659668 ceqB ps b b' = ceq ps (binderTy b) (binderTy b')
660669 -- Special case for 'case' blocks - size of scope causes complications,
661670 -- we only want to check the blocks themselves are valid and identical
@@ -859,9 +868,11 @@ data MetaInformation =
859868
860869-- | Contexts used for global definitions and for proof state. They contain
861870-- universe constraints and existing definitions.
871+-- Also store maximum RigCount of the name (can't bind a name at multiplicity
872+-- 1 in a RigW, for example)
862873data Context = MkContext {
863874 next_tvar :: Int,
864− definitions :: Ctxt (Def, Injectivity, Accessibility, Totality, MetaInformation)
875+ definitions :: Ctxt (Def, RigCount, Injectivity, Accessibility, Totality, MetaInformation)
865876 } deriving (Show, Generic)
866877
867878
@@ -871,53 +882,59 @@ initContext = MkContext 0 emptyContext
871882
872883mapDefCtxt :: (Def -> Def) -> Context -> Context
873884mapDefCtxt f (MkContext t !defs) = MkContext t (mapCtxt f' defs)
874− where f' (!d, i, a, t, m) = f' (f d, i, a, t, m)
885+ where f' (!d, r, i, a, t, m) = f' (f d, r, i, a, t, m)
875886
876887-- | Get the definitions from a context
877888ctxtAlist :: Context -> [(Name, Def)]
878−ctxtAlist ctxt = map (\(n, (d, i, a, t, m)) -> (n, d)) $ toAlist (definitions ctxt)
889+ctxtAlist ctxt = map (\(n, (d, r, i, a, t, m)) -> (n, d)) $ toAlist (definitions ctxt)
879890
880891veval ctxt env t = evalState (eval False ctxt [] env t []) initEval
881892
882893addToCtxt :: Name -> Term -> Type -> Context -> Context
883894addToCtxt n tm ty uctxt
884895 = let ctxt = definitions uctxt
885− !ctxt' = addDef n (Function ty tm, False, Public, Unchecked, EmptyMI) ctxt in
896+ !ctxt' = addDef n (Function ty tm, RigW, False, Public, Unchecked, EmptyMI) ctxt in
886897 uctxt { definitions = ctxt' }
887898
888899setAccess :: Name -> Accessibility -> Context -> Context
889900setAccess n a uctxt
890901 = let ctxt = definitions uctxt
891− !ctxt' = updateDef n (\ (d, i, _, t, m) -> (d, i, a, t, m)) ctxt in
902+ !ctxt' = updateDef n (\ (d, r, i, _, t, m) -> (d, r, i, a, t, m)) ctxt in
892903 uctxt { definitions = ctxt' }
893904
894905setInjective :: Name -> Injectivity -> Context -> Context
895906setInjective n i uctxt
896907 = let ctxt = definitions uctxt
897− !ctxt' = updateDef n (\ (d, _, a, t, m) -> (d, i, a, t, m)) ctxt in
908+ !ctxt' = updateDef n (\ (d, r, _, a, t, m) -> (d, r, i, a, t, m)) ctxt in
898909 uctxt { definitions = ctxt' }
899910
900911setTotal :: Name -> Totality -> Context -> Context
901912setTotal n t uctxt
902913 = let ctxt = definitions uctxt
903− !ctxt' = updateDef n (\ (d, i, a, _, m) -> (d, i, a, t, m)) ctxt in
914+ !ctxt' = updateDef n (\ (d, r, i, a, _, m) -> (d, r, i, a, t, m)) ctxt in
915+ uctxt { definitions = ctxt' }
916+
917+setRigCount :: Name -> RigCount -> Context -> Context
918+setRigCount n rc uctxt
919+ = let ctxt = definitions uctxt
920+ !ctxt' = updateDef n (\ (d, _, i, a, t, m) -> (d, rc, i, a, t, m)) ctxt in
904921 uctxt { definitions = ctxt' }
905922
906923setMetaInformation :: Name -> MetaInformation -> Context -> Context
907924setMetaInformation n m uctxt
908925 = let ctxt = definitions uctxt
909− !ctxt' = updateDef n (\ (d, i, a, t, _) -> (d, i, a, t, m)) ctxt in
926+ !ctxt' = updateDef n (\ (d, r, i, a, t, _) -> (d, r, i, a, t, m)) ctxt in
910927 uctxt { definitions = ctxt' }
911928
912929addCtxtDef :: Name -> Def -> Context -> Context
913930addCtxtDef n d c = let ctxt = definitions c
914− !ctxt' = addDef n (d, False, Public, Unchecked, EmptyMI) $! ctxt in
931+ !ctxt' = addDef n (d, RigW, False, Public, Unchecked, EmptyMI) $! ctxt in
915932 c { definitions = ctxt' }
916933
917934addTyDecl :: Name -> NameType -> Type -> Context -> Context
918935addTyDecl n nt ty uctxt
919936 = let ctxt = definitions uctxt
920− !ctxt' = addDef n (TyDecl nt ty, False, Public, Unchecked, EmptyMI) ctxt in
937+ !ctxt' = addDef n (TyDecl nt ty, RigW, False, Public, Unchecked, EmptyMI) ctxt in
921938 uctxt { definitions = ctxt' }
922939
923940addDatatype :: Datatype Name -> Context -> Context
@@ -925,14 +942,14 @@ addDatatype (Data n tag ty unique cons) uctxt
925942 = let ctxt = definitions uctxt
926943 ty' = normalise uctxt [] ty
927944 !ctxt' = addCons 0 cons (addDef n
928− (TyDecl (TCon tag (arity ty')) ty, True, Public, Unchecked, EmptyMI) ctxt) in
945+ (TyDecl (TCon tag (arity ty')) ty, RigW, True, Public, Unchecked, EmptyMI) ctxt) in
929946 uctxt { definitions = ctxt' }
930947 where
931948 addCons tag [] ctxt = ctxt
932949 addCons tag ((n, ty) : cons) ctxt
933950 = let ty' = normalise uctxt [] ty in
934951 addCons (tag+1) cons (addDef n
935− (TyDecl (DCon tag (arity ty') unique) ty, True, Public, Unchecked, EmptyMI) ctxt)
952+ (TyDecl (DCon tag (arity ty') unique) ty, RigW, True, Public, Unchecked, EmptyMI) ctxt)
936953
937954-- FIXME: Too many arguments! Refactor all these Bools.
938955--
@@ -966,7 +983,7 @@ addCasedef n ei ci@(CaseInfo inline alwaysInline tcdict)
966983 (args_rt, sc_rt)
967984 op = (CaseOp (ci { case_inlinable = inlc })
968985 ty argtys ps_in ps_ct cdef,
969− False, access, Unchecked, EmptyMI)
986+ RigW, False, access, Unchecked, EmptyMI)
970987 in return $ addDef n op ctxt
971988-- other -> tfail (Msg $ "Error adding case def: " ++ show other)
972989 return uctxt { definitions = ctxt' }
@@ -979,20 +996,20 @@ simplifyCasedef :: Name -> ErasureInfo -> Context -> TC Context
979996simplifyCasedef n ei uctxt
980997 = do let ctxt = definitions uctxt
981998 ctxt' <- case lookupCtxt n ctxt of
982− [(CaseOp ci ty atys [] ps _, inj, acc, tot, metainf)] ->
999+ [(CaseOp ci ty atys [] ps _, rc, inj, acc, tot, metainf)] ->
9831000 return ctxt -- nothing to simplify (or already done...)
984− [(CaseOp ci ty atys ps_in ps cd, inj, acc, tot, metainf)] ->
1001+ [(CaseOp ci ty atys ps_in ps cd, rc, inj, acc, tot, metainf)] ->
9851002 do let ps_in' = map simpl ps_in
9861003 pdef = map debind ps_in'
9871004 CaseDef args sc _ <- simpleCase False (STerm Erased) False CompileTime emptyFC [] atys pdef ei
9881005 return $ addDef n (CaseOp ci
9891006 ty atys ps_in' ps (cd { cases_compiletime = (args, sc) }),
990− inj, acc, tot, metainf) ctxt
1007+ rc, inj, acc, tot, metainf) ctxt
9911008
9921009 _ -> return ctxt
9931010 return uctxt { definitions = ctxt' }
9941011 where
995− depat acc (Bind n (PVar t) sc)
1012+ depat acc (Bind n (PVar _ t) sc)
9961013 = depat (n : acc) (instantiate (P Bound n t) sc)
9971014 depat acc x = (acc, x)
9981015 debind (Right (x, y)) = let (vs, x') = depat [] x
@@ -1007,10 +1024,10 @@ addOperator :: Name -> Type -> Int -> ([Value] -> Maybe Value) ->
10071024 Context -> Context
10081025addOperator n ty a op uctxt
10091026 = let ctxt = definitions uctxt
1010− ctxt' = addDef n (Operator ty a op, False, Public, Unchecked, EmptyMI) ctxt in
1027+ ctxt' = addDef n (Operator ty a op, RigW, False, Public, Unchecked, EmptyMI) ctxt in
10111028 uctxt { definitions = ctxt' }
10121029
1013−tfst (a, _, _, _, _) = a
1030+tfst (a, _, _, _, _, _) = a
10141031
10151032lookupNames :: Name -> Context -> [Name]
10161033lookupNames n ctxt
@@ -1096,10 +1113,10 @@ lookupP_all :: Bool -> Bool -> Name -> Context -> [Term]
10961113lookupP_all all exact n ctxt
10971114 = do (n', def) <- names
10981115 p <- case def of
1099− (Function ty tm, inj, a, _, _) -> return (P Ref n' ty, a)
1100− (TyDecl nt ty, _, a, _, _) -> return (P nt n' ty, a)
1101− (CaseOp _ ty _ _ _ _, inj, a, _, _) -> return (P Ref n' ty, a)
1102− (Operator ty _ _, inj, a, _, _) -> return (P Ref n' ty, a)
1116+ (Function ty tm, _, inj, a, _, _) -> return (P Ref n' ty, a)
1117+ (TyDecl nt ty, _, _, a, _, _) -> return (P nt n' ty, a)
1118+ (CaseOp _ ty _ _ _ _, _, inj, a, _, _) -> return (P Ref n' ty, a)
1119+ (Operator ty _ _, _, inj, a, _, _) -> return (P Ref n' ty, a)
11031120 case snd p of
11041121 Hidden -> if all then return (fst p) else []
11051122 Private -> if all then return (fst p) else []
@@ -1126,28 +1143,63 @@ lookupDefAcc :: Name -> Bool -> Context ->
11261143lookupDefAcc n mkpublic ctxt
11271144 = map mkp $ lookupCtxt n (definitions ctxt)
11281145 -- io_bind a special case for REPL prettiness
1129− where mkp (d, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure"))
1130− then (d, Public) else (d, a)
1146+ where mkp (d, _, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure"))
1147+ then (d, Public) else (d, a)
11311148
11321149lookupDefAccExact :: Name -> Bool -> Context ->
11331150 Maybe (Def, Accessibility)
11341151lookupDefAccExact n mkpublic ctxt
11351152 = fmap mkp $ lookupCtxtExact n (definitions ctxt)
11361153 -- io_bind a special case for REPL prettiness
1137− where mkp (d, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure"))
1138− then (d, Public) else (d, a)
1154+ where mkp (d, _, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure"))
1155+ then (d, Public) else (d, a)
11391156
11401157lookupTotal :: Name -> Context -> [Totality]
11411158lookupTotal n ctxt = map mkt $ lookupCtxt n (definitions ctxt)
1142− where mkt (d, inj, a, t, m) = t
1159+ where mkt (d, _, inj, a, t, m) = t
11431160
11441161lookupTotalExact :: Name -> Context -> Maybe Totality
11451162lookupTotalExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt)
1146− where mkt (d, inj, a, t, m) = t
1163+ where mkt (d, _, inj, a, t, m) = t
1164+
1165+lookupRigCount :: Name -> Context -> [Totality]
1166+lookupRigCount n ctxt = map mkt $ lookupCtxt n (definitions ctxt)
1167+ where mkt (d, _, inj, a, t, m) = t
1168+
1169+lookupRigCountExact :: Name -> Context -> Maybe RigCount
1170+lookupRigCountExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt)
1171+ where mkt (d, rc, inj, a, t, m) = rc
11471172
11481173lookupInjectiveExact :: Name -> Context -> Maybe Injectivity
11491174lookupInjectiveExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt)
1150− where mkt (d, inj, a, t, m) = inj
1175+ where mkt (d, _, inj, a, t, m) = inj
1176+
1177+-- Assume type is at least in whnfArgs form
1178+linearCheck :: Context -> Type -> TC ()
1179+linearCheck ctxt t = checkArgs t
1180+ where
1181+ checkArgs (Bind n (Pi RigW _ ty _) sc)
1182+ = do linearCheckArg ctxt ty
1183+ checkArgs (substV (P Bound n Erased) sc)
1184+ checkArgs (Bind n (Pi _ _ _ _) sc)
1185+ = checkArgs (substV (P Bound n Erased) sc)
1186+ checkArgs _ = return ()
1187+
1188+linearCheckArg :: Context -> Type -> TC ()
1189+linearCheckArg ctxt ty = mapM_ checkNameOK (allTTNames ty)
1190+ where
1191+ checkNameOK f
1192+ = case lookupRigCountExact f ctxt of
1193+ Just Rig1 ->
1194+ tfail $ Msg $ show f ++ " can only appear in a linear binding"
1195+ _ -> return ()
1196+
1197+ checkArgs (Bind n (Pi RigW _ ty _) sc)
1198+ = do mapM_ checkNameOK (allTTNames ty)
1199+ checkArgs (substV (P Bound n Erased) sc)
1200+ checkArgs (Bind n (Pi _ _ _ _) sc)
1201+ = checkArgs (substV (P Bound n Erased) sc)
1202+ checkArgs _ = return ()
11511203
11521204-- Check if a name is reducible in the type checker. Partial definitions
11531205-- are not reducible (so treated as a constant)
@@ -1159,10 +1211,10 @@ tcReducible n ctxt = case lookupTotalExact n ctxt of
11591211
11601212lookupMetaInformation :: Name -> Context -> [MetaInformation]
11611213lookupMetaInformation n ctxt = map mkm $ lookupCtxt n (definitions ctxt)
1162− where mkm (d, inj, a, t, m) = m
1214+ where mkm (d, _, inj, a, t, m) = m
11631215
11641216lookupNameTotal :: Name -> Context -> [(Name, Totality)]
1165−lookupNameTotal n = map (\(n, (_, _, _, t, _)) -> (n, t)) . lookupCtxtName n . definitions
1217+lookupNameTotal n = map (\(n, (_, _, _, _, t, _)) -> (n, t)) . lookupCtxtName n . definitions
11661218
11671219
11681220lookupVal :: Name -> Context -> [Value]
@@ -1173,11 +1225,11 @@ lookupVal n ctxt
11731225 (TyDecl nt ty) -> return (VP nt n (veval ctxt [] ty))
11741226 _ -> []
11751227
1176−lookupTyEnv :: Name -> Env -> Maybe (Int, Type)
1228+lookupTyEnv :: Name -> Env -> Maybe (Int, RigCount, Type)
11771229lookupTyEnv n env = li n 0 env where
11781230 li n i [] = Nothing
1179− li n i ((x, b): xs)
1180− | n == x = Just (i, binderTy b)
1231+ li n i ((x, r, b): xs)
1232+ | n == x = Just (i, r, binderTy b)
11811233 | otherwise = li n (i+1) xs
11821234
11831235-- | Create a unique name given context and other existing names
src/Idris/Core/Execute.hs+5−4
@@ -91,14 +91,14 @@ toTT (EBind n b body) = do n' <- newN n
9191 body' <- body $ EP Bound n' EErased
9292 b' <- fixBinder b
9393 Bind n' b' <$> toTT body'
94− where fixBinder (Lam t) = Lam <$> toTT t
95− fixBinder (Pi i t k) = Pi i <$> toTT t <*> toTT k
94+ where fixBinder (Lam rig t) = Lam rig <$> toTT t
95+ fixBinder (Pi rig i t k) = Pi rig i <$> toTT t <*> toTT k
9696 fixBinder (Let t1 t2) = Let <$> toTT t1 <*> toTT t2
9797 fixBinder (NLet t1 t2) = NLet <$> toTT t1 <*> toTT t2
9898 fixBinder (Hole t) = Hole <$> toTT t
9999 fixBinder (GHole i ns t) = GHole i ns <$> toTT t
100100 fixBinder (Guess t1 t2) = Guess <$> toTT t1 <*> toTT t2
101− fixBinder (PVar t) = PVar <$> toTT t
101+ fixBinder (PVar rig t) = PVar rig <$> toTT t
102102 fixBinder (PVTy t) = PVTy <$> toTT t
103103 newN n = do (ExecState hs ns) <- lift get
104104 let n' = uniqueName n ns
@@ -114,7 +114,7 @@ toTT (EConstant c) = return (Constant c)
114114toTT (EThunk ctxt env tm) = do env' <- mapM toBinder env
115115 return $ normalise ctxt env' tm
116116 where toBinder (n, v) = do v' <- toTT v
117− return (n, Let Erased v')
117+ return (n, RigW, Let Erased v')
118118toTT (EHandle _) = execFail $ Msg "Can't convert handles back to TT after execution."
119119toTT (EPtr ptr) = execFail $ Msg "Can't convert pointers back to TT after execution."
120120
@@ -212,6 +212,7 @@ doExec env ctxt (Proj tm i) = let (x, xs) = unApply tm in
212212 doExec env ctxt ((x:xs) !! i)
213213doExec env ctxt Erased = return EErased
214214doExec env ctxt Impossible = fail "Tried to execute an impossible case"
215+doExec env ctxt (Inferred t) = doExec env ctxt t
215216doExec env ctxt (TType u) = return (EType u)
216217doExec env ctxt (UType u) = return (EUType u)
217218
src/Idris/Core/ProofState.hs+75−60
@@ -23,6 +23,7 @@ import Idris.Core.ProofTerm
2323import Idris.Core.TT
2424import Idris.Core.Typecheck
2525import Idris.Core.Unify
26+import Idris.Core.WHNF
2627
2728import Util.Pretty hiding (fill)
2829
@@ -81,12 +82,13 @@ data Tactic = Attack
8182 | Compute
8283 | ComputeLet Name
8384 | Simplify
84− | HNF_Compute
85+ | WHNF_Compute
86+ | WHNF_ComputeArgs
8587 | EvalIn Raw
8688 | CheckIn Raw
8789 | Intro (Maybe Name)
8890 | IntroTy Raw (Maybe Name)
89− | Forall Name (Maybe ImplicitInfo) Raw
91+ | Forall Name RigCount (Maybe ImplicitInfo) Raw
9092 | LetBind Name Raw Raw
9193 | ExpandLet Name Term
9294 | Rewrite Raw
@@ -94,7 +96,7 @@ data Tactic = Attack
9496 | CaseTac Raw
9597 | Equiv Raw
9698 | PatVar Name
97− | PatBind Name
99+ | PatBind Name RigCount
98100 | Focus Name
99101 | Defer [Name] Name
100102 | DeferType Name Raw [Name]
@@ -127,12 +129,12 @@ instance Show ProofState where
127129 ") -------\n " ++
128130 show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
129131 where showPs env [] = ""
130− showPs env ((n, Let t v):bs)
132+ showPs env ((n, _, Let t v):bs)
131133 = " " ++ show n ++ " : " ++
132134 showEnv env ({- normalise ctxt env -} t) ++ " = " ++
133135 showEnv env ({- normalise ctxt env -} v) ++
134136 "\n" ++ showPs env bs
135− showPs env ((n, b):bs)
137+ showPs env ((n, _, b):bs)
136138 = " " ++ show n ++ " : " ++
137139 showEnv env ({- normalise ctxt env -} (binderTy b)) ++
138140 "\n" ++ showPs env bs
@@ -158,18 +160,18 @@ instance Pretty ProofState OutputAnnotation where
158160 prettyGoal ps b = prettyEnv ps $ binderTy b
159161
160162 prettyPs env [] = empty
161− prettyPs env ((n, Let t v):bs) =
163+ prettyPs env ((n, _, Let t v):bs) =
162164 nest nestingSize (pretty n <+> colon <+>
163165 prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
164166 nest nestingSize (prettyPs env bs))
165− prettyPs env ((n, b):bs) =
167+ prettyPs env ((n, _, b):bs) =
166168 nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
167169 nest nestingSize (prettyPs env bs))
168170
169171holeName i = sMN i "hole"
170172
171173qshow :: Fails -> String
172−qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fst env, x, y, hs)) fs)
174+qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fstEnv env, x, y, hs)) fs)
173175
174176match_unify' :: Context -> Env ->
175177 (TT Name, Maybe Provenance) ->
@@ -361,7 +363,7 @@ computeLet ctxt n tm = cl [] tm where
361363 cl env (Bind n' (Let t v) sc)
362364 | n' == n = let v' = normalise ctxt env v in
363365 Bind n' (Let t v') sc
364− cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, b):env) sc)
366+ cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, Rig0, b):env) sc)
365367 cl env (App s f a) = App s (cl env f) (cl env a)
366368 cl env t = t
367369
@@ -390,7 +392,7 @@ claimFn n bn argty ctxt env t@(Bind x (Hole retty) sc) =
390392 lift $ isType ctxt env tyt
391393 action (\ps -> let (g:gs) = holes ps in
392394 ps { holes = g : n : gs } )
393− return $ Bind n (Hole (Bind bn (Pi Nothing tyv tyt) retty)) t
395+ return $ Bind n (Hole (Bind bn (Pi RigW Nothing tyv tyt) retty)) t
394396claimFn _ _ _ ctxt env _ = fail "Can't make function type here"
395397
396398reorder_claims :: RunTactic
@@ -461,7 +463,7 @@ setinj n ctxt env (Bind x b sc)
461463
462464defer :: [Name] -> Name -> RunTactic
463465defer dropped n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
464− do let env' = filter (\(n, t) -> n `notElem` dropped) env
466+ do let env' = filter (\(n, _, t) -> n `notElem` dropped) env
465467 action (\ps -> let hs = holes ps in
466468 ps { usedns = n : usedns ps,
467469 holes = hs \\ [x] })
@@ -470,9 +472,9 @@ defer dropped n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
470472 (mkApp (P Ref n ty) (map getP (reverse env'))))
471473 where
472474 mkTy [] t = t
473− mkTy ((n,b) : bs) t = Bind n (Pi Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)
475+ mkTy ((n,rig,b) : bs) t = Bind n (Pi RigW Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)
474476
475− getP (n, b) = P Bound n (binderTy b)
477+ getP (n, rig, b) = P Bound n (binderTy b)
476478defer dropped n ctxt env _ = fail "Can't defer a non-hole focus."
477479
478480-- as defer, but build the type and application explicitly
@@ -486,7 +488,7 @@ deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
486488 return (Bind n (GHole 0 [] fty)
487489 (mkApp (P Ref n ty) (map getP args)))
488490 where
489− getP n = case lookup n env of
491+ getP n = case lookupBinder n env of
490492 Just b -> P Bound n (binderTy b)
491493 Nothing -> error ("deferType can't find " ++ show n)
492494deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus."
@@ -539,7 +541,7 @@ fill guess ctxt env (Bind x (Hole ty) sc) =
539541 -- some expected types show up commonly in errors and indicate a
540542 -- specific problem.
541543 -- argTy -> retTy suggests a function applied to too many arguments
542− chkPurpose val (Bind _ (Pi _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
544+ chkPurpose val (Bind _ (Pi _ _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
543545 = TooManyArgs val
544546 chkPurpose _ _ = ExpectedType
545547fill _ _ _ _ = fail "Can't fill here."
@@ -650,27 +652,27 @@ introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
650652 Just name -> name
651653 Nothing -> x
652654 let t' = case t of
653− x@(Bind y (Pi _ s _) _) -> x
655+ x@(Bind y (Pi _ _ s _) _) -> x
654656 _ -> normalise ctxt env t
655657 (tyv, tyt) <- lift $ check ctxt env ty
656658-- ns <- lift $ unify ctxt env tyv t'
657659 case t' of
658− Bind y (Pi _ s _) t -> let t' = updsubst y (P Bound n s) t in
659− do ns <- unify' ctxt env (s, Nothing) (tyv, Nothing)
660− ps <- get
661− let (uh, uns) = unified ps
662−-- put (ps { unified = (uh, uns ++ ns) })
663− return $ Bind n (Lam tyv) (Bind x (Hole t') (P Bound x t'))
660+ Bind y (Pi rig _ s _) t -> let t' = updsubst y (P Bound n s) t in
661+ do ns <- unify' ctxt env (s, Nothing) (tyv, Nothing)
662+ ps <- get
663+ let (uh, uns) = unified ps
664+-- put (ps { unified = (uh, uns ++ ns) })
665+ return $ Bind n (Lam rig tyv) (Bind x (Hole t') (P Bound x t'))
664666 _ -> lift $ tfail $ CantIntroduce t'
665667introTy ty n ctxt env _ = fail "Can't introduce here."
666668
667669intro :: Maybe Name -> RunTactic
668670intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
669671 do let t' = case t of
670− x@(Bind y (Pi _ s _) _) -> x
672+ x@(Bind y (Pi _ _ s _) _) -> x
671673 _ -> normalise ctxt env t
672674 case t' of
673− Bind y (Pi _ s _) t ->
675+ Bind y (Pi rig _ s _) t ->
674676 let n = case mn of
675677 Just name -> name
676678 Nothing -> y
@@ -678,17 +680,17 @@ intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
678680 -- because we want to substitute even in portions of
679681 -- terms that we know do not contain holes.
680682 t' = subst y (P Bound n s) t
681− in return $ Bind n (Lam s) (Bind x (Hole t') (P Bound x t'))
683+ in return $ Bind n (Lam rig s) (Bind x (Hole t') (P Bound x t'))
682684 _ -> lift $ tfail $ CantIntroduce t'
683685intro n ctxt env _ = fail "Can't introduce here."
684686
685−forall :: Name -> Maybe ImplicitInfo -> Raw -> RunTactic
686−forall n impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
687+forall :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> RunTactic
688+forall n rig impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
687689 do (tyv, tyt) <- lift $ check ctxt env ty
688690 unify' ctxt env (tyt, Nothing) (TType (UVar [] 0), Nothing)
689691 unify' ctxt env (t, Nothing) (TType (UVar [] 0), Nothing)
690− return $ Bind n (Pi impl tyv (TType (UVar [] 0))) (Bind x (Hole t) (P Bound x t))
691−forall n impl ty ctxt env _ = fail "Can't pi bind here"
692+ return $ Bind n (Pi rig impl tyv (TType (UVar [] 0))) (Bind x (Hole t) (P Bound x t))
693+forall n rig impl ty ctxt env _ = fail "Can't pi bind here"
692694
693695patvar :: Name -> RunTactic
694696patvar n ctxt env (Bind x (Hole t) sc) =
@@ -700,7 +702,7 @@ patvar n ctxt env (Bind x (Hole t) sc) =
700702 (notunified ps),
701703 injective = addInj n x (injective ps)
702704 })
703− return $ Bind n (PVar t) (updsubst x (P Bound n t) sc)
705+ return $ Bind n (PVar RigW t) (updsubst x (P Bound n t) sc)
704706 where addInj n x ps | x `elem` ps = n : ps
705707 | otherwise = ps
706708patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
@@ -723,7 +725,7 @@ rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
723725 let tmt' = normalise ctxt env tmt
724726 case unApply tmt' of
725727 (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
726− do let p = Bind rname (Lam lt) (mkP (P Bound rname lt) r l t)
728+ do let p = Bind rname (Lam RigW lt) (mkP (P Bound rname lt) r l t)
727729 let newt = mkP l r l t
728730 let sc = forget $ (Bind x (Hole newt)
729731 (mkApp (P Ref (sUN "replace") (TType (UVal 0)))
@@ -783,7 +785,7 @@ casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
783785 Var nm -> uniqueNameCtxt ctxt nm currentNames
784786 _ -> uniqueNameCtxt ctxt (sMN 0 "iv") currentNames
785787 let tmvar = P Bound tmnm tmt'
786− prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam tmt') (mkP tmvar tmv tmvar t)
788+ prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam RigW tmt') (mkP tmvar tmv tmvar t)
787789 consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (getProofTerm (pterm ps))) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (getProofTerm (pterm ps)))) consargs)
788790 let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (tacn tnm)) (TType (UVal 0)))
789791 (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv])))
@@ -810,7 +812,7 @@ casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
810812 makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) []
811813 replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx)
812814 let var = P Bound idnm idxt
813− return $ Bind idnm (Lam idxt) (mkP var idxv var t)) prop $ zip idnms idxs
815+ return $ Bind idnm (Lam RigW idxt) (mkP var idxv var t)) prop $ zip idnms idxs
814816casetac tm induction ctxt env _ = fail $ "Can't do " ++ (if induction then "induction" else "case analysis") ++ " here"
815817
816818
@@ -821,28 +823,33 @@ equiv tm ctxt env (Bind x (Hole t) sc) =
821823 return $ Bind x (Hole tmv) sc
822824equiv tm ctxt env _ = fail "Can't equiv here"
823825
824−patbind :: Name -> RunTactic
825−patbind n ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
826+patbind :: Name -> RigCount -> RunTactic
827+patbind n rig ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
826828 do let t' = case t of
827829 x@(Bind y (PVTy s) t) -> x
828830 _ -> normalise ctxt env t
829831 case t' of
830832 Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
831− return $ Bind n (PVar s) (Bind x (Hole t') (P Bound x t'))
833+ return $ Bind n (PVar rig s) (Bind x (Hole t') (P Bound x t'))
832834 _ -> fail "Nothing to pattern bind"
833−patbind n ctxt env _ = fail "Can't pattern bind here"
835+patbind n _ ctxt env _ = fail "Can't pattern bind here"
834836
835837compute :: RunTactic
836838compute ctxt env (Bind x (Hole ty) sc) =
837839 do return $ Bind x (Hole (normalise ctxt env ty)) sc
838840compute ctxt env t = return t
839841
840−hnf_compute :: RunTactic
841−hnf_compute ctxt env (Bind x (Hole ty) sc) =
842− do let ty' = normalise ctxt env ty in
843−-- trace ("HNF " ++ show (ty, ty')) $
842+whnf_compute :: RunTactic
843+whnf_compute ctxt env (Bind x (Hole ty) sc) =
844+ do let ty' = whnf ctxt env ty in
844845 return $ Bind x (Hole ty') sc
845−hnf_compute ctxt env t = return t
846+whnf_compute ctxt env t = return t
847+
848+whnf_compute_args :: RunTactic
849+whnf_compute_args ctxt env (Bind x (Hole ty) sc) =
850+ do let ty' = whnfArgs ctxt env ty in
851+ return $ Bind x (Hole ty') sc
852+whnf_compute_args ctxt env t = return t
846853
847854-- reduce let bindings only
848855simplify :: RunTactic
@@ -907,8 +914,8 @@ keepGiven du (u : us) hs = keepGiven du us hs
907914
908915updateEnv [] e = e
909916updateEnv ns [] = []
910−updateEnv ns ((n, b) : env)
911− = (n, fmap (updateSolvedTerm ns) b) : updateEnv ns env
917+updateEnv ns ((n, rig, b) : env)
918+ = (n, rig, fmap (updateSolvedTerm ns) b) : updateEnv ns env
912919
913920updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
914921updateProv ns p = p
@@ -995,6 +1002,18 @@ updateProblems ps updates probs = rec 10 updates probs
9951002 (x', y', newx || newy,
9961003 updateEnv ns env, updateError ns err, fc, fa)
9971004
1005+orderUpdateSolved :: [(Name, Term)] -> ProofTerm -> (ProofTerm, [Name])
1006+orderUpdateSolved ns tm = update [] ns tm
1007+ where
1008+ update done [] t = (t, done)
1009+ update done ((n, P _ n' _) : ns) t | n == n' = update done ns t
1010+ update done (n : ns) t = update (fst n : done)
1011+ (map (updateMatch n) ns)
1012+ (updateSolved [n] t)
1013+
1014+ -- Update the later solutions too
1015+ updateMatch n (x, tm) = (x, updateSolvedTerm [n] tm)
1016+
9981017-- attempt to solve remaining problems with match_unify
9991018matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
10001019 -> ([(Name, TT Name)], Fails)
@@ -1058,30 +1077,25 @@ processTactic (ComputeLet n) ps
10581077 (getProofTerm (pterm ps)) }, "")
10591078processTactic UnifyProblems ps
10601079 = do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
1061− pterm' = orderUpdateSolved ns' (pterm ps)
1062− traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show (map fst ns')) $
1080+ (pterm', dropped) = orderUpdateSolved ns' (pterm ps)
1081+ traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show dropped) $
10631082 return (ps { pterm = pterm', solved = Nothing, problems = probs',
10641083 previous = Just ps, plog = "",
10651084 notunified = updateNotunified ns' (notunified ps),
1066− recents = recents ps ++ map fst ns',
1085+ recents = recents ps ++ dropped,
10671086 dotted = filter (notIn ns') (dotted ps),
1068− holes = holes ps \\ (map fst ns') }, plog ps)
1087+ holes = holes ps \\ dropped }, plog ps)
10691088 where notIn ns (h, _) = h `notElem` map fst ns
1070− orderUpdateSolved [] t = t
1071− orderUpdateSolved (n : ns) t = orderUpdateSolved ns (updateSolved [n] t)
10721089processTactic (MatchProblems all) ps
10731090 = do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
10741091 (ns'', probs'') = matchProblems all ps ns' probs'
1075− pterm' = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
1076− traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show ns'') $
1092+ (pterm', dropped) = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
1093+ traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show dropped) $
10771094 return (ps { pterm = pterm', solved = Nothing, problems = probs'',
10781095 previous = Just ps, plog = "",
10791096 notunified = updateNotunified ns'' (notunified ps),
1080− recents = recents ps ++ map fst ns'',
1081− holes = holes ps \\ (map fst ns'') }, plog ps)
1082− where
1083− orderUpdateSolved [] t = t
1084− orderUpdateSolved (n : ns) t = orderUpdateSolved ns (updateSolved [n] t)
1097+ recents = recents ps ++ dropped,
1098+ holes = holes ps \\ dropped }, plog ps)
10851099processTactic t ps
10861100 = case holes ps of
10871101 [] -> case t of
@@ -1131,10 +1145,11 @@ process t h = tactic (Just h) (mktac t)
11311145 mktac (StartUnify n) = start_unify n
11321146 mktac Compute = compute
11331147 mktac Simplify = Idris.Core.ProofState.simplify
1134− mktac HNF_Compute = hnf_compute
1148+ mktac WHNF_Compute = whnf_compute
1149+ mktac WHNF_ComputeArgs = whnf_compute_args
11351150 mktac (Intro n) = intro n
11361151 mktac (IntroTy ty n) = introTy ty n
1137− mktac (Forall n i t) = forall n i t
1152+ mktac (Forall n r i t) = forall n r i t
11381153 mktac (LetBind n t v) = letbind n t v
11391154 mktac (ExpandLet n b) = expandLet n b
11401155 mktac (Rewrite t) = rewrite t
@@ -1142,7 +1157,7 @@ process t h = tactic (Just h) (mktac t)
11421157 mktac (CaseTac t) = casetac t False
11431158 mktac (Equiv t) = equiv t
11441159 mktac (PatVar n) = patvar n
1145− mktac (PatBind n) = patbind n
1160+ mktac (PatBind n rig) = patbind n rig
11461161 mktac (CheckIn r) = check_in r
11471162 mktac (EvalIn r) = eval_in r
11481163 mktac (Focus n) = focus n
src/Idris/Core/ProofTerm.hs+11−11
@@ -84,7 +84,7 @@ findHole n env t = fh' env Top t where
8484 | Just (p, env', tm) <- fh' env path f = Just (AppL s p a, env', tm)
8585 fh' env path (Bind x b sc)
8686 | Just (bp, env', tm) <- fhB env path b = Just (InBind x bp sc, env', tm)
87− | Just (p, env', tm) <- fh' ((x,b):env) path sc = Just (InScope x b p, env', tm)
87+ | Just (p, env', tm) <- fh' ((x,RigW,b):env) path sc = Just (InScope x b p, env', tm)
8888 fh' _ _ _ = Nothing
8989
9090 fhB env path (Let t v)
@@ -170,10 +170,10 @@ updateSolvedTerm' xs x = updateSolved' xs x where
170170 _ -> let (t', _) = updateSolved' xs t in
171171 (updsubst n v t', True)
172172 updateSolved' xs tm@(Bind n b t)
173− | otherwise = let (t', ut) = updateSolved' xs t
174− (b', ub) = updateSolvedB' xs b in
175− if ut || ub then (Bind n b' t', True)
176− else (tm, False)
173+ = let (t', ut) = updateSolved' xs t
174+ (b', ub) = updateSolvedB' xs b in
175+ if ut || ub then (Bind n b' t', True)
176+ else (tm, False)
177177 updateSolved' xs t@(App Complete f a) = (t, False)
178178 updateSolved' xs t@(App s f a)
179179 = let (f', uf) = updateSolved' xs f
@@ -255,7 +255,7 @@ updsubst n v tm = fst $ subst' 0 tm
255255updateEnv :: [(Name, Term)] -> Env -> Env
256256updateEnv [] e = e
257257updateEnv ns [] = []
258−updateEnv ns ((n, b) : env) = (n, fmap (updateSolvedTerm ns) b) : updateEnv ns env
258+updateEnv ns ((n, r, b) : env) = (n, r, fmap (updateSolvedTerm ns) b) : updateEnv ns env
259259
260260-- | Fill out solved holes in a term zipper.
261261updateSolvedPath :: [(Name, Term)] -> TermPath -> TermPath
@@ -284,7 +284,7 @@ updateSolvedPath ns (InScope n b sc)
284284updateSolved :: [(Name, Term)] -> ProofTerm -> ProofTerm
285285updateSolved xs pt@(PT path env sub ups)
286286 = PT path -- (updateSolvedPath xs path)
287− (updateEnv xs (filter (\(n, t) -> n `notElem` map fst xs) env))
287+ (updateEnv xs (filter (\(n, r, t) -> n `notElem` map fst xs) env))
288288 (updateSolvedTerm xs sub)
289289 (ups ++ xs)
290290
@@ -297,10 +297,10 @@ goal h pt@(PT path env sub ups)
297297 g env (Bind n b@(Guess _ _) sc)
298298 | same h n = return $ GD env b
299299 | otherwise
300− = gb env b `mplus` g ((n, b):env) sc
300+ = gb env b `mplus` g ((n, RigW, b):env) sc
301301 g env (Bind n b sc) | hole b && same h n = return $ GD env b
302302 | otherwise
303− = g ((n, b):env) sc `mplus` gb env b
303+ = g ((n, RigW, b):env) sc `mplus` gb env b
304304 g env (App Complete f a) = fail "Can't find hole"
305305 g env (App _ f a) = g env a `mplus` g env f
306306 g env t = fail "Can't find hole"
@@ -338,12 +338,12 @@ atHole h f c e pt -- @(PT path env sub)
338338 = do -- binder first
339339 (b', u) <- ulift2 f c env Guess t v
340340 if u then return (Bind n b' sc, True)
341− else do (sc', u) <- atH f c ((n, b) : env) sc
341+ else do (sc', u) <- atH f c ((n, RigW, b) : env) sc
342342 return (Bind n b' sc', u)
343343 atH f c env binder@(Bind n b sc)
344344 | hole b && same h n = updated (f c env binder)
345345 | otherwise -- scope first
346− = do (sc', u) <- atH f c ((n, b) : env) sc
346+ = do (sc', u) <- atH f c ((n, RigW, b) : env) sc
347347 if u then return (Bind n b sc', True)
348348 else do (b', u) <- atHb f c env b
349349 return (Bind n b' sc', u)
src/Idris/Core/TT.hs+113−53
@@ -31,7 +31,7 @@ module Idris.Core.TT(
3131 , Env(..), EnvTT(..), Err(..), Err'(..), ErrorReportPart(..)
3232 , FC(..), FC'(..), ImplicitInfo(..), IntTy(..), Name(..)
3333 , NameOutput(..), NameType(..), NativeTy(..), OutputAnnotation(..)
34− , Provenance(..), Raw(..), SpecialName(..), TC(..), Term(..)
34+ , Provenance(..), Raw(..), RigCount(..), SpecialName(..), TC(..), Term(..)
3535 , TermSize(..), TextFormatting(..), TT(..),Type(..), TypeInfo(..)
3636 , UConstraint(..), UCs(..), UExp(..), Universe(..)
3737 , addAlist, addBinder, addDef, allTTNames, arity, bindAll
@@ -49,6 +49,8 @@ module Idris.Core.TT(
4949 , substV, sUN, tcname, termSmallerThan, tfail, thead, tnull
5050 , toAlist, traceWhen, txt, unApply, uniqueBinders, uniqueName
5151 , uniqueNameFrom, uniqueNameSet, unList, updateDef, vToP, weakenTm
52+ , rigPlus, rigMult, fstEnv, rigEnv, sndEnv, lookupBinder, envBinders
53+ , envZero
5254 ) where
5355
5456import Util.Pretty hiding (Str)
@@ -851,9 +853,11 @@ deriving instance Binary ImplicitInfo
851853-- | All binding forms are represented in a uniform fashion. This type only represents
852854-- the types of bindings (and their values, if any); the attached identifiers are part
853855-- of the 'Bind' constructor for the 'TT' type.
854−data Binder b = Lam { binderTy :: !b {-^ type annotation for bound variable-}}
856+data Binder b = Lam { binderCount :: RigCount,
857+ binderTy :: !b {-^ type annotation for bound variable-}}
855858 -- ^ A function binding
856− | Pi { binderImpl :: Maybe ImplicitInfo,
859+ | Pi { binderCount :: RigCount,
860+ binderImpl :: Maybe ImplicitInfo,
857861 binderTy :: !b,
858862 binderKind :: !b }
859863 -- ^ A binding that occurs in a function type
@@ -885,7 +889,8 @@ data Binder b = Lam { binderTy :: !b {-^ type annotation for bound variable-}
885889 -- substituted - the guess is to keep it
886890 -- computationally inert while working on other things
887891 -- if necessary.
888− | PVar { binderTy :: !b }
892+ | PVar { binderCount :: RigCount,
893+ binderTy :: !b }
889894 -- ^ A pattern variable (these are bound around terms
890895 -- that make up pattern-match clauses)
891896 | PVTy { binderTy :: !b }
@@ -896,25 +901,25 @@ deriving instance Binary Binder
896901!-}
897902
898903instance Sized a => Sized (Binder a) where
899− size (Lam ty) = 1 + size ty
900− size (Pi _ ty _) = 1 + size ty
904+ size (Lam _ ty) = 1 + size ty
905+ size (Pi _ _ ty _) = 1 + size ty
901906 size (Let ty val) = 1 + size ty + size val
902907 size (NLet ty val) = 1 + size ty + size val
903908 size (Hole ty) = 1 + size ty
904909 size (GHole _ _ ty) = 1 + size ty
905910 size (Guess ty val) = 1 + size ty + size val
906− size (PVar ty) = 1 + size ty
911+ size (PVar _ ty) = 1 + size ty
907912 size (PVTy ty) = 1 + size ty
908913
909914fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
910915fmapMB f (Let t v) = liftM2 Let (f t) (f v)
911916fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
912917fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
913−fmapMB f (Lam t) = liftM Lam (f t)
914−fmapMB f (Pi i t k) = liftM2 (Pi i) (f t) (f k)
918+fmapMB f (Lam c t) = liftM (Lam c) (f t)
919+fmapMB f (Pi c i t k) = liftM2 (Pi c i) (f t) (f k)
915920fmapMB f (Hole t) = liftM Hole (f t)
916921fmapMB f (GHole i ns t) = liftM (GHole i ns) (f t)
917−fmapMB f (PVar t) = liftM PVar (f t)
922+fmapMB f (PVar c t) = liftM (PVar c) (f t)
918923fmapMB f (PVTy t) = liftM PVTy (f t)
919924
920925raw_apply :: Raw -> [Raw] -> Raw
@@ -1008,6 +1013,9 @@ data TT n = P NameType n (TT n) -- ^ named references with type
10081013 -- (-1) is a special case for 'subtract one from BI'
10091014 | Erased -- ^ an erased term
10101015 | Impossible -- ^ special case for totality checking
1016+ | Inferred (TT n) -- ^ For building case trees when coverage checkimg only.
1017+ -- Marks a term as being inferred by the machine, rather than
1018+ -- given by the programmer
10111019 | TType UExp -- ^ the type of types at some level
10121020 | UType Universe -- ^ Uniqueness type universe (disjoint from TType)
10131021 deriving (Ord, Functor, Data, Generic, Typeable)
@@ -1055,12 +1063,48 @@ instance Sized a => Sized (TT a) where
10551063 size (TType u) = 1 + size u
10561064 size (Proj a _) = 1 + size a
10571065 size Impossible = 1
1066+ size (Inferred t) = size t
10581067 size (UType u) = 1 + size u
10591068
10601069instance Pretty a o => Pretty (TT a) o where
10611070 pretty _ = text "test"
10621071
1063−type EnvTT n = [(n, Binder (TT n))]
1072+data RigCount = Rig0 | Rig1 | RigW
1073+ deriving (Show, Eq, Ord, Data, Generic, Typeable)
1074+
1075+rigPlus :: RigCount -> RigCount -> RigCount
1076+rigPlus Rig0 Rig0 = Rig0
1077+rigPlus Rig0 Rig1 = Rig1
1078+rigPlus Rig0 RigW = RigW
1079+rigPlus Rig1 Rig0 = Rig1
1080+rigPlus Rig1 Rig1 = RigW
1081+rigPlus Rig1 RigW = RigW
1082+rigPlus RigW Rig0 = RigW
1083+rigPlus RigW Rig1 = RigW
1084+rigPlus RigW RigW = RigW
1085+
1086+rigMult :: RigCount -> RigCount -> RigCount
1087+rigMult Rig0 Rig0 = Rig0
1088+rigMult Rig0 Rig1 = Rig0
1089+rigMult Rig0 RigW = Rig0
1090+rigMult Rig1 Rig0 = Rig0
1091+rigMult Rig1 Rig1 = Rig1
1092+rigMult Rig1 RigW = RigW
1093+rigMult RigW Rig0 = Rig0
1094+rigMult RigW Rig1 = RigW
1095+rigMult RigW RigW = RigW
1096+
1097+type EnvTT n = [(n, RigCount, Binder (TT n))]
1098+
1099+fstEnv (n, c, b) = n
1100+rigEnv (n, c, b) = c
1101+sndEnv (n, c, b) = b
1102+
1103+envBinders = map (\(n, _, b) -> (n, b))
1104+envZero = map (\(n, _, b) -> (n, Rig0, b))
1105+
1106+lookupBinder :: Eq n => n -> EnvTT n -> Maybe (Binder (TT n))
1107+lookupBinder n = lookup n . envBinders
10641108
10651109data Datatype n = Data { d_typename :: n,
10661110 d_typetag :: Int,
@@ -1082,7 +1126,9 @@ data TypeInfo = TI { con_names :: [Name],
10821126 codata :: Bool,
10831127 data_opts :: DataOpts,
10841128 param_pos :: [Int],
1085− mutual_types :: [Name] }
1129+ mutual_types :: [Name],
1130+ linear_con :: Bool -- is there a linear argument?
1131+ }
10861132 deriving (Show, Generic)
10871133{-!
10881134deriving instance Binary TypeInfo
@@ -1110,7 +1156,7 @@ isInjective (P (DCon _ _ _) _ _) = True
11101156isInjective (P (TCon _ _) _ _) = True
11111157isInjective (Constant _) = True
11121158isInjective (TType x) = True
1113−isInjective (Bind _ (Pi _ _ _) sc) = True
1159+isInjective (Bind _ (Pi _ _ _ _) sc) = True
11141160isInjective (App _ f a) = isInjective f
11151161isInjective _ = False
11161162
@@ -1344,7 +1390,7 @@ freeNames t = nub $ freeNames' t
13441390
13451391-- | Return the arity of a (normalised) type
13461392arity :: TT n -> Int
1347−arity (Bind n (Pi _ t _) sc) = 1 + arity sc
1393+arity (Bind n (Pi _ _ t _) sc) = 1 + arity sc
13481394arity _ = 0
13491395
13501396-- | Deconstruct an application; returns the function and a list of arguments
@@ -1379,6 +1425,7 @@ termSmallerThan x (V i) = True
13791425termSmallerThan x (Constant c) = True
13801426termSmallerThan x Erased = True
13811427termSmallerThan x Impossible = True
1428+termSmallerThan x (Inferred t) = termSmallerThan x t
13821429termSmallerThan x (TType u) = True
13831430termSmallerThan x (UType u) = True
13841431
@@ -1421,6 +1468,7 @@ safeForgetEnv env (UType u) = Just $ RUType u
14211468safeForgetEnv env Erased = Just $ RConstant Forgot
14221469safeForgetEnv env (Proj tm i) = error "Don't know how to forget a projection"
14231470safeForgetEnv env Impossible = error "Don't know how to forget Impossible"
1471+safeForgetEnv env (Inferred t) = safeForgetEnv env t
14241472
14251473-- | Introduce a 'Bind' into the given term for each element of the
14261474-- given list of (name, binder) pairs.
@@ -1438,22 +1486,22 @@ bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
14381486-- | Return a list of pairs of the names of the outermost 'Pi'-bound
14391487-- variables in the given term, together with their types.
14401488getArgTys :: TT n -> [(n, TT n)]
1441−getArgTys (Bind n (PVar _) sc) = getArgTys sc
1489+getArgTys (Bind n (PVar _ _) sc) = getArgTys sc
14421490getArgTys (Bind n (PVTy _) sc) = getArgTys sc
1443−getArgTys (Bind n (Pi _ t _) sc) = (n, t) : getArgTys sc
1491+getArgTys (Bind n (Pi _ _ t _) sc) = (n, t) : getArgTys sc
14441492getArgTys _ = []
14451493
14461494getRetTy :: TT n -> TT n
1447−getRetTy (Bind n (PVar _) sc) = getRetTy sc
1495+getRetTy (Bind n (PVar _ _) sc) = getRetTy sc
14481496getRetTy (Bind n (PVTy _) sc) = getRetTy sc
1449−getRetTy (Bind n (Pi _ _ _) sc) = getRetTy sc
1497+getRetTy (Bind n (Pi _ _ _ _) sc) = getRetTy sc
14501498getRetTy sc = sc
14511499
14521500-- | As getRetTy but substitutes names for de Bruijn indices
14531501substRetTy :: TT n -> TT n
1454−substRetTy (Bind n (PVar ty) sc) = substRetTy (substV (P Ref n ty) sc)
1502+substRetTy (Bind n (PVar _ ty) sc) = substRetTy (substV (P Ref n ty) sc)
14551503substRetTy (Bind n (PVTy ty) sc) = substRetTy (substV (P Ref n ty) sc)
1456−substRetTy (Bind n (Pi _ ty _) sc) = substRetTy (substV (P Ref n ty) sc)
1504+substRetTy (Bind n (Pi _ _ ty _) sc) = substRetTy (substV (P Ref n ty) sc)
14571505substRetTy sc = sc
14581506
14591507
@@ -1566,15 +1614,15 @@ prettyEnv env t = prettyEnv' env t False
15661614 prettySe p env (V i) debug
15671615 | i < length env =
15681616 if debug then
1569− text . show . fst $ env!!i
1617+ text . show . fstEnv $ env!!i
15701618 else
15711619 lbracket <+> text (show i) <+> rbracket
15721620 | otherwise = text "unbound" <+> text (show i) <+> text "!"
1573− prettySe p env (Bind n b@(Pi _ t _) sc) debug
1621+ prettySe p env (Bind n b@(Pi _ _ t _) sc) debug
15741622 | noOccurrence n sc && not debug =
1575− bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
1623+ bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, Rig0, b):env) sc debug
15761624 prettySe p env (Bind n b sc) debug =
1577− bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
1625+ bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, Rig0, b):env) sc debug
15781626 prettySe p env (App _ f a) debug =
15791627 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
15801628 prettySe p env (Proj x i) debug =
@@ -1583,14 +1631,18 @@ prettyEnv env t = prettyEnv' env t False
15831631 prettySe p env Erased debug = text "[_]"
15841632 prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
15851633 prettySe p env Impossible debug = text "Impossible"
1634+ prettySe p env (Inferred tm) debug = text "<" <+> prettySe p env tm debug <+> text ">"
15861635 prettySe p env (UType u) debug = text (show u)
15871636
15881637 -- Render a `Binder` and its name
1589− prettySb env n (Lam t) = prettyB env "λ" "=>" n t
1638+ prettySb env n (Lam _ t) = prettyB env "λ" "=>" n t
15901639 prettySb env n (Hole t) = prettyB env "?defer" "." n t
15911640 prettySb env n (GHole _ _ t) = prettyB env "?gdefer" "." n t
1592− prettySb env n (Pi _ t _) = prettyB env "(" ") ->" n t
1593− prettySb env n (PVar t) = prettyB env "pat" "." n t
1641+ prettySb env n (Pi Rig0 _ t _) = prettyB env "(" ") ->" n t
1642+ prettySb env n (Pi Rig1 _ t _) = prettyB env "(" ") -o" n t
1643+ prettySb env n (Pi RigW _ t _) = prettyB env "(" ") ->" n t
1644+ prettySb env n (PVar Rig1 t) = prettyB env "pat 1 " "." n t
1645+ prettySb env n (PVar _ t) = prettyB env "pat" "." n t
15941646 prettySb env n (PVTy t) = prettyB env "pty" "." n t
15951647 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
15961648 prettySb env n (NLet t v) = prettyBv env "nlet" "in" n t v
@@ -1613,30 +1665,37 @@ showEnv' env t dbg = se 10 env t where
16131665 se p env (P nt n t) = show n
16141666 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
16151667 se p env (V i) | i < length env && i >= 0
1616− = (show $ fst $ env!!i) ++
1668+ = (show $ fstEnv $ env!!i) ++
16171669 if dbg then "{" ++ show i ++ "}" else ""
16181670 | otherwise = "!!V " ++ show i ++ "!!"
1619− se p env (Bind n b@(Pi (Just _) t k) sc)
1620− = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
1621− se p env (Bind n b@(Pi _ t k) sc)
1622− | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ arrow k ++ se 10 ((n,b):env) sc
1623− where arrow (TType _) = " -> "
1624− arrow u = " [" ++ show u ++ "] -> "
1625− se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
1671+ se p env (Bind n b@(Pi rig (Just _) t k) sc)
1672+ = bracket p 2 $ sb env n b ++ se 10 ((n, rig, b):env) sc
1673+ se p env (Bind n b@(Pi rig _ t k) sc)
1674+ | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ arrow rig ++ se 10 ((n,Rig0,b):env) sc
1675+ where arrow Rig0 = " -> "
1676+ arrow Rig1 = " -o "
1677+ arrow RigW = " -> "
1678+ se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,Rig0,b):env) sc
16261679 se p env (App _ f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
16271680 se p env (Proj x i) = se 1 env x ++ "!" ++ show i
16281681 se p env (Constant c) = show c
16291682 se p env Erased = "[__]"
16301683 se p env Impossible = "[impossible]"
1684+ se p env (Inferred t) = "<" ++ se p env t ++ ">"
16311685 se p env (TType i) = "Type " ++ show i
16321686 se p env (UType u) = show u
16331687
1634− sb env n (Lam t) = showb env "\\ " " => " n t
1688+ sb env n (Lam Rig1 t) = showb env "\\ 1 " " => " n t
1689+ sb env n (Lam _ t) = showb env "\\ " " => " n t
16351690 sb env n (Hole t) = showb env "? " ". " n t
16361691 sb env n (GHole i ns t) = showb env "?defer " ". " n t
1637− sb env n (Pi (Just _) t _) = showb env "{" "} -> " n t
1638− sb env n (Pi _ t _) = showb env "(" ") -> " n t
1639− sb env n (PVar t) = showb env "pat " ". " n t
1692+ sb env n (Pi Rig1 (Just _) t _) = showb env "{" "} -o " n t
1693+ sb env n (Pi _ (Just _) t _) = showb env "{" "} -> " n t
1694+ sb env n (Pi Rig1 _ t _) = showb env "(" ") -0 " n t
1695+ sb env n (Pi _ _ t _) = showb env "(" ") -> " n t
1696+ sb env n (PVar Rig0 t) = showb env "pat 0 " ". " n t
1697+ sb env n (PVar Rig1 t) = showb env "pat 1 " ". " n t
1698+ sb env n (PVar _ t) = showb env "pat " ". " n t
16401699 sb env n (PVTy t) = showb env "pty " ". " n t
16411700 sb env n (Let t v) = showbv env "let " " in " n t v
16421701 sb env n (NLet t v) = showbv env "nlet " " in " n t v
@@ -1678,14 +1737,14 @@ weakenTm i t = wk i 0 t
16781737weakenEnv :: EnvTT n -> EnvTT n
16791738weakenEnv env = wk (length env - 1) env
16801739 where wk i [] = []
1681− wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
1740+ wk i ((n, c, b) : bs) = (n, c, weakenTmB i b) : wk (i - 1) bs
16821741 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
16831742 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
16841743 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
16851744
16861745-- | Weaken every term in the environment by the given amount
16871746weakenTmEnv :: Int -> EnvTT n -> EnvTT n
1688−weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
1747+weakenTmEnv i = map (\ (n, c, b) -> (n, c, fmap (weakenTm i) b))
16891748
16901749refsIn :: TT Name -> [Name]
16911750refsIn (P _ n _) = [n]
@@ -1736,20 +1795,21 @@ pprintTT bound tm = pp startPrec bound tm
17361795 text "!" <> text (show i)
17371796 pp p bound Erased = text "<<<erased>>>"
17381797 pp p bound Impossible = text "<<<impossible>>>"
1798+ pp p bound (Inferred t) = text "<" <+> pp p bound t <+> text ">"
17391799 pp p bound (TType ue) = annotate (AnnType "Type" "The type of types") $
17401800 text "Type"
17411801 pp p bound (UType u) = text (show u)
17421802
1743− ppb p bound n (Lam ty) sc =
1803+ ppb p bound n (Lam rig ty) sc =
17441804 bracket p startPrec . group . align . hang 2 $
17451805 text "λ" <+> bindingOf n False <+> text "." <> line <> sc
1746− ppb p bound n (Pi _ ty k) sc =
1806+ ppb p bound n (Pi rig _ ty k) sc =
17471807 bracket p startPrec . group . align $
17481808 lparen <> (bindingOf n False) <+> colon <+>
17491809 (group . align) (pp startPrec bound ty) <>
1750− rparen <+> mkArrow k <> line <> sc
1751− where mkArrow (UType UniqueType) = text "⇴"
1752− mkArrow (UType NullType) = text "⥛"
1810+ rparen <+> mkArrow rig <> line <> sc
1811+ where mkArrow Rig1 = text "⇴"
1812+ mkArrow Rig0 = text "⥛"
17531813 mkArrow _ = text "→"
17541814 ppb p bound n (Let ty val) sc =
17551815 bracket p startPrec . group . align $
@@ -1778,7 +1838,7 @@ pprintTT bound tm = pp startPrec bound tm
17781838 text "?" <> bindingOf n False <+>
17791839 text "≈" <+> pp startPrec bound val <+>
17801840 text "." <> line <> sc
1781− ppb p bound n (PVar ty) sc =
1841+ ppb p bound n (PVar _ ty) sc =
17821842 bracket p startPrec . group . align . hang 2 $
17831843 annotate AnnKeyword (text "pat") <+>
17841844 bindingOf n False <+> colon <+> pp startPrec bound ty <+>
@@ -1829,10 +1889,10 @@ pprintRaw bound (RBind n b body) =
18291889 , ppb b
18301890 , pprintRaw (n:bound) body]
18311891 where
1832− ppb (Lam ty) = enclose lparen rparen . group . align . hang 2 $
1833− text "Lam" <$> pprintRaw bound ty
1834− ppb (Pi _ ty k) = enclose lparen rparen . group . align . hang 2 $
1835− vsep [text "Pi", pprintRaw bound ty, pprintRaw bound k]
1892+ ppb (Lam _ ty) = enclose lparen rparen . group . align . hang 2 $
1893+ text "Lam" <$> pprintRaw bound ty
1894+ ppb (Pi _ _ ty k) = enclose lparen rparen . group . align . hang 2 $
1895+ vsep [text "Pi", pprintRaw bound ty, pprintRaw bound k]
18361896 ppb (Let ty v) = enclose lparen rparen . group . align . hang 2 $
18371897 vsep [text "Let", pprintRaw bound ty, pprintRaw bound v]
18381898 ppb (NLet ty v) = enclose lparen rparen . group . align . hang 2 $
@@ -1843,8 +1903,8 @@ pprintRaw bound (RBind n b body) =
18431903 text "GHole" <$> pprintRaw bound ty
18441904 ppb (Guess ty v) = enclose lparen rparen . group . align . hang 2 $
18451905 vsep [text "Guess", pprintRaw bound ty, pprintRaw bound v]
1846− ppb (PVar ty) = enclose lparen rparen . group . align . hang 2 $
1847− text "PVar" <$> pprintRaw bound ty
1906+ ppb (PVar _ ty) = enclose lparen rparen . group . align . hang 2 $
1907+ text "PVar" <$> pprintRaw bound ty
18481908 ppb (PVTy ty) = enclose lparen rparen . group . align . hang 2 $
18491909 text "PVTy" <$> pprintRaw bound ty
18501910pprintRaw bound (RApp f x) =
src/Idris/Core/Typecheck.hs+142−103
@@ -12,6 +12,7 @@ Maintainer : The Idris Community.
1212module Idris.Core.Typecheck where
1313
1414import Idris.Core.Evaluate
15+import Idris.Core.WHNF
1516import Idris.Core.TT
1617
1718import Control.Monad.State
@@ -25,7 +26,7 @@ import Debug.Trace
2526
2627convertsC :: Context -> Env -> Term -> Term -> StateT UCs TC ()
2728convertsC ctxt env x y =
28− do let hs = map fst (filter isHole env)
29+ do let hs = map fstEnv (filter isHole env)
2930 c1 <- convEq ctxt hs x y
3031 if c1 then return ()
3132 else
@@ -38,7 +39,7 @@ convertsC ctxt env x y =
3839
3940converts :: Context -> Env -> Term -> Term -> TC ()
4041converts ctxt env x y
41− = let hs = map fst (filter isHole env) in
42+ = let hs = map fstEnv (filter isHole env) in
4243 case convEq' ctxt hs x y of
4344 OK True -> return ()
4445 _ -> case convEq' ctxt hs (finalise (normalise ctxt env x))
@@ -48,10 +49,10 @@ converts ctxt env x y
4849 (finalise (normalise ctxt env x))
4950 (finalise (normalise ctxt env y)) (errEnv env))
5051
51−isHole (n, Hole _) = True
52+isHole (n, _, Hole _) = True
5253isHole _ = False
5354
54−errEnv = map (\(x, b) -> (x, binderTy b))
55+errEnv = map (\(x, _, b) -> (x, binderTy b))
5556
5657isType :: Context -> Env -> Term -> TC ()
5758isType ctxt env tm = isType' (normalise ctxt env tm)
@@ -86,7 +87,10 @@ check ctxt env tm
8687 = evalStateT (check' True [] ctxt env tm) (0, [])
8788
8889check' :: Bool -> String -> Context -> Env -> Raw -> StateT UCs TC (Term, Type)
89−check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top where
90+check' holes tcns ctxt env top
91+ = do (tm, ty, _) <- chk Rig1 (TType (UVar tcns (-5))) Nothing env top
92+ return (tm, ty)
93+ where
9094
9195 smaller (UType NullType) _ = UType NullType
9296 smaller _ (UType NullType) = UType NullType
@@ -97,75 +101,89 @@ check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top wh
97101 astate | holes = MaybeHoles
98102 | otherwise = Complete
99103
100− chk :: Type -> -- uniqueness level
104+ chk :: RigCount -> -- multiplicity (need enough in context to produce this many of the term)
105+ Type -> -- uniqueness level
101106 Maybe UExp -> -- universe for kind
102− Env -> Raw -> StateT UCs TC (Term, Type)
103− chk u lvl env (Var n)
104− | Just (i, ty) <- lookupTyEnv n env = return (P Bound n ty, ty)
107+ Env -> Raw -> StateT UCs TC (Term, Type, [Name])
108+ chk rigc u lvl env (Var n)
109+ | Just (i, erig, ty) <- lookupTyEnv n env
110+ = case rigSafe holes erig rigc n of
111+ Nothing -> return (P Bound n ty, ty, used rigc n)
112+ Just msg -> lift $ tfail $ Msg msg
105113 -- If we're elaborating, we don't want the private names; if we're
106114 -- checking an already elaborated term, we do
107− | [P nt n' ty] <- lookupP_all (not holes) False n ctxt
108− = return (P nt n' ty, ty)
109− -- If the names are ambiguous, require it to be fully qualified
110115 | [P nt n' ty] <- lookupP_all (not holes) True n ctxt
111− = return (P nt n' ty, ty)
116+ = return (P nt n' ty, ty, [])
117+-- -- If the names are ambiguous, require it to be fully qualified
118+-- | [P nt n' ty] <- lookupP_all (not holes) True n ctxt
119+-- = return (P nt n' ty, ty, [])
112120 | otherwise = do lift $ tfail $ NoSuchVariable n
113− chk u lvl env ap@(RApp f RType) | not holes
121+ where rigSafe True _ _ n = Nothing
122+ rigSafe _ Rig1 RigW n = Just ("Trying to use linear name " ++ show n ++ " in non-linear context")
123+ rigSafe _ Rig0 RigW n = Just ("Trying to use irrelevant name " ++ show n ++ " in relevant context")
124+ rigSafe _ _ _ n = Nothing
125+
126+ used Rig0 n = []
127+ used _ n = [n]
128+
129+ chk rigc u lvl env ap@(RApp f RType) | not holes
114130 -- special case to reduce constraintss
115− = do (fv, fty) <- chk u Nothing env f
116− let fty' = case uniqueBinders (map fst env) (finalise fty) of
117− ty@(Bind x (Pi i s k) t) -> ty
118− _ -> uniqueBinders (map fst env)
131+ = do (fv, fty, fns) <- chk rigc u Nothing env f
132+ let fty' = case uniqueBinders (map fstEnv env) (finalise fty) of
133+ ty@(Bind x (Pi _ i s k) t) -> ty
134+ _ -> uniqueBinders (map fstEnv env)
119135 $ case normalise ctxt env fty of
120− ty@(Bind x (Pi i s k) t) -> ty
136+ ty@(Bind x (Pi _ i s k) t) -> ty
121137 _ -> normalise ctxt env fty
122138 case fty' of
123− Bind x (Pi i (TType v') k) t ->
139+ Bind x (Pi rig i (TType v') k) t ->
124140 do (v, cs) <- get
125141 put (v+1, ULT (UVar tcns v) v' : cs)
126142 let apty = simplify initContext env
127143 (Bind x (Let (TType v') (TType (UVar tcns v))) t)
128− return (App Complete fv (TType (UVar tcns v)), apty)
129− Bind x (Pi i s k) t ->
130− do (av, aty) <- chk u Nothing env RType
144+ return (App Complete fv (TType (UVar tcns v)), apty, fns)
145+ Bind x (Pi rig i s k) t ->
146+ do (av, aty, _) <- chk rigc u Nothing env RType
131147 convertsC ctxt env aty s
132148 let apty = simplify initContext env
133149 (Bind x (Let aty av) t)
134− return (App astate fv av, apty)
150+ return (App astate fv av, apty, fns)
135151 t -> lift $ tfail $ NonFunctionType fv fty
136− chk u lvl env ap@(RApp f a)
137− = do (fv, fty) <- chk u Nothing env f
138− let fty' = case uniqueBinders (map fst env) (finalise fty) of
139− ty@(Bind x (Pi i s k) t) -> ty
140− _ -> uniqueBinders (map fst env)
141− $ case normalise ctxt env fty of
142− ty@(Bind x (Pi i s k) t) -> ty
143− _ -> normalise ctxt env fty
144− (av, aty) <- chk u Nothing env a
152+ chk rigc u lvl env ap@(RApp f a)
153+ = do (fv, fty, fns) <- chk rigc u Nothing env f
154+ let (rigf, fty') =
155+ case uniqueBinders (map fstEnv env) (finalise fty) of
156+ ty@(Bind x (Pi rig i s k) t) -> (rig, ty)
157+ _ -> case normalise ctxt env fty of
158+ ty@(Bind x (Pi rig i s k) t) ->
159+ (rig, uniqueBinders (map fstEnv env) ty)
160+ _ -> (RigW, uniqueBinders (map fstEnv env)
161+ (normalise ctxt env fty)) -- This is an error, caught below...
162+ (av, aty, ans) <- chk (rigMult rigc rigf) u Nothing env a
145163 case fty' of
146− Bind x (Pi i s k) t ->
164+ Bind x (Pi rig i s k) t ->
147165 do convertsC ctxt env aty s
148166 let apty = simplify initContext env
149167 (Bind x (Let aty av) t)
150− return (App astate fv av, apty)
168+ return (App astate fv av, apty, fns ++ ans)
151169 t -> lift $ tfail $ NonFunctionType fv fty
152− chk u lvl env RType
153− | holes = return (TType (UVal 0), TType (UVal 0))
170+ chk rigc u lvl env RType
171+ | holes = return (TType (UVal 0), TType (UVal 0), [])
154172 | otherwise = do (v, cs) <- get
155173 let c = ULT (UVar tcns v) (UVar tcns (v+1))
156174 put (v+2, (c:cs))
157− return (TType (UVar tcns v), TType (UVar tcns (v+1)))
158− chk u lvl env (RUType un)
159− | holes = return (UType un, TType (UVal 0))
175+ return (TType (UVar tcns v), TType (UVar tcns (v+1)), [])
176+ chk rigc u lvl env (RUType un)
177+ | holes = return (UType un, TType (UVal 0), [])
160178 | otherwise = do -- TODO! Issue #1715 on the issue tracker.
161179 -- https://github.com/idris-lang/Idris-dev/issues/1715
162180 -- (v, cs) <- get
163181 -- let c = ULT (UVar v) (UVar (v+1))
164182 -- put (v+2, (c:cs))
165183 -- return (TType (UVar v), TType (UVar (v+1)))
166− return (UType un, TType (UVal 0))
167− chk u lvl env (RConstant Forgot) = return (Erased, Erased)
168− chk u lvl env (RConstant c) = return (Constant c, constType c)
184+ return (UType un, TType (UVal 0), [])
185+ chk rigc u lvl env (RConstant Forgot) = return (Erased, Erased, [])
186+ chk rigc u lvl env (RConstant c) = return (Constant c, constType c, [])
169187 where constType (I _) = Constant (AType (ATInt ITNative))
170188 constType (BI _) = Constant (AType (ATInt ITBig))
171189 constType (Fl _) = Constant (AType ATFloat)
@@ -178,15 +196,17 @@ check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top wh
178196 constType TheWorld = Constant WorldType
179197 constType Forgot = Erased
180198 constType _ = TType (UVal 0)
181− chk u lvl env (RBind n (Pi i s k) t)
182− = do (sv, st) <- chk u Nothing env s
199+ chk rigc u lvl env (RBind n (Pi rig i s k) t)
200+ = do (sv, st, sns) <- chk Rig0 u Nothing (envZero env) s
201+ when (rig == RigW) $
202+ lift $ linearCheckArg ctxt (normalise ctxt env sv)
183203 (v, cs) <- get
184− (kv, kt) <- chk u Nothing env k -- no need to validate these constraints, they are independent
204+ (kv, kt, _) <- chk Rig0 u Nothing (envZero env) k -- no need to validate these constraints, they are independent
185205 put (v+1, cs)
186206 let maxu = case lvl of
187207 Nothing -> UVar tcns v
188208 Just v' -> v'
189− (tv, tt) <- chk st (Just maxu) ((n, Pi i sv kv) : env) t
209+ (tv, tt, tns) <- chk Rig0 st (Just maxu) ((n, Rig0, Pi Rig0 i sv kv) : envZero env) t
190210
191211-- convertsC ctxt env st (TType maxu)
192212-- convertsC ctxt env tt (TType maxu)
@@ -200,18 +220,18 @@ check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top wh
200220 put (v, ULE su maxu :
201221 ULE tu maxu : cs)
202222 let k' = TType (UVar tcns v) `smaller` st `smaller` kv `smaller` u
203− return (Bind n (Pi i (uniqueBinders (map fst env) sv) k')
204− (pToV n tv), k')
223+ return (Bind n (Pi rig i (uniqueBinders (map fstEnv env) sv) k')
224+ (pToV n tv), k', sns ++ tns)
205225 (un, un') ->
206226 let k' = st `smaller` kv `smaller` un `smaller` un' `smaller` u in
207− return (Bind n (Pi i (uniqueBinders (map fst env) sv) k')
208− (pToV n tv), k')
227+ return (Bind n (Pi rig i (uniqueBinders (map fstEnv env) sv) k')
228+ (pToV n tv), k', sns ++ tns)
209229
210− where mkUniquePi kv (Bind n (Pi i s k) sc)
230+ where mkUniquePi kv (Bind n (Pi rig i s k) sc)
211231 = let k' = smaller kv k in
212− Bind n (Pi i s k') (mkUniquePi k' sc)
213− mkUniquePi kv (Bind n (Lam t) sc)
214− = Bind n (Lam (mkUniquePi kv t)) (mkUniquePi kv sc)
232+ Bind n (Pi rig i s k') (mkUniquePi k' sc)
233+ mkUniquePi kv (Bind n (Lam rig t) sc)
234+ = Bind n (Lam rig (mkUniquePi kv t)) (mkUniquePi kv sc)
215235 mkUniquePi kv (Bind n (Let t v) sc)
216236 = Bind n (Let (mkUniquePi kv t) v) (mkUniquePi kv sc)
217237 mkUniquePi kv t = t
@@ -219,84 +239,103 @@ check' holes tcns ctxt env top = chk (TType (UVar tcns (-5))) Nothing env top wh
219239 -- Kind of the whole thing is the kind of the most unique thing
220240 -- in the environment (because uniqueness taints everything...)
221241 mostUnique [] k = k
222− mostUnique (Pi _ _ pk : es) k = mostUnique es (smaller pk k)
242+ mostUnique (Pi _ _ _ pk : es) k = mostUnique es (smaller pk k)
223243 mostUnique (_ : es) k = mostUnique es k
224244
225− chk u lvl env (RBind n b sc)
226− = do (b', bt') <- checkBinder b
227− (scv, sct) <- chk (smaller bt' u) Nothing ((n, b'):env) sc
228− discharge n b' bt' (pToV n scv) (pToV n sct)
229− where checkBinder (Lam t)
230− = do (tv, tt) <- chk u Nothing env t
245+ chk rigc u lvl env (RBind n b sc)
246+ = do (b', bt', bns) <- checkBinder b
247+ (scv, sct, scns) <- chk rigc (smaller bt' u) Nothing ((n, getCount b, b'):env) sc
248+ when (getCount b == RigW) $
249+ lift $ linearCheckArg ctxt (normalise ctxt env (binderTy b'))
250+ checkUsageOK (getCount b) scns
251+ discharge n b' bt' (pToV n scv) (pToV n sct) (bns ++ scns)
252+ where getCount (Pi rig _ _ _) = rigMult rigc rig
253+ getCount (PVar rig _) = rigMult rigc rig
254+ getCount (Lam rig _) = rigMult rigc rig
255+ getCount _ = rigMult rigc RigW
256+
257+ checkUsageOK Rig0 _ = return ()
258+ checkUsageOK RigW _ = return ()
259+ checkUsageOK Rig1 ns
260+ = let used = length (filter (==n) ns) in
261+ if used == 1 then return ()
262+ else lift $ tfail $ Msg $ "There are " ++ (show used) ++
263+ " uses of linear name " ++ show n
264+
265+ checkBinder (Lam rig t)
266+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
231267 let tv' = normalise ctxt env tv
232268 convType tcns ctxt env tt
233− return (Lam tv, tt)
269+ return (Lam rig tv, tt, [])
234270 checkBinder (Let t v)
235− = do (tv, tt) <- chk u Nothing env t
236− (vv, vt) <- chk u Nothing env v
271+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
272+ -- May have multiple uses, check at RigW
273+ -- (or rather, like an application of a lambda, multiply)
274+ -- (Consider: adding a single use let?)
275+ (vv, vt, vns) <- chk (rigMult rigc RigW) u Nothing env v
237276 let tv' = normalise ctxt env tv
238277 convertsC ctxt env vt tv
239278 convType tcns ctxt env tt
240− return (Let tv vv, tt)
279+ return (Let tv vv, tt, vns)
241280 checkBinder (NLet t v)
242− = do (tv, tt) <- chk u Nothing env t
243− (vv, vt) <- chk u Nothing env v
281+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
282+ (vv, vt, vns) <- chk rigc u Nothing env v
244283 let tv' = normalise ctxt env tv
245284 convertsC ctxt env vt tv
246285 convType tcns ctxt env tt
247− return (NLet tv vv, tt)
286+ return (NLet tv vv, tt, vns)
248287 checkBinder (Hole t)
249288 | not holes = lift $ tfail (IncompleteTerm undefined)
250289 | otherwise
251− = do (tv, tt) <- chk u Nothing env t
290+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
252291 let tv' = normalise ctxt env tv
253292 convType tcns ctxt env tt
254− return (Hole tv, tt)
293+ return (Hole tv, tt, [])
255294 checkBinder (GHole i ns t)
256− = do (tv, tt) <- chk u Nothing env t
295+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
257296 let tv' = normalise ctxt env tv
258297 convType tcns ctxt env tt
259− return (GHole i ns tv, tt)
298+ return (GHole i ns tv, tt, [])
260299 checkBinder (Guess t v)
261300 | not holes = lift $ tfail (IncompleteTerm undefined)
262301 | otherwise
263− = do (tv, tt) <- chk u Nothing env t
264− (vv, vt) <- chk u Nothing env v
302+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
303+ (vv, vt, vns) <- chk rigc u Nothing env v
265304 let tv' = normalise ctxt env tv
266305 convertsC ctxt env vt tv
267306 convType tcns ctxt env tt
268− return (Guess tv vv, tt)
269− checkBinder (PVar t)
270− = do (tv, tt) <- chk u Nothing env t
307+ return (Guess tv vv, tt, vns)
308+ checkBinder (PVar rig t)
309+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
271310 let tv' = normalise ctxt env tv
272311 convType tcns ctxt env tt
273312 -- Normalised version, for erasure purposes (it's easier
274313 -- to tell if it's a collapsible variable)
275− return (PVar tv, tt)
314+ return (PVar rig tv, tt, [])
276315 checkBinder (PVTy t)
277− = do (tv, tt) <- chk u Nothing env t
316+ = do (tv, tt, _) <- chk Rig0 u Nothing (envZero env) t
278317 let tv' = normalise ctxt env tv
279318 convType tcns ctxt env tt
280− return (PVTy tv, tt)
281−
282− discharge n (Lam t) bt scv sct
283− = return (Bind n (Lam t) scv, Bind n (Pi Nothing t bt) sct)
284− discharge n (Pi i t k) bt scv sct
285− = return (Bind n (Pi i t k) scv, sct)
286− discharge n (Let t v) bt scv sct
287− = return (Bind n (Let t v) scv, Bind n (Let t v) sct)
288− discharge n (NLet t v) bt scv sct
289− = return (Bind n (NLet t v) scv, Bind n (Let t v) sct)
290− discharge n (Hole t) bt scv sct
291− = return (Bind n (Hole t) scv, sct)
292− discharge n (GHole i ns t) bt scv sct
293− = return (Bind n (GHole i ns t) scv, sct)
294− discharge n (Guess t v) bt scv sct
295− = return (Bind n (Guess t v) scv, sct)
296− discharge n (PVar t) bt scv sct
297− = return (Bind n (PVar t) scv, Bind n (PVTy t) sct)
298− discharge n (PVTy t) bt scv sct
299− = return (Bind n (PVTy t) scv, sct)
319+ return (PVTy tv, tt, [])
320+
321+ discharge n (Lam r t) bt scv sct ns
322+ = return (Bind n (Lam r t) scv, Bind n (Pi r Nothing t bt) sct, ns)
323+ discharge n (Pi r i t k) bt scv sct ns
324+ = return (Bind n (Pi r i t k) scv, sct, ns)
325+ discharge n (Let t v) bt scv sct ns
326+ = return (Bind n (Let t v) scv, Bind n (Let t v) sct, ns)
327+ discharge n (NLet t v) bt scv sct ns
328+ = return (Bind n (NLet t v) scv, Bind n (Let t v) sct, ns)
329+ discharge n (Hole t) bt scv sct ns
330+ = return (Bind n (Hole t) scv, sct, ns)
331+ discharge n (GHole i ns t) bt scv sct uns
332+ = return (Bind n (GHole i ns t) scv, sct, uns)
333+ discharge n (Guess t v) bt scv sct ns
334+ = return (Bind n (Guess t v) scv, sct, ns)
335+ discharge n (PVar r t) bt scv sct ns
336+ = return (Bind n (PVar r t) scv, Bind n (PVTy t) sct, ns)
337+ discharge n (PVTy t) bt scv sct ns
338+ = return (Bind n (PVTy t) scv, sct, ns)
300339
301340-- Number of times a name can be used
302341data UniqueUse = Never -- no more times
@@ -316,7 +355,7 @@ checkUnique borrowed ctxt env tm
316355 isVar _ = False
317356
318357 chkBinders :: Env -> Term -> StateT [(Name, (UniqueUse, Universe))] TC ()
319− chkBinders env (V i) | length env > i = chkName (fst (env!!i))
358+ chkBinders env (V i) | length env > i = chkName (fstEnv (env!!i))
320359 chkBinders env (P _ n _) = chkName n
321360 -- 'lending' a unique or nulltype variable doesn't count as a use,
322361 -- but we still can't lend something that's already been used.
@@ -336,13 +375,13 @@ checkUnique borrowed ctxt env tm
336375 case b of
337376 Let t v -> chkBinders env v
338377 _ -> return ()
339− chkBinders ((n, b) : env) t
378+ chkBinders ((n, Rig0, b) : env) t
340379 chkBinders env t = return ()
341380
342381 chkBinderName :: Env -> Name -> Binder Term ->
343382 StateT [(Name, (UniqueUse, Universe))] TC ()
344383 chkBinderName env n b
345− = do let rawty = forgetEnv (map fst env) (binderTy b)
384+ = do let rawty = forgetEnv (map fstEnv env) (binderTy b)
346385 (_, kind) <- lift $ check ctxt env rawty
347386 case kind of
348387 UType UniqueType -> do ns <- get
src/Idris/Core/Unify.hs+40−40
@@ -140,8 +140,8 @@ match_unify ctxt env (topx, xfrom) (topy, yfrom) inj holes from =
140140 uB bnames (Let tx vx) (Let ty vy) = do h1 <- un bnames tx ty
141141 h2 <- un bnames vx vy
142142 combine bnames h1 h2
143− uB bnames (Lam tx) (Lam ty) = un bnames tx ty
144− uB bnames (Pi i tx _) (Pi i' ty _) = un bnames tx ty
143+ uB bnames (Lam _ tx) (Lam _ ty) = un bnames tx ty
144+ uB bnames (Pi r i tx _) (Pi r' i' ty _) = un bnames tx ty
145145 uB bnames x y = do UI s f <- get
146146 let r = recoverable (normalise ctxt env (binderTy x))
147147 (normalise ctxt env (binderTy y))
@@ -204,13 +204,13 @@ match_unify ctxt env (topx, xfrom) (topy, yfrom) inj holes from =
204204 bind i ns tm
205205 | i < 0 = tm
206206 | otherwise = let ((x,y),ty) = ns!!i in
207− App MaybeHoles (Bind y (Lam ty) (bind (i-1) ns tm))
207+ App MaybeHoles (Bind y (Lam RigW ty) (bind (i-1) ns tm))
208208 (P Bound x ty)
209209
210210renameBinders env (x, t) = (x, renameBindersTm env t)
211211
212212renameBindersTm :: Env -> TT Name -> TT Name
213−renameBindersTm env tm = uniqueBinders (map fst env) tm
213+renameBindersTm env tm = uniqueBinders (map fstEnv env) tm
214214 where
215215 uniqueBinders env (Bind n b sc)
216216 | n `elem` env
@@ -370,7 +370,7 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
370370 = case compare (envPos 0 x env) (envPos 0 y env) of
371371 LT -> do sc 1; checkCycle bnames (x, ty)
372372 _ -> do sc 1; checkCycle bnames (y, tx)
373− where envPos i n ((n',_):env) | n == n' = i
373+ where envPos i n ((n',_,_):env) | n == n' = i
374374 envPos i n (_:env) = envPos (i+1) n env
375375 envPos _ _ _ = 100000
376376 un' env fn bnames xtm@(P _ x _) tm
@@ -424,7 +424,7 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
424424 = -- trace ("PATTERN RULE SOLVE: " ++ show (mv, tm, env, bindLams args (substEnv env tm))) $
425425 checkCycle bnames (mv, eta [] $ bindLams args (substEnv env tm))
426426 where rigid (V i) = True
427− rigid (P _ t _) = t `elem` map fst env &&
427+ rigid (P _ t _) = t `elem` map fstEnv env &&
428428 not (holeIn env t || t `elem` holes)
429429 rigid _ = False
430430
@@ -450,24 +450,24 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
450450 bindLams [] tm = tm
451451 bindLams (a : as) tm = bindLam a (bindLams as tm)
452452
453− bindLam (V i) tm = Bind (fst (env !! i))
454− (Lam (binderTy (snd (env !! i))))
453+ bindLam (V i) tm = Bind (fstEnv (env !! i))
454+ (Lam RigW (binderTy (sndEnv (env !! i))))
455455 tm
456− bindLam (P _ n ty) tm = Bind n (Lam ty) tm
456+ bindLam (P _ n ty) tm = Bind n (Lam RigW ty) tm
457457 bindLam _ tm = error "Can't happen [non rigid bindLam]"
458458
459459 substEnv [] tm = tm
460− substEnv ((n, t) : env) tm
460+ substEnv ((n, _, t) : env) tm
461461 = substEnv env (substV (P Bound n (binderTy t)) tm)
462462
463463 -- remove any unnecessary lambdas (helps with interface
464464 -- resolution later).
465− eta ks (Bind n (Lam ty) sc) = eta ((n, ty) : ks) sc
465+ eta ks (Bind n (Lam r ty) sc) = eta ((n, r, ty) : ks) sc
466466 eta ks t = rebind ks t
467467
468− rebind ((n, ty) : ks) (App _ f (P _ n' _))
468+ rebind ((n, r, ty) : ks) (App _ f (P _ n' _))
469469 | n == n' = eta ks f
470− rebind ((n, ty) : ks) t = rebind ks (Bind n (Lam ty) t)
470+ rebind ((n, r, ty) : ks) t = rebind ks (Bind n (Lam r ty) t)
471471 rebind _ t = t
472472
473473 un' env fn bnames appx@(App _ _ _) appy@(App _ _ _)
@@ -475,13 +475,13 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
475475-- = uplus (unApp fn bnames appx appy)
476476-- (unifyTmpFail appx appy) -- take the whole lot
477477
478− un' env fn bnames x (Bind n (Lam t) (App _ y (P Bound n' _)))
478+ un' env fn bnames x (Bind n (Lam _ t) (App _ y (P Bound n' _)))
479479 | n == n' = un' env False bnames x y
480− un' env fn bnames (Bind n (Lam t) (App _ x (P Bound n' _))) y
480+ un' env fn bnames (Bind n (Lam _ t) (App _ x (P Bound n' _))) y
481481 | n == n' = un' env False bnames x y
482− un' env fn bnames x (Bind n (Lam t) (App _ y (V 0)))
482+ un' env fn bnames x (Bind n (Lam _ t) (App _ y (V 0)))
483483 = un' env False bnames x y
484− un' env fn bnames (Bind n (Lam t) (App _ x (V 0))) y
484+ un' env fn bnames (Bind n (Lam _ t) (App _ x (V 0))) y
485485 = un' env False bnames x y
486486-- un' env fn bnames (Bind x (PVar _) sx) (Bind y (PVar _) sy)
487487-- = un' env False ((x,y):bnames) sx sy
@@ -491,27 +491,27 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
491491 -- f D unifies with t -> D. This is dubious, but it helps with
492492 -- interface resolution for interfaces over functions.
493493
494− un' env fn bnames (App _ f x) (Bind n (Pi i t k) y)
494+ un' env fn bnames (App _ f x) (Bind n (Pi r i t k) y)
495495 | noOccurrence n y && injectiveApp f
496496 = do ux <- un' env False bnames x y
497− uf <- un' env False bnames f (Bind (sMN 0 "uv") (Lam (TType (UVar [] 0)))
498− (Bind n (Pi i t k) (V 1)))
497+ uf <- un' env False bnames f (Bind (sMN 0 "uv") (Lam RigW (TType (UVar [] 0)))
498+ (Bind n (Pi r i t k) (V 1)))
499499 combine env bnames ux uf
500500
501− un' env fn bnames (Bind n (Pi i t k) y) (App _ f x)
501+ un' env fn bnames (Bind n (Pi r i t k) y) (App _ f x)
502502 | noOccurrence n y && injectiveApp f
503503 = do ux <- un' env False bnames y x
504− uf <- un' env False bnames (Bind (sMN 0 "uv") (Lam (TType (UVar [] 0)))
505− (Bind n (Pi i t k) (V 1))) f
504+ uf <- un' env False bnames (Bind (sMN 0 "uv") (Lam RigW (TType (UVar [] 0)))
505+ (Bind n (Pi r i t k) (V 1))) f
506506 combine env bnames ux uf
507507
508508 un' env fn bnames (Bind x bx sx) (Bind y by sy)
509509 | sameBinder bx by
510510 = do h1 <- uB env bnames bx by
511− h2 <- un' ((x, bx) : env) False (((x,y),binderTy bx):bnames) sx sy
511+ h2 <- un' ((x, RigW, bx) : env) False (((x,y),binderTy bx):bnames) sx sy
512512 combine env bnames h1 h2
513− where sameBinder (Lam _) (Lam _) = True
514− sameBinder (Pi i _ _) (Pi i' _ _) = True
513+ where sameBinder (Lam _ _) (Lam _ _) = True
514+ sameBinder (Pi _ i _ _) (Pi _ i' _ _) = True
515515 sameBinder _ _ = False -- never unify holes/guesses/etc
516516 un' env fn bnames x y
517517 | OK True <- convEq' ctxt holes x y = do sc 1; return []
@@ -606,7 +606,7 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
606606 P _ x _ -> x `elem` holes || patIn env x
607607 _ -> False
608608 inenv t = case t of
609− P _ x _ -> x `elem` (map fst env)
609+ P _ x _ -> x `elem` (map fstEnv env)
610610 _ -> False
611611
612612 notFn t = injective t || metavar t || inenv t
@@ -642,10 +642,10 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
642642 h2 <- un' env False bnames vx vy
643643 sc 1
644644 combine env bnames h1 h2
645− uB env bnames (Lam tx) (Lam ty) = do sc 1; un' env False bnames tx ty
646− uB env bnames (Pi _ tx _) (Pi _ ty _) = do sc 1; un' env False bnames tx ty
645+ uB env bnames (Lam _ tx) (Lam _ ty) = do sc 1; un' env False bnames tx ty
646+ uB env bnames (Pi _ _ tx _) (Pi _ _ ty _) = do sc 1; un' env False bnames tx ty
647647 uB env bnames (Hole tx) (Hole ty) = un' env False bnames tx ty
648− uB env bnames (PVar tx) (PVar ty) = un' env False bnames tx ty
648+ uB env bnames (PVar _ tx) (PVar _ ty) = un' env False bnames tx ty
649649 uB env bnames x y
650650 = do UI s f <- get
651651 let r = recoverable (normalise ctxt env (binderTy x))
@@ -679,7 +679,7 @@ unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
679679 bind i ns tm
680680 | i < 0 = tm
681681 | otherwise = let ((x,y),ty) = ns!!i in
682− App MaybeHoles (Bind y (Lam ty) (bind (i-1) ns tm))
682+ App MaybeHoles (Bind y (Lam RigW ty) (bind (i-1) ns tm))
683683 (P Bound x ty)
684684
685685 combine env bnames as [] = return as
@@ -754,33 +754,33 @@ recoverable (App _ f a) (App _ f' a')
754754 | f == f' = recoverable a a'
755755recoverable (App _ f a) (App _ f' a')
756756 = recoverable f f' -- && recoverable a a'
757−recoverable f (Bind _ (Pi _ _ _) sc)
757+recoverable f (Bind _ (Pi _ _ _ _) sc)
758758 | (P (DCon _ _ _) _ _, _) <- unApply f = False
759759 | (P (TCon _ _) _ _, _) <- unApply f = False
760760 | (Constant _) <- f = False
761761 | TType _ <- f = False
762762 | UType _ <- f = False
763−recoverable (Bind _ (Pi _ _ _) sc) f
763+recoverable (Bind _ (Pi _ _ _ _) sc) f
764764 | (P (DCon _ _ _) _ _, _) <- unApply f = False
765765 | (P (TCon _ _) _ _, _) <- unApply f = False
766766 | (Constant _) <- f = False
767767 | TType _ <- f = False
768768 | UType _ <- f = False
769−recoverable (Bind _ (Lam _) sc) f = recoverable sc f
770−recoverable f (Bind _ (Lam _) sc) = recoverable f sc
769+recoverable (Bind _ (Lam _ _) sc) f = recoverable sc f
770+recoverable f (Bind _ (Lam _ _) sc) = recoverable f sc
771771recoverable x y = True
772772
773−errEnv :: [(a, Binder b)] -> [(a, b)]
774−errEnv = map (\(x, b) -> (x, binderTy b))
773+errEnv :: [(a, r, Binder b)] -> [(a, b)]
774+errEnv = map (\(x, _, b) -> (x, binderTy b))
775775
776776holeIn :: Env -> Name -> Bool
777−holeIn env n = case lookup n env of
777+holeIn env n = case lookupBinder n env of
778778 Just (Hole _) -> True
779779 Just (Guess _ _) -> True
780780 _ -> False
781781
782782patIn :: Env -> Name -> Bool
783−patIn env n = case lookup n env of
784− Just (PVar _) -> True
783+patIn env n = case lookupBinder n env of
784+ Just (PVar _ _) -> True
785785 Just (PVTy _) -> True
786786 _ -> False
src/Idris/Core/WHNF.hs+70−25
@@ -8,7 +8,7 @@ Maintainer : The Idris Community.
88
99{-# LANGUAGE PatternGuards #-}
1010{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
11−module Idris.Core.WHNF(whnf, WEnv) where
11+module Idris.Core.WHNF(whnf, whnfArgs, WEnv) where
1212
1313import Idris.Core.CaseTree
1414import Idris.Core.Evaluate hiding (quote)
@@ -20,6 +20,7 @@ import Debug.Trace
2020-- | A stack entry consists of a term and the environment it is to be
2121-- evaluated in (i.e. it's a thunk)
2222type StackEntry = (Term, WEnv)
23+
2324data WEnv = WEnv Int -- number of free variables
2425 [(Term, WEnv)]
2526 deriving Show
@@ -34,10 +35,11 @@ type Stack = [StackEntry]
3435-- environment it was encountered in, so that when we quote back to a term
3536-- we get the substitutions right.
3637
37−data WHNF = WDCon Int Int Bool Name (Type, WEnv) -- ^ data constructor
38+data WHNF = WDCon Int Int Bool Name (Term, WEnv) -- ^ data constructor
3839 | WTCon Int Int Name (Type, WEnv) -- ^ type constructor
39− | WPRef Name (Type, WEnv) -- ^irreducible global (e.g. a postulate)
40− | WBind Name (Binder Term) (Term, WEnv)
40+ | WPRef Name (Term, WEnv) -- ^irreducible global (e.g. a postulate)
41+ | WV Int
42+ | WBind Name (Binder (Term, WEnv)) (Term, WEnv)
4143 | WApp WHNF (Term, WEnv)
4244 | WConstant Const
4345 | WProj WHNF Int
@@ -46,24 +48,56 @@ data WHNF = WDCon Int Int Bool Name (Type, WEnv) -- ^ data constructor
4648 | WErased
4749 | WImpossible
4850
49−-- | Reduce a *closed* term to weak head normal form.
50−whnf :: Context -> Term -> Term
51−whnf ctxt tm = quote (do_whnf ctxt (WEnv 0 []) tm)
51+-- NOTE: These aren't yet ready to be used in practice - there's still a
52+-- bug or two in the handling of de Bruijn indices.
53+
54+-- | Reduce a term to weak head normal form.
55+whnf :: Context -> Env -> Term -> Term
56+-- whnf ctxt env tm = let res = whnf' ctxt env tm in
57+-- trace (show tm ++ "\n==>\n" ++ show res ++ "\n") res
58+whnf ctxt env tm =
59+ inlineSmall ctxt env $ -- reduce small things in body. This is primarily
60+ -- to get rid of any noisy "assert_smaller/assert_total"
61+ -- and evaluate any simple operators, which makes things
62+ -- easier to read.
63+ whnf' ctxt env tm
64+whnf' ctxt env tm =
65+ quote (do_whnf ctxt (map finalEntry env) (finalise tm))
66+
67+-- | Reduce a type so that all arguments are expanded
68+whnfArgs :: Context -> Env -> Term -> Term
69+whnfArgs ctxt env tm = inlineSmall ctxt env $ finalise (whnfArgs' ctxt env tm)
70+whnfArgs' ctxt env tm
71+ = case whnf' ctxt env tm of
72+ -- The assumption is that de Bruijn indices refer to local things
73+ -- (so not in the external environment) so we need to instantiate
74+ -- the name
75+ Bind n b@(Pi rig _ ty _) sc ->
76+ Bind n b (whnfArgs' ctxt ((n, rig, b):env)
77+ (subst n (P Bound n ty) sc))
78+ res -> tm
79+
80+finalEntry :: (Name, RigCount, Binder (TT Name)) -> (Name, RigCount, Binder (TT Name))
81+finalEntry (n, r, b) = (n, r, fmap finalise b)
5282
53−do_whnf :: Context -> WEnv -> Term -> WHNF
54−do_whnf ctxt env tm = eval env [] tm
83+do_whnf :: Context -> Env -> Term -> WHNF
84+do_whnf ctxt genv tm = eval (WEnv 0 []) [] tm
5585 where
5686 eval :: WEnv -> Stack -> Term -> WHNF
5787 eval wenv@(WEnv d env) stk (V i)
5888 | i < length env = let (tm, env') = env !! i in
5989 eval env' stk tm
60− | otherwise = error "Can't happen: WHNF scope error"
90+ | otherwise = WV i
6191 eval wenv@(WEnv d env) stk (Bind n (Let t v) sc)
6292 = eval (WEnv d ((v, wenv) : env)) stk sc
63− eval (WEnv d env) [] (Bind n b sc) = WBind n b (sc, WEnv (d + 1) env)
64− eval (WEnv d env) ((tm, tenv) : stk) (Bind n b sc)
93+ eval (WEnv d env) ((tm, tenv) : stk) (Bind n b@(Lam _ _) sc)
6594 = eval (WEnv d ((tm, tenv) : env)) stk sc
95+ eval wenv@(WEnv d env) stk (Bind n b sc) -- stk must be empty if well typed
96+ =let n' = uniqueName n (map fstEnv genv) in
97+ WBind n' (fmap (\t -> (t, wenv)) b) (sc, WEnv (d + 1) env)
6698
99+ eval env stk (P nt n ty)
100+ | Just (Let t v) <- lookupBinder n genv = eval env stk v
67101 eval env stk (P nt n ty) = apply env nt n ty stk
68102 eval env stk (App _ f a) = eval env ((a, env) : stk) f
69103 eval env stk (Constant c) = unload (WConstant c) stk
@@ -73,30 +107,34 @@ do_whnf ctxt env tm = eval env [] tm
73107
74108 eval env stk Erased = unload WErased stk
75109 eval env stk Impossible = unload WImpossible stk
110+ eval env stk (Inferred tm) = eval env stk tm
76111 eval env stk (TType u) = unload (WType u) stk
77112 eval env stk (UType u) = unload (WUType u) stk
78113
79114 apply :: WEnv -> NameType -> Name -> Type -> Stack -> WHNF
80− apply env nt n ty stk
115+ apply env nt n ty stk
81116 = let wp = case nt of
82117 DCon t a u -> WDCon t a u n (ty, env)
83118 TCon t a -> WTCon t a n (ty, env)
84119 Ref -> WPRef n (ty, env)
85120 _ -> WPRef n (ty, env)
86121 in
87− case lookupDefExact n ctxt of
88− Just (CaseOp ci _ _ _ _ cd) ->
89− let (ns, tree) = cases_compiletime cd in
90− case evalCase env ns tree stk of
91− Just w -> w
92− Nothing -> unload wp stk
93− Just (Operator _ i op) ->
122+ if not (tcReducible n ctxt)
123+ then unload wp stk
124+ else case lookupDefAccExact n False ctxt of
125+ Just (CaseOp ci _ _ _ _ cd, acc)
126+ | acc == Public || acc == Hidden ->
127+ let (ns, tree) = cases_compiletime cd in
128+ case evalCase env ns tree stk of
129+ Just w -> w
130+ Nothing -> unload wp stk
131+ Just (Operator _ i op, acc) ->
94132 if i <= length stk
95133 then case runOp env op (take i stk) (drop i stk) of
96134 Just v -> v
97135 Nothing -> unload wp stk
98136 else unload wp stk
99− _ -> unload wp stk
137+ _ -> unload wp stk
100138
101139 unload :: WHNF -> Stack -> WHNF
102140 unload f [] = f
@@ -112,6 +150,8 @@ do_whnf ctxt env tm = eval env [] tm
112150 -- aren't run on constants are themselves pretty ugly
113151 -- (it's prim__believe_me and prim__syntacticEq, for
114152 -- example) so let's not worry too much...
153+ -- We will need to deal with believe_me before dropping this
154+ -- into the type checker, though.
115155 Just val -> Just $ eval env rest (quoteTerm val)
116156 _ -> Nothing
117157
@@ -189,7 +229,9 @@ quote :: WHNF -> Term
189229quote (WDCon t a u n (ty, env)) = P (DCon t a u) n (quoteEnv env ty)
190230quote (WTCon t a n (ty, env)) = P (TCon t a) n (quoteEnv env ty)
191231quote (WPRef n (ty, env)) = P Ref n (quoteEnv env ty)
192−quote (WBind n ty (sc, env)) = Bind n ty (quoteEnv env sc)
232+quote (WV i) = V i
233+quote (WBind n b (sc, env)) = Bind n (fmap (\ (t, env) -> quoteEnv env t) b)
234+ (quoteEnv env sc)
193235quote (WApp f (a, env)) = App Complete (quote f) (quoteEnv env a)
194236quote (WConstant c) = Constant c
195237quote (WProj t i) = Proj (quote t) i
@@ -201,10 +243,13 @@ quote WImpossible = Impossible
201243quoteEnv :: WEnv -> Term -> Term
202244quoteEnv (WEnv d ws) tm = qe' d ws tm
203245 where
246+ -- d is number of free variables in the external environment
247+ -- (all bound in the scope of 'ws')
204248 qe' d ts (V i)
205− | i < d = V i
206− | otherwise = let (tm, env) = ts !! (i - d) in
207− quoteEnv env tm
249+ | (i - d) < length ts && (i - d) >= 0
250+ = let (tm, env) = ts !! (i - d) in
251+ quoteEnv env tm
252+ | otherwise = V i
208253 qe' d ts (Bind n b sc)
209254 = Bind n (fmap (qe' d ts) b) (qe' (d + 1) ts sc)
210255 qe' d ts (App c f a)
src/Idris/Coverage.hs+302−256
@@ -6,7 +6,8 @@ License : BSD3
66Maintainer : The Idris Community.
77-}
88{-# LANGUAGE PatternGuards #-}
9−module Idris.Coverage where
9+module Idris.Coverage(genClauses, validCoverageCase, recoverableCoverage,
10+ mkPatTm) where
1011
1112import Idris.AbsSyntax
1213import Idris.Core.CaseTree
@@ -61,100 +62,269 @@ mkPatTm t = do i <- getIState
6162--
6263-- This will only work after the given clauses have been typechecked and the
6364-- names are fully explicit!
64−genClauses :: FC -> Name -> [Term] -> [PTerm] -> Idris [PTerm]
65−genClauses fc n xs given
65+genClauses :: FC -> Name -> [([Name], Term)] -> -- (Argument names, LHS)
66+ [PTerm] -> Idris [PTerm]
67+-- No clauses (only valid via elab reflection). We should probably still do
68+-- a check here somehow, e.g. that one of the arguments is an obviously
69+-- empty type. In practice, this should only really be used for Void elimination.
70+genClauses fc n lhs_tms [] = return []
71+genClauses fc n lhs_tms given
6672 = do i <- getIState
67− let lhs_tms = map (\x -> flattenArgs $ delab' i x True True) xs
68− -- if a placeholder was given, don't bother generating cases for it
69− let lhs_tms' = zipWith mergePlaceholders lhs_tms
70− (map (stripUnmatchable i) (map flattenArgs given))
71− let lhss = map pUnApply lhs_tms'
72− nty <- case lookupTyExact n (tt_ctxt i) of
73− Just t -> return (normalise (tt_ctxt i) [] t)
74− _ -> fail "Can't happen - genClauses, lookupTyExact"
75−
76− let argss = transpose lhss
77− let all_args = map (genAll i) (zip (genPH i nty) argss)
78− logCoverage 5 $ "COVERAGE of " ++ show n
79− logCoverage 5 $ "using type " ++ show nty
80− logCoverage 5 $ "non-concrete args " ++ show (genPH i nty)
81−
82− logCoverage 5 $ show (lhs_tms, lhss)
83− logCoverage 5 $ "Args are: " ++ show argss
84− logCoverage 5 $ show (map length argss) ++ "\nAll args:\n" ++ show (map length all_args)
85− logCoverage 10 $ "All args are: " ++ show all_args
86− logCoverage 3 $ "Original: \n" ++
87− showSep "\n" (map (\t -> showTmImpls (delab' i t True True)) xs)
88− -- add an infinite supply of explicit arguments to update the possible
89− -- cases for (the return type may be variadic, or function type, so
90− -- there may be more case splitting that the idris_implicits record
91− -- suggests)
92− let parg = case lookupCtxt n (idris_implicits i) of
93− (p : _) ->
94− p ++ repeat (PExp 0 [] (sMN 0 "gcarg") Placeholder)
95− _ -> repeat (pexp Placeholder)
96− let tryclauses = mkClauses parg all_args
97− logCoverage 3 $ show (length tryclauses) ++ " initially to check"
98− logCoverage 2 $ showSep "\n" (map (showTm i) tryclauses)
99−
100− let xsdelab = map (\x -> stripUnmatchable i (delab' i x True True)) xs
101− let new = filter (noMatch i xsdelab) tryclauses
102− logCoverage 2 $ show (length new) ++ " clauses to check for impossibility"
103− logCoverage 4 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
104−-- ++ " from:\n" ++ showSep "\n" (map (showImp True) tryclauses)
105− return new
106−-- return (map (\t -> PClause n t [] PImpossible []) new)
107− where getLHS i term
108− | (f, args) <- unApply term = map (\t -> delab' i t True True) args
109− | otherwise = []
110−
111− -- if an argument has a non-concrete type (i.e. it's a function
112− -- that calculates something from a previous argument) we'll also
113− -- need to generate a placeholder pattern for it since it could be
114− -- anything based on earlier values
115− genPH :: IState -> Type -> [Bool]
116− genPH ist (Bind n (Pi _ ty _) sc) = notConcrete ist ty : genPH ist sc
117− genPH ist ty = []
118−
119− notConcrete ist t | (P _ n _, args) <- unApply t,
120− not (isConName n (tt_ctxt ist)) = True
121− notConcrete _ _ = False
122−
123− pUnApply (PApp _ f args) = map getTm args
124− pUnApply _ = []
125−
73+
74+ let lhs_given = zipWith removePlaceholders lhs_tms
75+ (map (stripUnmatchable i) (map flattenArgs given))
76+
77+ logCoverage 5 $ "Building coverage tree for:\n" ++ showSep "\n" (map show (lhs_given))
78+ let givenpos = mergePos (map getGivenPos given)
79+
80+ (cns, ctree_in) <-
81+ case simpleCase False (UnmatchedCase "Undefined") False
82+ (CoverageCheck givenpos) emptyFC [] []
83+ lhs_given
84+ (const []) of
85+ OK (CaseDef cns ctree_in _) ->
86+ return (cns, ctree_in)
87+ Error e -> tclift $ tfail $ At fc e
88+
89+ let ctree = trimOverlapping (addMissingCons i ctree_in)
90+ let (coveredas, missingas) = mkNewClauses (tt_ctxt i) n cns ctree
91+ let covered = map (\t -> delab' i t True True) coveredas
92+ let missing = filter (\x -> x `notElem` covered) $
93+ map (\t -> delab' i t True True) missingas
94+
95+ logCoverage 5 $ "Coverage from case tree for " ++ show n ++ ": " ++ show ctree
96+ logCoverage 2 $ show (length missing) ++ " missing clauses for " ++ show n
97+ logCoverage 3 $ "Missing clauses:\n" ++ showSep "\n"
98+ (map showTmImpls missing)
99+ logCoverage 10 $ "Covered clauses:\n" ++ showSep "\n"
100+ (map showTmImpls covered)
101+ return missing
102+ where
126103 flattenArgs (PApp fc (PApp _ f as) as')
127104 = flattenArgs (PApp fc f (as ++ as'))
128105 flattenArgs t = t
129106
130− -- Return whether the given clause matches none of the input clauses
131− -- (xs)
132− noMatch i xs tm = all (\x -> case matchClause i x tm of
133− Right ms -> False
134− Left miss -> True) xs
135−
136−
137− mergePlaceholders :: PTerm -> PTerm -> PTerm
138− mergePlaceholders x Placeholder = Placeholder
139− mergePlaceholders (PApp fc f args) (PApp fc' f' args')
140− = PApp fc' f' (zipWith mergePArg args args')
141− where mergePArg x y = let xtm = mergePlaceholders (getTm x) (getTm y) in
142− x { getTm = xtm}
143− mergePlaceholders x _ = x
144−
145− mkClauses :: [PArg] -> [[PTerm]] -> [PTerm]
146− mkClauses parg args
147− | all (== [Placeholder]) args = []
148− mkClauses parg args
149− = do args' <- mkArg args
150− let tm = PApp fc (PRef fc [] n) (zipWith upd args' parg)
151− return tm
152− where
153− mkArg :: [[PTerm]] -> [[PTerm]]
154− mkArg [] = return []
155− mkArg (a : as) = do a' <- a
156− as' <- mkArg as
157− return (a':as')
107+getGivenPos :: PTerm -> [Int]
108+getGivenPos (PApp _ _ pargs) = getGiven 0 (map getTm pargs)
109+ where
110+ getGiven i (Placeholder : tms) = getGiven (i + 1) tms
111+ getGiven i (_ : tms) = i : getGiven (i + 1) tms
112+ getGiven i [] = []
113+getGivenPos _ = []
114+
115+-- Return a list of Ints which are in every list
116+mergePos :: [[Int]] -> [Int]
117+mergePos [] = []
118+mergePos [x] = x
119+mergePos (x : xs) = intersect x (mergePos xs)
120+
121+removePlaceholders :: ([Name], Term) -> PTerm -> ([Name], Term, Term)
122+removePlaceholders (ns, tm) ptm = (ns, rp tm ptm, Erased)
123+ where
124+ rp Erased Placeholder = Erased
125+ rp tm Placeholder = Inferred tm
126+ rp tm (PApp _ pf pargs)
127+ | (tf, targs) <- unApply tm
128+ = let tf' = rp tf pf
129+ targs' = zipWith rp targs (map getTm pargs) in
130+ mkApp tf' targs'
131+ rp tm (PPair _ _ _ pl pr)
132+ | (tf, [tyl, tyr, tl, tr]) <- unApply tm
133+ = let tl' = rp tl pl
134+ tr' = rp tr pr in
135+ mkApp tf [Erased, Erased, tl', tr']
136+ rp tm (PDPair _ _ _ pl pt pr)
137+ | (tf, [tyl, tyr, tl, tr]) <- unApply tm
138+ = let tl' = rp tl pl
139+ tr' = rp tr pr in
140+ mkApp tf [Erased, Erased, tl', tr']
141+ rp tm _ = tm
142+
143+mkNewClauses :: Context -> Name -> [Name] -> SC -> ([Term], [Term])
144+mkNewClauses ctxt fn ns sc
145+ = (map (mkPlApp (P Ref fn Erased)) $
146+ mkFromSC True (map (\n -> P Ref n Erased) ns) sc,
147+ map (mkPlApp (P Ref fn Erased)) $
148+ mkFromSC False (map (\n -> P Ref n Erased) ns) sc)
149+ where
150+ mkPlApp f args = mkApp f (map erasePs args)
151+
152+ erasePs ap@(App t f a)
153+ | (f, args) <- unApply ap = mkApp f (map erasePs args)
154+ erasePs (P _ n _) | not (isConName n ctxt) = Erased
155+ erasePs tm = tm
156+
157+ mkFromSC cov args sc = evalState (mkFromSC' cov args sc) []
158+
159+ mkFromSC' :: Bool -> [Term] -> SC -> State [[Term]] [[Term]]
160+ mkFromSC' cov args (STerm _)
161+ = if cov then return [args] else return [] -- leaf of provided case
162+ mkFromSC' cov args (UnmatchedCase _)
163+ = if cov then return [] else return [args] -- leaf of missing case
164+ mkFromSC' cov args ImpossibleCase = return []
165+ mkFromSC' cov args (Case _ x alts)
166+ = do done <- get
167+ if (args `elem` done)
168+ then return []
169+ else do alts' <- mapM (mkFromAlt cov args x) alts
170+ put (args : done)
171+ return (concat alts')
172+ mkFromSC' cov args _ = return [] -- Should never happen
173+
174+ mkFromAlt :: Bool -> [Term] -> Name -> CaseAlt -> State [[Term]] [[Term]]
175+ mkFromAlt cov args x (ConCase c t conargs sc)
176+ = let argrep = mkApp (P (DCon t (length args) False) c Erased)
177+ (map (\n -> P Ref n Erased) conargs)
178+ args' = map (subst x argrep) args in
179+ mkFromSC' cov args' sc
180+ mkFromAlt cov args x (ConstCase c sc)
181+ = let argrep = Constant c
182+ args' = map (subst x argrep) args in
183+ mkFromSC' cov args' sc
184+ mkFromAlt cov args x (DefaultCase sc)
185+ = mkFromSC' cov args sc
186+ mkFromAlt cov _ _ _ = return []
187+
188+-- Modify the generated case tree (the case tree builder doesn't have access
189+-- to the context, so can't do this itself).
190+-- Replaces any missing cases with explicit cases for the missing constructors
191+addMissingCons :: IState -> SC -> SC
192+addMissingCons ist sc = evalState (addMissingConsSt ist sc) 0
193+
194+addMissingConsSt :: IState -> SC -> State Int SC
195+addMissingConsSt ist (Case t n alts) = liftM (Case t n) (addMissingAlts n alts)
196+ where
197+ addMissingAlt :: CaseAlt -> State Int CaseAlt
198+ addMissingAlt (ConCase n i ns sc)
199+ = liftM (ConCase n i ns) (addMissingConsSt ist sc)
200+ addMissingAlt (FnCase n ns sc)
201+ = liftM (FnCase n ns) (addMissingConsSt ist sc)
202+ addMissingAlt (ConstCase c sc)
203+ = liftM (ConstCase c) (addMissingConsSt ist sc)
204+ addMissingAlt (SucCase n sc)
205+ = liftM (SucCase n) (addMissingConsSt ist sc)
206+ addMissingAlt (DefaultCase sc)
207+ = liftM DefaultCase (addMissingConsSt ist sc)
208+
209+ addMissingAlts argn as
210+-- | any hasDefault as = map addMissingAlt as
211+ | cons@(n:_) <- mapMaybe collectCons as,
212+ Just tyn <- getConType n,
213+ Just ti <- lookupCtxtExact tyn (idris_datatypes ist)
214+ -- If we've fallen through on this argument earlier, then the
215+ -- things which were matched in other cases earlier can't be missing
216+ -- cases now
217+ = let missing = con_names ti \\ cons in
218+ do as' <- addCases missing as
219+ mapM addMissingAlt as'
220+ | consts@(n:_) <- mapMaybe collectConsts as
221+ = let missing = nub (map nextConst consts) \\ consts in
222+ mapM addMissingAlt (addCons missing as)
223+ addMissingAlts n as = mapM addMissingAlt as
224+
225+ addCases missing [] = return []
226+ addCases missing (DefaultCase rhs : rest)
227+ = do missing' <- mapM (genMissingAlt rhs) missing
228+ return (mapMaybe id missing' ++ rest)
229+ addCases missing (c : rest)
230+ = liftM (c :) $ addCases missing rest
231+
232+ addCons missing [] = []
233+ addCons missing (DefaultCase rhs : rest)
234+ = map (genMissingConAlt rhs) missing ++ rest
235+ addCons missing (c : rest) = c : addCons missing rest
236+
237+ genMissingAlt rhs n
238+ | Just (TyDecl (DCon tag arity _) ty) <- lookupDefExact n (tt_ctxt ist)
239+ = do name <- get
240+ put (name + arity)
241+ let args = map (name +) [0..arity-1]
242+ return $ Just $ ConCase n tag (map (\i -> sMN i "m") args) rhs
243+ | otherwise = return Nothing
244+
245+ genMissingConAlt rhs n = ConstCase n rhs
246+
247+ collectCons (ConCase n i args sc) = Just n
248+ collectCons _ = Nothing
249+
250+ collectConsts (ConstCase c sc) = Just c
251+ collectConsts _ = Nothing
252+
253+ hasDefault (DefaultCase (UnmatchedCase _)) = False
254+ hasDefault (DefaultCase _) = True
255+ hasDefault _ = False
256+
257+ getConType n = do ty <- lookupTyExact n (tt_ctxt ist)
258+ case unApply (getRetTy (normalise (tt_ctxt ist) [] ty)) of
259+ (P _ tyn _, _) -> Just tyn
260+ _ -> Nothing
261+
262+ -- for every constant in a term (at any level) take next one to make sure
263+ -- that constants which are not explicitly handled are covered
264+ nextConst (I c) = I (c + 1)
265+ nextConst (BI c) = BI (c + 1)
266+ nextConst (Fl c) = Fl (c + 1)
267+ nextConst (B8 c) = B8 (c + 1)
268+ nextConst (B16 c) = B16 (c + 1)
269+ nextConst (B32 c) = B32 (c + 1)
270+ nextConst (B64 c) = B64 (c + 1)
271+ nextConst (Ch c) = Ch (chr $ ord c + 1)
272+ nextConst (Str c) = Str (c ++ "'")
273+ nextConst o = o
274+
275+addMissingConsSt ist sc = return sc
276+
277+trimOverlapping :: SC -> SC
278+trimOverlapping sc = trim [] [] sc
279+ where
280+ trim :: [(Name, (Name, [Name]))] -> -- Variable - constructor+args already matched
281+ [(Name, [Name])] -> -- Variable - constructors which it can't be
282+ SC -> SC
283+ trim mustbes nots (Case t vn alts)
284+ | Just (c, args) <- lookup vn mustbes
285+ = Case t vn (trimAlts mustbes nots vn (substMatch (c, args) alts))
286+ | Just cantbe <- lookup vn nots
287+ = let alts' = filter (notConMatch cantbe) alts in
288+ Case t vn (trimAlts mustbes nots vn alts')
289+ | otherwise = Case t vn (trimAlts mustbes nots vn alts)
290+ trim cs nots sc = sc
291+
292+ trimAlts cs nots vn [] = []
293+ trimAlts cs nots vn (ConCase cn t args sc : rest)
294+ = ConCase cn t args (trim (addMatch vn (cn, args) cs) nots sc) :
295+ trimAlts cs (addCantBe vn cn nots) vn rest
296+ trimAlts cs nots vn (FnCase n ns sc : rest)
297+ = FnCase n ns (trim cs nots sc) : trimAlts cs nots vn rest
298+ trimAlts cs nots vn (ConstCase c sc : rest)
299+ = ConstCase c (trim cs nots sc) : trimAlts cs nots vn rest
300+ trimAlts cs nots vn (SucCase n sc : rest)
301+ = SucCase n (trim cs nots sc) : trimAlts cs nots vn rest
302+ trimAlts cs nots vn (DefaultCase sc : rest)
303+ = DefaultCase (trim cs nots sc) : trimAlts cs nots vn rest
304+
305+ isConMatch c (ConCase cn t args sc) = c == cn
306+ isConMatch _ _ = False
307+
308+ substMatch :: (Name, [Name]) -> [CaseAlt] -> [CaseAlt]
309+ substMatch ca [] = []
310+ substMatch (c,args) (ConCase cn t args' sc : _)
311+ | c == cn = [ConCase c t args (substNames (zip args' args) sc)]
312+ substMatch ca (_:cs) = substMatch ca cs
313+
314+ substNames [] sc = sc
315+ substNames ((n, n') : ns) sc
316+ = substNames ns (substSC n n' sc)
317+
318+ notConMatch cs (ConCase cn t args sc) = cn `notElem` cs
319+ notConMatch cs _ = True
320+
321+ addMatch vn cn cs = (vn, cn) : cs
322+
323+ addCantBe :: Name -> Name -> [(Name, [Name])] -> [(Name, [Name])]
324+ addCantBe vn cn [] = [(vn, [cn])]
325+ addCantBe vn cn ((n, cbs) : nots)
326+ | vn == n = ((n, nub (cn : cbs)) : nots)
327+ | otherwise = ((n, cbs) : addCantBe vn cn nots)
158328
159329-- | Does this error result rule out a case as valid when coverage checking?
160330validCoverageCase :: Context -> Err -> Bool
@@ -179,10 +349,29 @@ recoverableCoverage :: Context -> Err -> Bool
179349recoverableCoverage ctxt (CantUnify r (topx, _) (topy, _) e _ _)
180350 = let topx' = normalise ctxt [] topx
181351 topy' = normalise ctxt [] topy in
182− r || checkRec topx' topy'
352+ evalState (checkRec topx' topy') []
183353 where -- different notion of recoverable than in unification, since we
184354 -- have no metavars -- just looking to see if a constructor is failing
185− -- to unify with a function that may be reduced later
355+ -- to unify with a function that may be reduced later, or if any
356+ -- variables need to have two different constructor forms
357+
358+ -- The state is a mapping of name to what it has failed to unify
359+ -- with
360+ checkRec :: Term -> Term -> State [(Name, Term)] Bool
361+ checkRec (P Bound x _) tm
362+ | (P yt _ _, _) <- unApply tm,
363+ conType yt = do nmap <- get
364+ case lookup x nmap of
365+ Nothing -> do put ((x, tm) : nmap)
366+ return True
367+ Just y' -> checkRec tm y'
368+ checkRec tm (P Bound y _)
369+ | (P xt _ _, _) <- unApply tm,
370+ conType xt = do nmap <- get
371+ case lookup y nmap of
372+ Nothing -> do put ((y, tm) : nmap)
373+ return True
374+ Just x' -> checkRec tm x'
186375 checkRec (App _ f a) p@(P _ _ _) = checkRec f p
187376 checkRec p@(P _ _ _) (App _ f a) = checkRec p f
188377 checkRec fa@(App _ _ _) fa'@(App _ _ _)
@@ -190,175 +379,32 @@ recoverableCoverage ctxt (CantUnify r (topx, _) (topy, _) e _ _)
190379 (f', as') <- unApply fa'
191380 = if (length as /= length as')
192381 then checkRec f f'
193− else checkRec f f' && and (zipWith checkRec as as')
194− checkRec (P xt x _) (P yt y _) = x == y || ntRec xt yt
195− checkRec _ _ = False
196−
382+ else checkRecs (f : as) (f' : as')
383+ where
384+ checkRecs [] [] = return True
385+ checkRecs (a : as) (b : bs) = do aok <- checkRec a b
386+ asok <- checkRecs as bs
387+ return (aok && asok)
388+ checkRec (P xt x _) (P yt y _)
389+ | x == y = return True
390+ | ntRec xt yt = return True
391+ checkRec _ _ = return False
392+
393+ conType (DCon _ _ _) = True
394+ conType (TCon _ _) = True
395+ conType _ = False
396+
397+ -- If either name is a reference or a bound variable, then further
398+ -- development may fix the error, so consider it recoverable.
399+ -- If both names are constructors, and the name is different, then
400+ -- it's not recoverable
197401 ntRec x y | Ref <- x = True
198402 | Ref <- y = True
199− | (Bound, Bound) <- (x, y) = True
403+ | Bound <- x = True
404+ | Bound <- y = True
200405 | otherwise = False -- name is different, unrecoverable
201406recoverableCoverage ctxt (At _ e) = recoverableCoverage ctxt e
202407recoverableCoverage ctxt (Elaborating _ _ _ e) = recoverableCoverage ctxt e
203408recoverableCoverage ctxt (ElaboratingArg _ _ _ e) = recoverableCoverage ctxt e
204409recoverableCoverage _ _ = False
205410
206−genAll :: IState -> (Bool, [PTerm]) -> [PTerm]
207−genAll i (addPH, args)
208− = case filter (/=Placeholder) $ fnub $ mergePHs $ fnub (concatMap otherPats (fnub args)) of
209− [] -> [Placeholder]
210− xs -> ph xs
211− where
212− -- Add a placeholder - this is to account for the case where an argument
213− -- has a dependent type calculated from another argument, to make sure that
214− -- all dependencies are covered. If they are, any generated case will
215− -- match given cases.
216− -- (Also this helps when checking, because if we eliminate the placeholder
217− -- quickly then lots of other cases get ruled out fast)
218− ph ts = if addPH then Placeholder : ts else ts
219−
220− -- Merge patterns with placeholders in other patterns, to ensure we've
221− -- covered all possible generated cases
222− -- e.g. if we have (True, _) (False, _) (_, True) (_, False)
223− -- we should merge these to get (True, True), (False, False)
224− -- (False, True) and (True, False)
225− mergePHs :: [PTerm] -> [PTerm]
226− mergePHs xs = mergePHs' xs xs
227−
228− mergePHs' [] all = []
229− mergePHs' (x : xs) all = mergePH x all ++ mergePHs' xs all
230−
231− mergePH :: PTerm -> [PTerm] -> [PTerm]
232− mergePH tm [] = []
233− mergePH tm (x : xs)
234− | Just merged <- mergePTerm tm x = merged : mergePH tm xs
235− | otherwise = mergePH tm xs
236−
237− mergePTerm :: PTerm -> PTerm -> Maybe PTerm
238− mergePTerm x Placeholder = Just x
239− mergePTerm Placeholder x = Just x
240− mergePTerm tm@(PRef fc1 hl1 n1) (PRef fc2 hl2 n2)
241− | n1 == n2 = Just tm
242− mergePTerm (PPair fc1 hl1 p1 x1 y1) (PPair fc2 hl2 p2 x2 y2)
243− = do x <- mergePTerm x1 x2
244− y <- mergePTerm y1 y2
245− Just (PPair fc1 hl1 p1 x y)
246− mergePTerm (PDPair fc1 hl1 p1 x1 t1 y1) (PDPair fc2 hl2 p2 x2 t2 y2)
247− = do x <- mergePTerm x1 x2
248− y <- mergePTerm y1 y2
249− t <- mergePTerm t1 t2
250− Just (PDPair fc1 hl1 p1 x t y)
251− mergePTerm (PApp fc1 f1 args1) (PApp fc2 f2 args2)
252− = do fm <- mergePTerm f1 f2
253− margs <- mergeArgs args1 args2
254− Just (PApp fc1 fm margs)
255− where
256− mergeArgs [] [] = Just []
257− mergeArgs (a : as) (b : bs)
258− = do ma_in <- mergePTerm (getTm a) (getTm b)
259− let ma = a { getTm = ma_in }
260− mas <- mergeArgs as bs
261− Just (ma : mas)
262− mergeArgs _ _ = Nothing
263− mergePTerm x y | x == y = Just x
264− | otherwise = Nothing
265−
266− -- for every constant in a term (at any level) take next one to make sure
267− -- that constants which are not explicitly handled are covered
268− nextConst (PConstant fc c) = PConstant NoFC (nc' c)
269− nextConst o = o
270−
271− nc' (I c) = I (c + 1)
272− nc' (BI c) = BI (c + 1)
273− nc' (Fl c) = Fl (c + 1)
274− nc' (B8 c) = B8 (c + 1)
275− nc' (B16 c) = B16 (c + 1)
276− nc' (B32 c) = B32 (c + 1)
277− nc' (B64 c) = B64 (c + 1)
278− nc' (Ch c) = Ch (chr $ ord c + 1)
279− nc' (Str c) = Str (c ++ "'")
280− nc' o = o
281−
282− otherPats :: PTerm -> [PTerm]
283− otherPats (PRef fc hl n) = ph $ ops fc n []
284− otherPats (PApp _ (PRef fc hl n) xs) = ph $ ops fc n xs
285− otherPats (PPair fc hls _ l r)
286− = ph $ ops fc pairCon
287− ([pimp (sUN "A") Placeholder True,
288− pimp (sUN "B") Placeholder True] ++
289− [pexp l, pexp r])
290− otherPats (PDPair fc hls p t _ v)
291− = ph $ ops fc sigmaCon
292− ([pimp (sUN "a") Placeholder True,
293− pimp (sUN "P") Placeholder True] ++
294− [pexp t,pexp v])
295− otherPats o@(PConstant _ c) = ph [o, nextConst o]
296− otherPats arg = return Placeholder
297−
298− ops fc n xs
299− | (TyDecl c@(DCon _ arity _) ty : _) <- lookupDef n (tt_ctxt i)
300− = do xs' <- mapM otherPats (map getExpTm xs)
301− let p = resugar (PApp fc (PRef fc [] n) (zipWith upd xs' xs))
302− let tyn = getTy n (tt_ctxt i)
303− case lookupCtxt tyn (idris_datatypes i) of
304− (TI ns _ _ _ _ : _) -> p : map (mkPat fc) (ns \\ [n])
305− _ -> [p]
306− ops fc n arg = return Placeholder
307−
308− getExpTm (PImp _ True _ _ _) = Placeholder -- machine inferred, no point!
309− getExpTm t = getTm t
310−
311− -- put it back to its original form
312− resugar (PApp _ (PRef fc hl n) [_,_,t,v])
313− | n == sigmaCon
314− = PDPair fc [] TypeOrTerm (getTm t) Placeholder (getTm v)
315− resugar (PApp _ (PRef fc hl n) [_,_,l,r])
316− | n == pairCon
317− = PPair fc [] IsTerm (getTm l) (getTm r)
318− resugar t = t
319−
320− dropForce force (x : xs) i | i `elem` force
321− = upd Placeholder x : dropForce force xs (i + 1)
322− dropForce force (x : xs) i = x : dropForce force xs (i + 1)
323− dropForce _ [] _ = []
324−
325−
326− getTy n ctxt = case lookupTy n ctxt of
327− (t : _) -> case unApply (getRetTy t) of
328− (P _ tyn _, _) -> tyn
329− x -> error $ "Can't happen getTy 1 " ++ show (n, x)
330− _ -> error "Can't happen getTy 2"
331−
332− mkPat fc x = case lookupCtxt x (idris_implicits i) of
333− (pargs : _)
334− -> PApp fc (PRef fc [] x) (map (upd Placeholder) pargs)
335− _ -> error "Can't happen - genAll"
336−
337− fnub :: [PTerm] -> [PTerm]
338− fnub xs = fnub' [] xs
339−
340− fnub' :: [PTerm] -> [PTerm] -> [PTerm]
341− fnub' acc (x : xs) | x `qelem` acc = fnub' acc (filter (not.(quickEq x)) xs)
342− | otherwise = fnub' (x : acc) xs
343− fnub' acc [] = acc
344−
345− -- quick check for constructor equality
346− quickEq :: PTerm -> PTerm -> Bool
347− quickEq (PConstant _ n) (PConstant _ n') = n == n'
348− quickEq (PRef _ _ n) (PRef _ _ n') = n == n'
349− quickEq (PPair _ _ _ l r) (PPair _ _ _ l' r') = quickEq l l' && quickEq r r'
350− quickEq (PApp _ t as) (PApp _ t' as')
351− | length as == length as'
352− = quickEq t t' && and (zipWith quickEq (map getTm as) (map getTm as'))
353− quickEq Placeholder Placeholder = True
354− quickEq x y = False
355−
356− qelem :: PTerm -> [PTerm] -> Bool
357− qelem x [] = False
358− qelem x (y : ys) | x `quickEq` y = True
359− | otherwise = qelem x ys
360−
361−
362−upd :: t -> PArg' t -> PArg' t
363−upd p' p = p { getTm = p' }
364−
src/Idris/DataOpts.hs+1−1
@@ -103,7 +103,7 @@ applyDataOptRT n tag arity uniq args
103103 satArgs n = map (\i -> sMN i "sat") [1..n]
104104
105105 bind [] tm = tm
106− bind (n:ns) tm = Bind n (Lam Erased) (pToV n (bind ns tm))
106+ bind (n:ns) tm = Bind n (Lam RigW Erased) (pToV n (bind ns tm))
107107
108108 -- Nat special cases
109109 -- TODO: Would be nice if this was configurable in idris source!
src/Idris/Delaborate.hs+21−20
@@ -135,29 +135,29 @@ delabTy' ist imps tm fullname mvs docases = de [] imps tm
135135 = case lookup n (idris_metavars ist) of
136136 Just (Just _, mi, _, _, _) -> mkMVApp n []
137137 _ -> PRef un [] n
138− de env _ (Bind n (Lam ty) sc)
138+ de env _ (Bind n (Lam _ ty) sc)
139139 = PLam un n NoFC (de env [] ty) (de ((n,n):env) [] sc)
140− de env (_ : is) (Bind n (Pi (Just impl) ty _) sc)
140+ de env (_ : is) (Bind n (Pi rig (Just impl) ty _) sc)
141141 | toplevel_imp impl -- information in 'imps' repeated
142− = PPi (Imp [] Dynamic False (Just impl) False) n NoFC (de env [] ty) (de ((n,n):env) is sc)
143− de env is (Bind n (Pi (Just impl) ty _) sc)
142+ = PPi (Imp [] Dynamic False (Just impl) False rig) n NoFC (de env [] ty) (de ((n,n):env) is sc)
143+ de env is (Bind n (Pi rig (Just impl) ty _) sc)
144144 | tcimplementation impl
145145 = PPi constraint n NoFC (de env [] ty) (de ((n,n):env) is sc)
146146 | otherwise
147− = PPi (Imp [] Dynamic False (Just impl) False) n NoFC (de env [] ty) (de ((n,n):env) is sc)
148− de env ((PImp { argopts = opts }):is) (Bind n (Pi _ ty _) sc)
149− = PPi (Imp opts Dynamic False Nothing False) n NoFC (de env [] ty) (de ((n,n):env) is sc)
150− de env (PConstraint _ _ _ _:is) (Bind n (Pi _ ty _) sc)
151− = PPi constraint n NoFC (de env [] ty) (de ((n,n):env) is sc)
152− de env (PTacImplicit _ _ _ tac _:is) (Bind n (Pi _ ty _) sc)
153− = PPi (tacimpl tac) n NoFC (de env [] ty) (de ((n,n):env) is sc)
154− de env (plic:is) (Bind n (Pi _ ty _) sc)
155− = PPi (Exp (argopts plic) Dynamic False)
147+ = PPi (Imp [] Dynamic False (Just impl) False rig) n NoFC (de env [] ty) (de ((n,n):env) is sc)
148+ de env ((PImp { argopts = opts }):is) (Bind n (Pi rig _ ty _) sc)
149+ = PPi (Imp opts Dynamic False Nothing False rig) n NoFC (de env [] ty) (de ((n,n):env) is sc)
150+ de env (PConstraint _ _ _ _:is) (Bind n (Pi rig _ ty _) sc)
151+ = PPi (constraint { pcount = rig}) n NoFC (de env [] ty) (de ((n,n):env) is sc)
152+ de env (PTacImplicit _ _ _ tac _:is) (Bind n (Pi rig _ ty _) sc)
153+ = PPi ((tacimpl tac) { pcount = rig }) n NoFC (de env [] ty) (de ((n,n):env) is sc)
154+ de env (plic:is) (Bind n (Pi rig _ ty _) sc)
155+ = PPi (Exp (argopts plic) Dynamic False rig)
156156 n NoFC
157157 (de env [] ty)
158158 (de ((n,n):env) is sc)
159− de env [] (Bind n (Pi _ ty _) sc)
160− = PPi expl n NoFC (de env [] ty) (de ((n,n):env) [] sc)
159+ de env [] (Bind n (Pi rig _ ty _) sc)
160+ = PPi (expl { pcount = rig }) n NoFC (de env [] ty) (de ((n,n):env) [] sc)
161161
162162 de env imps (Bind n (Let ty val) sc)
163163 | docases
@@ -173,6 +173,7 @@ delabTy' ist imps tm fullname mvs docases = de [] imps tm
173173 de env _ (Proj _ _) = error "Delaboration got run-time-only Proj!"
174174 de env _ Erased = Placeholder
175175 de env _ Impossible = Placeholder
176+ de env _ (Inferred t) = Placeholder
176177 de env _ (TType i) = PType un
177178 de env _ (UType u) = PUniverse un u
178179
@@ -187,7 +188,7 @@ delabTy' ist imps tm fullname mvs docases = de [] imps tm
187188 deFn env (P _ n _) [l,r]
188189 | n == pairTy = PPair un [] IsType (de env [] l) (de env [] r)
189190 | n == sUN "lazy" = de env [] r -- TODO: Fix string based matching
190− deFn env (P _ n _) [ty, Bind x (Lam _) r]
191+ deFn env (P _ n _) [ty, Bind x (Lam _ _) r]
191192 | n == sigmaTy
192193 = PDPair un [] IsType (PRef un [] x) (de env [] ty)
193194 (de ((x,x):env) [] (instantiate (P Bound x ty) r))
@@ -338,9 +339,9 @@ pprintErr' i (CantConvert x_in y_in env) =
338339 indented (annTm y_ns (pprintTerm' i (map (\ (n, b) -> (n, False)) env)
339340 y)) <>
340341 if (opt_errContext (idris_options i)) then line <> text "Conversion failure" <$> showSc i env else empty
341− where flagUnique (Bind n (Pi i t k@(UType u)) sc)
342+ where flagUnique (Bind n (Pi rig i t k@(UType u)) sc)
342343 = App Complete (P Ref (sUN (show u)) Erased)
343− (Bind n (Pi i (flagUnique t) k) (flagUnique sc))
344+ (Bind n (Pi rig i (flagUnique t) k) (flagUnique sc))
344345 flagUnique (App s f a) = App s (flagUnique f) (flagUnique a)
345346 flagUnique (Bind n b sc) = Bind n (fmap flagUnique b) (flagUnique sc)
346347 flagUnique t = t
@@ -526,13 +527,13 @@ pprintErr' i (ElabScriptDebug msg tm holes) =
526527 indented (vsep (map ppHole holes)) <> line <> line <>
527528 text "Term: " <> indented (pprintTT [] tm)
528529
529− where ppHole :: (Name, Type, Env) -> Doc OutputAnnotation
530+ where ppHole :: (Name, Type, [(Name, Binder Type)]) -> Doc OutputAnnotation
530531 ppHole (hn, goal, env) =
531532 ppAssumptions [] (reverse env) <>
532533 text "----------------------------------" <> line <>
533534 bindingOf hn False <+> text ":" <+>
534535 pprintTT (map fst (reverse env)) goal <> line
535− ppAssumptions :: [Name] -> Env -> Doc OutputAnnotation
536+ ppAssumptions :: [Name] -> [(Name, Binder Type)] -> Doc OutputAnnotation
536537 ppAssumptions ns [] = empty
537538 ppAssumptions ns ((n, b) : rest) =
538539 bindingOf n False <+>
src/Idris/Docs.hs+3−3
@@ -220,7 +220,7 @@ pprintDocs ist (InterfaceDoc n doc meths params constraints implementations sub_
220220 dumpImplementation :: PTerm -> Doc OutputAnnotation
221221 dumpImplementation = pprintPTerm ppo params' [] infixes
222222
223− prettifySubInterfaces (PPi (Constraint _ _) _ _ tm _) = prettifySubInterfaces tm
223+ prettifySubInterfaces (PPi (Constraint _ _ _) _ _ tm _) = prettifySubInterfaces tm
224224 prettifySubInterfaces (PPi plcity nm fc t1 t2) = PPi plcity (safeHead nm pNames) NoFC (prettifySubInterfaces t1) (prettifySubInterfaces t2)
225225 prettifySubInterfaces (PApp fc ref args) = PApp fc ref $ updateArgs pNames args
226226 prettifySubInterfaces tm = tm
@@ -235,7 +235,7 @@ pprintDocs ist (InterfaceDoc n doc meths params constraints implementations sub_
235235 updateRef nm (PRef fc _ _) = PRef fc [] nm
236236 updateRef _ pt = pt
237237
238− isSubInterface (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args')) = nm == n && map getTm args == map getTm args'
238+ isSubInterface (PPi (Constraint _ _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args')) = nm == n && map getTm args == map getTm args'
239239 isSubInterface (PPi _ _ _ _ pt) = isSubInterface pt
240240 isSubInterface _ = False
241241
@@ -356,7 +356,7 @@ docInterface n ci
356356 getDImpl (PImplementation _ _ _ _ _ _ _ _ _ _ _ _ t _ _) = Just t
357357 getDImpl _ = Nothing
358358
359− isSubInterface (PPi (Constraint _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args'))
359+ isSubInterface (PPi (Constraint _ _ _) _ _ (PApp _ _ args) (PApp _ (PRef _ _ nm) args'))
360360 = nm == n && map getTm args == map getTm args'
361361 isSubInterface (PPi _ _ _ _ pt)
362362 = isSubInterface pt
src/Idris/Elab/Clause.hs+70−34
@@ -14,6 +14,7 @@ import Idris.Core.CaseTree
1414import Idris.Core.Elaborate hiding (Tactic(..))
1515import Idris.Core.Evaluate
1616import Idris.Core.Execute
17+import Idris.Core.WHNF
1718import Idris.Core.TT
1819import Idris.Core.Typecheck
1920import Idris.Coverage
@@ -75,6 +76,8 @@ elabClauses info' fc opts n_in cs =
7576 -- Check n actually exists, with no definition yet
7677 let tys = lookupTy n ctxt
7778 let reflect = Reflection `elem` opts
79+ when (reflect && FCReflection `notElem` idris_language_extensions ist) $
80+ ierror $ At fc (Msg "You must turn on the FirstClassReflection extension to use %reflection")
7881 checkUndefined n ctxt
7982 unless (length tys > 1) $ do
8083 fty <- case tys of
@@ -186,12 +189,14 @@ elabClauses info' fc opts n_in cs =
186189 pmissing <-
187190 if cov && not (hasDefault pats_raw)
188191 then do -- Generate clauses from the given possible cases
189− missing <- genClauses fc n (map getLHS pdef_cov) cs_full
192+ missing <- genClauses fc n
193+ (map (\ (ns,tm,_) -> (ns, tm)) pdef)
194+ cs_full
190195 -- missing <- genMissing n scargs sc
191196 missing' <- checkPossibles info fc True n missing
192197 -- Filter out the ones which match one of the
193198 -- given cases (including impossible ones)
194− let clhs = map getLHS pdef_cov
199+ let clhs = map getLHS pdef
195200 logElab 2 $ "Must be unreachable (" ++ show (length missing') ++ "):\n" ++
196201 showSep "\n" (map showTmImpls missing') ++
197202 "\nAgainst: " ++
@@ -201,7 +206,7 @@ elabClauses info' fc opts n_in cs =
201206 -- unification may force a variable to take a
202207 -- particular form, rather than force a case
203208 -- to be impossible.
204− return (filter (noMatch ist clhs) missing')
209+ return missing' -- (filter (noMatch ist clhs) missing')
205210 else return []
206211 let pcover = null pmissing
207212
@@ -282,6 +287,10 @@ elabClauses info' fc opts n_in cs =
282287 Just Public -> mapM_ (checkVisibility fc n Public Public) calls
283288 _ -> return ()
284289 addCalls n calls
290+ let rig = if linearArg (whnfArgs ctxt [] ty)
291+ then Rig1
292+ else RigW
293+ updateContext (setRigCount n (minRig ctxt rig calls))
285294 addIBC (IBCCG n)
286295 _ -> return ()
287296 return ()
@@ -325,12 +334,12 @@ elabClauses info' fc opts n_in cs =
325334 debind (Left x) = let (vs, x') = depat [] x in
326335 (vs, x', Impossible)
327336
328− depat acc (Bind n (PVar t) sc) = depat ((n, t) : acc) (instantiate (P Bound n t) sc)
337+ depat acc (Bind n (PVar rig t) sc) = depat ((n, t) : acc) (instantiate (P Bound n t) sc)
329338 depat acc x = (acc, x)
330339
331340
332− getPVs (Bind x (PVar _) tm) = let (vs, tm') = getPVs tm
333− in (x:vs, tm')
341+ getPVs (Bind x (PVar rig _) tm) = let (vs, tm') = getPVs tm
342+ in (x:vs, tm')
334343 getPVs tm = ([], tm)
335344
336345 isPatVar vs (P Bound n _) = n `elem` vs
@@ -374,6 +383,12 @@ elabClauses info' fc opts n_in cs =
374383 Just t -> return t
375384 Nothing -> ierror (At fc (Msg "No specialisation achieved"))
376385
386+ minRig :: Context -> RigCount -> [Name] -> RigCount
387+ minRig c minr [] = minr
388+ minRig c minr (r : rs) = case lookupRigCountExact r c of
389+ Nothing -> minRig c minr rs
390+ Just rc -> minRig c (min minr rc) rs
391+
377392forceWith :: Ctxt OptInfo -> Term -> Term
378393forceWith opts lhs = -- trace (show lhs ++ "\n==>\n" ++ show (force lhs) ++ "\n----") $
379394 force lhs
@@ -524,8 +539,8 @@ elabPE info fc caller r =
524539 [] -> False
525540 _ -> True
526541 concreteTm ist (Constant _) = True
527− concreteTm ist (Bind n (Lam _) sc) = True
528− concreteTm ist (Bind n (Pi _ _ _) sc) = True
542+ concreteTm ist (Bind n (Lam _ _) sc) = True
543+ concreteTm ist (Bind n (Pi _ _ _ _) sc) = True
529544 concreteTm ist (Bind n (Let _ _) sc) = concreteTm ist sc
530545 concreteTm ist _ = False
531546
@@ -562,7 +577,10 @@ elabPE info fc caller r =
562577 qhash hash (x:xs) = qhash (hash * 33 + fromIntegral(fromEnum x)) xs
563578
564579-- | Checks if the clause is a possible left hand side.
565−checkPossible :: ElabInfo -> FC -> Bool -> Name -> PTerm -> Idris Bool
580+-- NOTE: A lot of this is repeated for reflected definitions in Idris.Elab.Term
581+-- One day, these should be merged, but until then remember that if you edit
582+-- this you might need to edit the other version...
583+checkPossible :: ElabInfo -> FC -> Bool -> Name -> PTerm -> Idris (Maybe PTerm)
566584checkPossible info fc tcgen fname lhs_in
567585 = do ctxt <- getContext
568586 i <- getIState
@@ -570,7 +588,7 @@ checkPossible info fc tcgen fname lhs_in
570588 logElab 10 $ "Trying missing case: " ++ showTmImpls lhs
571589 -- if the LHS type checks, it is possible
572590 case elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) (sMN 0 "patLHS") infP initEState
573− (erun fc (buildTC i info ELHS [] fname
591+ (erun fc (buildTC i info EImpossible [] fname
574592 (allNamesIn lhs_in)
575593 (infTerm lhs))) of
576594 OK (ElabResult lhs' _ _ ctxt' newDecls highlights newGName, _) ->
@@ -582,18 +600,29 @@ checkPossible info fc tcgen fname lhs_in
582600 let emptyPat = hasEmptyPat ctxt (idris_datatypes i) lhs_tm
583601 if emptyPat then
584602 do logElab 10 $ "Empty type in pattern "
585− return False
603+ return Nothing
586604 else
587605 case recheck (constraintNS info) ctxt' [] (forget lhs_tm) lhs_tm of
588− OK _ -> do logElab 10 $ "Valid"
589− return True
606+ OK (tm, _, _) ->
607+ do logElab 10 $ "Valid " ++ show tm ++ "\n"
608+ ++ " from " ++ show lhs
609+ return (Just (delab' i tm True True))
590610 err -> do logElab 10 $ "Conversion failure"
591− return False
611+ return Nothing
592612 -- if it's a recoverable error, the case may become possible
593− Error err -> do logLvl 10 $ "Impossible case " ++ show err
594− if tcgen then return (recoverableCoverage ctxt err)
595− else return (validCoverageCase ctxt err ||
613+ Error err -> do logLvl 10 $ "Impossible case " ++ (pshow i err)
614+ -- tcgen means that it was generated by genClauses,
615+ -- so only looking for an error. Otherwise, it
616+ -- needs to be the right kind of error (a type mismatch
617+ -- in the same family).
618+ if tcgen then returnTm i err (recoverableCoverage ctxt err)
619+ else returnTm i err (validCoverageCase ctxt err ||
596620 recoverableCoverage ctxt err)
621+ where returnTm i err True = do logLvl 10 $ "Possibly resolvable error on " ++
622+ pshow i (fmap (normalise (tt_ctxt i) []) err)
623+ ++ " on " ++ showTmImpls lhs_in
624+ return $ Just lhs_in
625+ returnTm i err False = return $ Nothing
597626
598627-- Filter out the terms which are not well type left hand sides. Whenever we
599628-- eliminate one, also eliminate later ones which match it without checking,
@@ -608,7 +637,9 @@ checkPossibles info fc tcgen fname (lhs : rest)
608637 -- check, just remove from the next batch
609638 let rest' = filter (\x -> not (qmatch x lhs)) (take 200 rest) ++ drop 200 rest
610639 restpos <- checkPossibles info fc tcgen fname rest'
611− if not ok then return restpos else return (lhs : restpos)
640+ case ok of
641+ Nothing -> return restpos
642+ Just lhstm -> return (lhstm : restpos)
612643 where
613644 qmatch _ Placeholder = True
614645 qmatch (PApp _ f args) (PApp _ f' args')
@@ -624,14 +655,14 @@ checkPossibles _ _ _ _ [] = return []
624655
625656findUnique :: Context -> Env -> Term -> [Name]
626657findUnique ctxt env (Bind n b sc)
627− = let rawTy = forgetEnv (map fst env) (binderTy b)
658+ = let rawTy = forgetEnv (map fstEnv env) (binderTy b)
628659 uniq = case check ctxt env rawTy of
629660 OK (_, UType UniqueType) -> True
630661 OK (_, UType NullType) -> True
631662 OK (_, UType AllTypes) -> True
632663 _ -> False in
633− if uniq then n : findUnique ctxt ((n, b) : env) sc
634− else findUnique ctxt ((n, b) : env) sc
664+ if uniq then n : findUnique ctxt ((n, RigW, b) : env) sc
665+ else findUnique ctxt ((n, RigW, b) : env) sc
635666findUnique _ _ _ = []
636667
637668getUnfolds (UnfoldIface n ns : _) = Just (n, ns)
@@ -671,12 +702,12 @@ elabClause info opts (_, PClause fc fname lhs_in [] PImpossible [])
671702 let lhs = addImpl [] i lhs_in
672703 b <- checkPossible info fc tcgen fname lhs_in
673704 case b of
674− True -> tclift $ tfail (At fc
675− (Msg $ show lhs_in ++ " is a valid case"))
676− False -> do ptm <- mkPatTm lhs_in
677− logElab 5 $ "Elaborated impossible case " ++ showTmImpls lhs ++
678− "\n" ++ show ptm
679− return (Left ptm, lhs)
705+ Just _ -> tclift $ tfail (At fc
706+ (Msg $ show lhs_in ++ " is a valid case"))
707+ Nothing -> do ptm <- mkPatTm lhs_in
708+ logElab 5 $ "Elaborated impossible case " ++ showTmImpls lhs ++
709+ "\n" ++ show ptm
710+ return (Left ptm, lhs)
680711elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as whereblock)
681712 = do let tcgen = Dictionary `elem` opts
682713 push_estack fname False
@@ -828,7 +859,7 @@ elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as wherebloc
828859
829860 when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
830861
831− logElab 5 "DONE CHECK"
862+ logElab 3 "DONE CHECK"
832863 logElab 3 $ "---> " ++ show rhsElab
833864 ctxt <- getContext
834865
@@ -902,7 +933,7 @@ elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as wherebloc
902933 rev <- case ret_fam of
903934 P _ rfamn _ ->
904935 case lookupCtxt rfamn (idris_datatypes i) of
905− [TI _ _ dopts _ _] ->
936+ [TI _ _ dopts _ _ _] ->
906937 return (DataErrRev `elem` dopts &&
907938 size clhs <= size crhs)
908939 _ -> return False
@@ -1007,7 +1038,12 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
10071038
10081039 logElab 5 ("Checked " ++ show clhs)
10091040 let bargs = getPBtys (explicitNames (normalise ctxt [] lhs_tm))
1010− let wval = rhs_trans info $ addImplBound i (map fst bargs) wval_in
1041+ wval <- case wval_in of
1042+ Placeholder -> ierror $ At fc $
1043+ Msg "No expression for the with block to inspect.\nYou need to replace the _ with an expression."
1044+ _ -> return $
1045+ rhs_trans info $
1046+ addImplBound i (map fst bargs) wval_in
10111047 logElab 5 ("Checking " ++ showTmImpls wval)
10121048 -- Elaborate wval in this context
10131049 ((wvalElab, defer, is, ctxt', newDecls, highlights, newGName), _) <-
@@ -1081,7 +1117,7 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
10811117 let wargname = sMN windex "warg"
10821118
10831119 logElab 5 ("Abstract over " ++ show wargval ++ " in " ++ show wargtype)
1084− let wtype = bindTyArgs (flip (Pi Nothing) (TType (UVar [] 0))) (bargs_pre ++
1120+ let wtype = bindTyArgs (flip (Pi RigW Nothing) (TType (UVar [] 0))) (bargs_pre ++
10851121 (wargname, wargtype) :
10861122 map (abstract wargname wargval wargtype) bargs_post ++
10871123 case mpn of
@@ -1175,7 +1211,7 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
11751211 (crhs, crhsty) <- recheckC (constraintNS info) fc id [] rhs'
11761212 return (Right (clhs, crhs), lhs)
11771213 where
1178− getImps (Bind n (Pi _ _ _) t) = pexp Placeholder : getImps t
1214+ getImps (Bind n (Pi _ _ _ _) t) = pexp Placeholder : getImps t
11791215 getImps _ = []
11801216
11811217 mkAuxC pn wname lhs ns ns' (PClauses fc o n cs)
@@ -1274,13 +1310,13 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
12741310 -- This is something of a hack, because matching on the top level
12751311 -- application won't find this information for us
12761312 addResolvesArgs :: FC -> Term -> [PArg] -> [PArg]
1277− addResolvesArgs fc (Bind n (Pi _ ty _) sc) (a : args)
1313+ addResolvesArgs fc (Bind n (Pi _ _ ty _) sc) (a : args)
12781314 | (P _ cn _, _) <- unApply ty,
12791315 getTm a == Placeholder
12801316 = case lookupCtxtExact cn (idris_interfaces ist) of
12811317 Just _ -> a { getTm = PResolveTC fc } : addResolvesArgs fc sc args
12821318 Nothing -> a : addResolvesArgs fc sc args
1283− addResolvesArgs fc (Bind n (Pi _ ty _) sc) (a : args)
1319+ addResolvesArgs fc (Bind n (Pi _ _ ty _) sc) (a : args)
12841320 = a : addResolvesArgs fc sc args
12851321 addResolvesArgs fc _ args = args
12861322
src/Idris/Elab/Data.hs+8−4
@@ -104,7 +104,8 @@ elabData info syn doc argDocs fc opts (PDatadecl n nfc t_in dcons)
104104 -- TI contains information about mutually declared types - this will
105105 -- be updated when the mutual block is complete
106106 putIState (i { idris_datatypes =
107− addDef n (TI (map fst cons) codata opts params [n])
107+ addDef n (TI (map fst cons) codata opts params [n]
108+ (any linearArg (map snd cons)))
108109 (idris_datatypes i) })
109110 addIBC (IBCDef n)
110111 addIBC (IBCData n)
@@ -119,6 +120,9 @@ elabData info syn doc argDocs fc opts (PDatadecl n nfc t_in dcons)
119120 -- TMP HACK! Make this a data option
120121 updateContext (addDatatype (Data n ttag cty unique cons))
121122 updateContext (setMetaInformation n metainf)
123+ when (any linearArg (map snd cons)) $
124+ updateContext (setRigCount n Rig1)
125+
122126 mapM_ totcheck (zip (repeat fc) (map fst cons))
123127-- mapM_ (checkPositive n) cons
124128
@@ -267,7 +271,7 @@ forceArgs ctxt ty = forceFrom 0 ty
267271 -- then when we look at the return type, if we see MN pos name
268272 -- constructor guarded, then 'pos' is a forceable position
269273 forceFrom :: Int -> Type -> [Int]
270− forceFrom i (Bind n (Pi _ _ _) sc)
274+ forceFrom i (Bind n (Pi _ _ _ _) sc)
271275 = forceFrom (i + 1) (substV (P Ref (sMN i "FF") Erased) sc)
272276 forceFrom i sc
273277 -- Go under the top level type application
@@ -310,7 +314,7 @@ addParamConstraints fc ps cty cons
310314 where
311315 getParamNames (n, ty) = (ty, getPs ty)
312316
313− getPs (Bind n (Pi _ _ _) sc)
317+ getPs (Bind n (Pi _ _ _ _) sc)
314318 = getPs (substV (P Ref n Erased) sc)
315319 getPs t | (f, args) <- unApply t
316320 = paramArgs 0 args
@@ -321,7 +325,7 @@ addParamConstraints fc ps cty cons
321325
322326 addConConstraint ps cvar (ty, pnames) = constraintTy ty
323327 where
324− constraintTy (Bind n (Pi _ ty _) sc)
328+ constraintTy (Bind n (Pi _ _ ty _) sc)
325329 = case getRetTy ty of
326330 TType avar -> do tit <- typeInType
327331 when (not tit) $ do
src/Idris/Elab/Implementation.hs+6−6
@@ -310,16 +310,16 @@ elabImplementation info syn doc argDocs what fc cs parents acc opts n nfc ps pex
310310 where
311311 needed is p = pname p `elem` map pname is
312312
313− lamBind i (PPi (Constraint _ _) _ _ _ sc) sc'
313+ lamBind i (PPi (Constraint _ _ _) _ _ _ sc) sc'
314314 = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc')
315315 lamBind i (PPi _ n _ ty sc) sc'
316316 = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc')
317317 lamBind i _ sc = sc
318− methArgs i (PPi (Imp _ _ _ _ _) n _ ty sc)
318+ methArgs i (PPi (Imp _ _ _ _ _ _) n _ ty sc)
319319 = PImp 0 True [] n (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc
320− methArgs i (PPi (Exp _ _ _) n _ ty sc)
320+ methArgs i (PPi (Exp _ _ _ _) n _ ty sc)
321321 = PExp 0 [] (sMN 0 "marg") (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc
322− methArgs i (PPi (Constraint _ _) n _ ty sc)
322+ methArgs i (PPi (Constraint _ _ _) n _ ty sc)
323323 = PConstraint 0 [] (sMN 0 "marg") (PResolveTC fc) : methArgs (i+1) sc
324324 methArgs i _ = []
325325
@@ -354,7 +354,7 @@ elabImplementation info syn doc argDocs what fc cs parents acc opts n nfc ps pex
354354 extrabind [] x = x
355355
356356 coninsert :: [(Name, PTerm)] -> [(Name, PTerm)] -> PTerm -> PTerm
357− coninsert cs ex (PPi p@(Imp _ _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs ex sc)
357+ coninsert cs ex (PPi p@(Imp _ _ _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs ex sc)
358358 coninsert cs ex sc = conbind cs (extrabind ex sc)
359359
360360 -- Reorder declarations to be in the same order as defined in the
@@ -516,6 +516,6 @@ checkInjectiveArgs fc n ds (Just ty)
516516 isInj i (Bind n b sc) = isInj i sc
517517 isInj _ _ = True
518518
519− instantiateRetTy (Bind n (Pi _ _ _) sc)
519+ instantiateRetTy (Bind n (Pi _ _ _ _) sc)
520520 = substV (P Bound n Erased) (instantiateRetTy sc)
521521 instantiateRetTy t = t
src/Idris/Elab/Interface.hs+8−8
@@ -210,7 +210,7 @@ elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd
210210 logElab 2 $ "Method " ++ show n ++ " : " ++ showTmImpls t'
211211 return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')),
212212 (n, (False, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps)
213− (\ l s p -> Imp l s p Nothing True) t'))),
213+ (\ l s p r -> Imp l s p Nothing True r) t'))),
214214 (n, (nfc, syn, o, t) ) )
215215 tdecl impps allmeths (PData doc _ syn _ _ (PLaterdecl n nfc t))
216216 = do let o = []
@@ -218,7 +218,7 @@ elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd
218218 logElab 2 $ "Data method " ++ show n ++ " : " ++ showTmImpls t'
219219 return ( (n, (toExp (map (\(pn, _, _) -> pn) ps) Exp t')),
220220 (n, (True, nfc, doc, o, (toExp (map (\(pn, _, _) -> pn) ps)
221− (\ l s p -> Imp l s p Nothing True) t'))),
221+ (\ l s p r -> Imp l s p Nothing True r) t'))),
222222 (n, (nfc, syn, o, t) ) )
223223 tdecl impps allmeths (PData doc _ syn _ _ _)
224224 = ierror $ At fc (Msg "Data definitions not allowed in an interface declaration")
@@ -294,9 +294,9 @@ elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd
294294 return [PTy doc [] syn fc o m mfc ty',
295295 PClauses fc [Inlinable] m [PClause fc m lhs [] rhs []]]
296296
297− getMArgs (PPi (Imp _ _ _ _ _) n _ ty sc) = IA n : getMArgs sc
298− getMArgs (PPi (Exp _ _ _) n _ ty sc) = EA n : getMArgs sc
299− getMArgs (PPi (Constraint _ _) n _ ty sc) = CA : getMArgs sc
297+ getMArgs (PPi (Imp _ _ _ _ _ _) n _ ty sc) = IA n : getMArgs sc
298+ getMArgs (PPi (Exp _ _ _ _) n _ ty sc) = EA n : getMArgs sc
299+ getMArgs (PPi (Constraint _ _ _) n _ ty sc) = CA : getMArgs sc
300300 getMArgs _ = []
301301
302302 getMeth :: [Name] -> [Name] -> Name -> PTerm
@@ -337,9 +337,9 @@ elabInterface info syn_in doc fc constraints tn tnfc ps pDocs fds ds mcn cd
337337 addC _ _ tm = tm
338338
339339 -- make arguments explicit and don't bind interface parameters
340− toExp ns e (PPi (Imp l s p _ _) n fc ty sc)
340+ toExp ns e (PPi (Imp l s p _ _ r) n fc ty sc)
341341 | n `elem` ns = toExp ns e sc
342− | otherwise = PPi (e l s p) n fc ty (toExp ns e sc)
342+ | otherwise = PPi (e l s p r) n fc ty (toExp ns e sc)
343343 toExp ns e (PPi p n fc ty sc) = PPi p n fc ty (toExp ns e sc)
344344 toExp ns e sc = sc
345345
@@ -376,7 +376,7 @@ findDets n ns =
376376 Just ty -> getDetPos 0 ns ty
377377 Nothing -> []
378378 where
379− getDetPos i ns (Bind n (Pi _ _ _) sc)
379+ getDetPos i ns (Bind n (Pi _ _ _ _) sc)
380380 | n `elem` ns = i : getDetPos (i + 1) ns sc
381381 | otherwise = getDetPos (i + 1) ns sc
382382 getDetPos _ _ _ = []
src/Idris/Elab/Record.hs+4−4
@@ -460,10 +460,10 @@ in_name n = n
460460
461461-- | Creates a PArg with a given plicity, name, and term.
462462asArg :: Plicity -> Name -> PTerm -> PArg
463−asArg (Imp os _ _ _ _) n t = PImp 0 False os n t
464−asArg (Exp os _ _) n t = PExp 0 os n t
465−asArg (Constraint os _) n t = PConstraint 0 os n t
466−asArg (TacImp os _ s) n t = PTacImplicit 0 os n s t
463+asArg (Imp os _ _ _ _ _) n t = PImp 0 False os n t
464+asArg (Exp os _ _ _) n t = PExp 0 os n t
465+asArg (Constraint os _ _) n t = PConstraint 0 os n t
466+asArg (TacImp os _ s _) n t = PTacImplicit 0 os n s t
467467
468468-- | Machine name "rec".
469469recName :: Name
src/Idris/Elab/Rewrite.hs+7−7
@@ -77,7 +77,7 @@ elabRewrite elab ist fc substfn_in rule sc_in newg
7777 let pred = PLam fc rname fc Placeholder
7878 (delab ist pred_tt)
7979 let rewrite = stripImpls $
80− addImplBound ist (map fst env) (PApp fc (PRef fc [] substfn)
80+ addImplBound ist (map fstEnv env) (PApp fc (PRef fc [] substfn)
8181 [pexp pred, pexp rule, pexp sc])
8282-- trace ("LHS: " ++ show l ++ "\n" ++
8383-- "RHS: " ++ show r ++ "\n" ++
@@ -156,10 +156,10 @@ data ParamInfo = Index
156156
157157getParamInfo :: Type -> [PArg] -> Int -> [Int] -> [ParamInfo]
158158-- Skip the top level implicits, we just need the explicit ones
159−getParamInfo (Bind n (Pi _ _ _) sc) (PExp{} : is) i ps
159+getParamInfo (Bind n (Pi _ _ _ _) sc) (PExp{} : is) i ps
160160 | i `elem` ps = Param : getParamInfo sc is (i + 1) ps
161161 | otherwise = Index : getParamInfo sc is (i + 1) ps
162−getParamInfo (Bind n (Pi _ _ _) sc) (_ : is) i ps
162+getParamInfo (Bind n (Pi _ _ _ _) sc) (_ : is) i ps
163163 | i `elem` ps = ImplicitParam : getParamInfo sc is (i + 1) ps
164164 | otherwise = ImplicitIndex : getParamInfo sc is (i + 1) ps
165165getParamInfo _ _ _ _ = []
@@ -249,13 +249,13 @@ mkLemma info lemma tcon ps ty =
249249 mkArgs _ _ _ = []
250250
251251 bindIdxs ist [] ty is tm = tm
252− bindIdxs ist (Param : pinfo) (Bind n (Pi _ ty _) sc) is tm
252+ bindIdxs ist (Param : pinfo) (Bind n (Pi _ _ ty _) sc) is tm
253253 = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm
254− bindIdxs ist (Index : pinfo) (Bind n (Pi _ ty _) sc) (i : is) tm
254+ bindIdxs ist (Index : pinfo) (Bind n (Pi _ _ ty _) sc) (i : is) tm
255255 = PPi forall_imp i fc (delab ist ty)
256256 (bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm)
257− bindIdxs ist (ImplicitParam : pinfo) (Bind n (Pi _ ty _) sc) is tm
257+ bindIdxs ist (ImplicitParam : pinfo) (Bind n (Pi _ _ ty _) sc) is tm
258258 = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm
259− bindIdxs ist (ImplicitIndex : pinfo) (Bind n (Pi _ ty _) sc) (i : is) tm
259+ bindIdxs ist (ImplicitIndex : pinfo) (Bind n (Pi _ _ ty _) sc) (i : is) tm
260260 = bindIdxs ist pinfo (instantiate (P Bound n ty) sc) is tm
261261 bindIdxs _ _ _ _ tm = tm
src/Idris/Elab/Term.hs+146−101
@@ -18,7 +18,7 @@ import Idris.Core.ProofTerm (getProofTerm)
1818import Idris.Core.TT
1919import Idris.Core.Typecheck (check, converts, isType, recheck)
2020import Idris.Core.Unify
21−import Idris.Core.WHNF (whnf)
21+import Idris.Core.WHNF (whnf,whnfArgs)
2222import Idris.Coverage (genClauses, recoverableCoverage, validCoverageCase)
2323import Idris.Delaborate
2424import Idris.DSL
@@ -45,7 +45,7 @@ import qualified Data.Set as S
4545import qualified Data.Text as T
4646import Debug.Trace
4747
48−data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS
48+data ElabMode = ETyDecl | ETransLHS | ELHS | EImpossible | ERHS
4949 deriving Eq
5050
5151
@@ -143,7 +143,7 @@ build ist info emode opts fn tm
143143 if log /= ""
144144 then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
145145 else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
146− where pattern = emode == ELHS
146+ where pattern = emode == ELHS || emode == EImpossible
147147 tydecl = emode == ETyDecl
148148
149149 mkPat = do hs <- get_holes
@@ -189,7 +189,7 @@ buildTC ist info emode opts fn ns tm
189189 if (log /= "")
190190 then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
191191 else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
192− where pattern = emode == ELHS
192+ where pattern = emode == ELHS || emode == EImpossible
193193
194194-- | return whether arguments of the given constructor name can be
195195-- matched on. If they're polymorphic, no, unless the type has beed
@@ -201,7 +201,7 @@ getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon
201201 Nothing -> []
202202 Just ty -> checkArgs [] [] ty
203203 where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool]
204− checkArgs env ns (Bind n (Pi _ t _) sc)
204+ checkArgs env ns (Bind n (Pi _ _ t _) sc)
205205 = let env' = case t of
206206 TType _ -> n : env
207207 _ -> env in
@@ -227,7 +227,7 @@ goal_polymorphic =
227227 do ty <- goal
228228 case ty of
229229 P _ n _ -> do env <- get_env
230− case lookup n env of
230+ case lookupBinder n env of
231231 Nothing -> return False
232232 _ -> return True
233233 _ -> return False
@@ -245,23 +245,30 @@ elab :: IState
245245elab ist info emode opts fn tm
246246 = do let loglvl = opt_logLevel (idris_options ist)
247247 when (loglvl > 5) $ unifyLog True
248− compute -- expand type synonyms, etc
248+ whnf_compute_args -- expand type synonyms, etc
249249 let fc = maybe "(unknown)"
250250 elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)
251251 est <- getAux
252252 sequence_ (get_delayed_elab est)
253253 end_unify
254+ when (pattern || intransform) $
255+ -- convert remaining holes to pattern vars
256+ do unify_all
257+ matchProblems False -- only the ones we matched earlier
258+ unifyProblems
259+ mkPat
260+ update_term liftPats
254261 ptm <- get_term
255− when (pattern || intransform) -- convert remaining holes to pattern vars
256− (do unify_all
257− matchProblems False -- only the ones we matched earlier
258− unifyProblems
259− mkPat
260− update_term liftPats)
262+ when pattern $
263+ -- Look for Rig1 (linear) pattern bindings
264+ do let pnms = findLinear ist [] ptm
265+ update_term (setLinear pnms)
261266 where
262− pattern = emode == ELHS
267+ pattern = emode == ELHS || emode == EImpossible
268+ eimpossible = emode == EImpossible
263269 intransform = emode == ETransLHS
264270 bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS
271+ || emode == EImpossible
265272 autoimpls = opt_autoimpls (idris_options ist)
266273
267274 get_delayed_elab est =
@@ -293,7 +300,7 @@ elab ist info emode opts fn tm
293300
294301 -- | elabE elaborates an expression, possibly wrapping implicit coercions
295302 -- and forces/delays. If you make a recursive call in elab', it is
296− -- normally correct to call elabE - the ones that don't are desugarings
303+ -- normally correct to call elabE - the ones that don't are `desugarings
297304 -- typically
298305 elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD ()
299306 elabE ina fc' t =
@@ -332,13 +339,13 @@ elab ist info emode opts fn tm
332339 pexp ct]))
333340
334341 forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
335− | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
342+ | (P _ (UN ht) _, _) <- unApply (whnf (tt_ctxt ist) env t),
336343 ht == txt "Delayed" = notDelay orig
337344 forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
338− | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'),
345+ | (P _ (UN ht) _, _) <- unApply (whnf (tt_ctxt ist) env t'),
339346 ht == txt "Delayed" = notDelay orig
340347 forceErr orig env (InfiniteUnify _ t _)
341− | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
348+ | (P _ (UN ht) _, _) <- unApply (whnf (tt_ctxt ist) env t),
342349 ht == txt "Delayed" = notDelay orig
343350 forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t
344351 forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t
@@ -349,7 +356,7 @@ elab ist info emode opts fn tm
349356 notDelay _ = True
350357
351358 local f = do e <- get_env
352− return (f `elem` map fst e)
359+ return (f `elem` map fstEnv e)
353360
354361 -- | Is a constant a type?
355362 constType :: Const -> Bool
@@ -370,7 +377,10 @@ elab ist info emode opts fn tm
370377 solve
371378 highlightSource fc' (AnnType "Type" "The type of types")
372379 elab' ina fc (PUniverse fc' u) =
373− do apply (RUType u) []
380+ do unless (UniquenessTypes `elem` idris_language_extensions ist
381+ || e_qq ina) $
382+ lift $ tfail $ At fc' (Msg "You must turn on the UniquenessTypes extension to use UniqueType or AnyType")
383+ apply (RUType u) []
374384 solve
375385 highlightSource fc' (AnnType (show u) "The type of unique types")
376386-- elab' (_,_,inty) (PConstant c)
@@ -387,7 +397,7 @@ elab ist info emode opts fn tm
387397 highlightSource fc' (AnnConst c)
388398 elab' ina fc (PQuote r) = do fill r; solve
389399 elab' ina _ (PTrue fc _) =
390− do compute
400+ do whnf_compute
391401 g <- goal
392402 case g of
393403 TType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
@@ -421,7 +431,7 @@ elab ist info emode opts fn tm
421431 pexp l, pexp r]))
422432
423433 elab' ina _ (PPair fc hls _ l r)
424− = do compute
434+ = do whnf_compute
425435 g <- goal
426436 let (tc, _) = unApply g
427437 case g of
@@ -444,7 +454,7 @@ elab ist info emode opts fn tm
444454 IsType -> asType
445455 IsTerm -> asValue
446456 TypeOrTerm ->
447− do compute
457+ do whnf_compute
448458 g <- goal
449459 case g of
450460 TType _ -> asType
@@ -498,11 +508,13 @@ elab ist info emode opts fn tm
498508 showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here
499509
500510 doPrune as =
501− do compute
511+ do compute -- to get 'Delayed' if it's there
502512 ty <- goal
503− let (tc, _) = unApply (unDelay ty)
513+ ctxt <- get_context
504514 env <- get_env
505− return $ pruneByType env tc (unDelay ty) ist as
515+ let ty' = unDelay ty
516+ let (tc, _) = unApply ty'
517+ return $ pruneByType eimpossible env tc ty' ist as
506518
507519 unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t,
508520 l == txt "Delayed" = unDelay arg
@@ -532,7 +544,7 @@ elab ist info emode opts fn tm
532544 (trySeq' deferr xs) True
533545 elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do
534546 env <- get_env
535− compute
547+ whnf_compute
536548 ty <- goal
537549 let doelab = elab' ina fc orig
538550 tryCatch doelab
@@ -564,7 +576,7 @@ elab ist info emode opts fn tm
564576 recoverableErr _ = True
565577
566578 pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env
567− = case unApply (normalise (tt_ctxt ist) env inc) of
579+ = case unApply (whnf (tt_ctxt ist) env inc) of
568580 (P (TCon _ _) n _, _) -> filter (hasArg n env) alts
569581 (Constant _, _) -> alts
570582 _ -> filter isLend alts -- special case hack for 'Borrowed'
@@ -656,7 +668,7 @@ elab ist info emode opts fn tm
656668 do fty <- get_type (Var n) -- check for implicits
657669 ctxt <- get_context
658670 env <- get_env
659− let a' = insertScopedImps fc (normalise ctxt env fty) []
671+ let a' = insertScopedImps fc (whnfArgs ctxt env fty) []
660672 if null a'
661673 then erun fc $
662674 do apply (Var n) []
@@ -698,19 +710,30 @@ elab ist info emode opts fn tm
698710 solve
699711 highlightSource nfc (AnnBoundName n False)
700712 elab' ina fc (PPi p n nfc Placeholder sc)
701− = do attack; arg n (is_scoped p) (sMN 0 "ty")
713+ = do attack;
714+ case pcount p of
715+ RigW -> return ()
716+ _ -> unless (LinearTypes `elem` idris_language_extensions ist
717+ || e_qq ina) $
718+ lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a count")
719+ arg n (pcount p) (is_scoped p) (sMN 0 "phTy")
702720 addAutoBind p n
703721 addPSname n -- okay for proof search
704722 elabE (ina { e_inarg = True, e_intype = True }) fc sc
705723 solve
706724 highlightSource nfc (AnnBoundName n False)
707725 elab' ina fc (PPi p n nfc ty sc)
708− = do attack; tyn <- getNameFrom (sMN 0 "ty")
726+ = do attack; tyn <- getNameFrom (sMN 0 "piTy")
709727 claim tyn RType
710728 n' <- case n of
711729 MN _ _ -> unique_hole n
712730 _ -> return n
713− forall n' (is_scoped p) (Var tyn)
731+ case pcount p of
732+ RigW -> return ()
733+ _ -> unless (LinearTypes `elem` idris_language_extensions ist
734+ || e_qq ina) $
735+ lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a linear argument")
736+ forall n' (pcount p) (is_scoped p) (Var tyn)
714737 addAutoBind p n'
715738 addPSname n' -- okay for proof search
716739 focus tyn
@@ -753,7 +776,7 @@ elab ist info emode opts fn tm
753776 (ivs' \\ ivs)
754777 -- HACK: If the name leaks into its type, it may leak out of
755778 -- scope outside, so substitute in the outer scope.
756− expandLet n (case lookup n env of
779+ expandLet n (case lookupBinder n env of
757780 Just (Let t v) -> v
758781 other -> error ("Value not a let binding: " ++ show other))
759782 solve
@@ -803,10 +826,10 @@ elab ist info emode opts fn tm
803826 ans <- claimArgTys env xs
804827 return ((aval, (True, (Var an))) : ans)
805828 fnTy [] ret = forget ret
806− fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret)
829+ fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi RigW Nothing xt RType) (fnTy xs ret)
807830
808831 localVar env (PRef _ _ x)
809− = case lookup x env of
832+ = case lookupBinder x env of
810833 Just _ -> Just x
811834 _ -> Nothing
812835 localVar env _ = Nothing
@@ -840,7 +863,7 @@ elab ist info emode opts fn tm
840863 let dataCon = isDConName f ctxt
841864 annot <- findHighlight f
842865 mapM_ checkKnownImplicit args_in
843− let args = insertScopedImps fc (normalise ctxt env fty) args_in
866+ let args = insertScopedImps fc (whnfArgs ctxt env fty) args_in
844867 let unmatchableArgs = if pattern
845868 then getUnmatchable (tt_ctxt ist) f
846869 else []
@@ -849,7 +872,7 @@ elab ist info emode opts fn tm
849872 && isTConName f (tt_ctxt ist)) $
850873 lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
851874-- trace (show (f, args_in, args)) $
852− if (f `elem` map fst env && length args == 1 && length args_in == 1)
875+ if (f `elem` map fstEnv env && length args == 1 && length args_in == 1)
853876 then -- simple app, as below
854877 do simple_app False
855878 (elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f))
@@ -897,12 +920,12 @@ elab ist info emode opts fn tm
897920 imp <- if (e_isfn ina) then
898921 do guess <- get_guess
899922 env <- get_env
900− case safeForgetEnv (map fst env) guess of
923+ case safeForgetEnv (map fstEnv env) guess of
901924 Nothing ->
902925 return []
903926 Just rguess -> do
904927 gty <- get_type rguess
905− let ty_n = normalise ctxt env gty
928+ let ty_n = whnf ctxt env gty
906929 return $ getReqImps ty_n
907930 else return []
908931 -- Now we find out how many implicits we needed at the
@@ -950,16 +973,16 @@ elab ist info emode opts fn tm
950973 = lift $ tfail $ UnknownImplicit (pname imp) f
951974 checkKnownImplicit _ = return ()
952975
953− getReqImps (Bind x (Pi (Just i) ty _) sc)
976+ getReqImps (Bind x (Pi _ (Just i) ty _) sc)
954977 = i : getReqImps sc
955978 getReqImps _ = []
956979
957980 checkIfInjective n = do
958981 env <- get_env
959− case lookup n env of
982+ case lookupBinder n env of
960983 Nothing -> return ()
961984 Just b ->
962− case unApply (normalise (tt_ctxt ist) env (binderTy b)) of
985+ case unApply (whnf (tt_ctxt ist) env (binderTy b)) of
963986 (P _ c _, args) ->
964987 case lookupCtxtExact c (idris_interfaces ist) of
965988 Nothing -> return ()
@@ -1032,6 +1055,9 @@ elab ist info emode opts fn tm
10321055 elab' ina fc (PElabError e) = lift $ tfail e
10331056 elab' ina mfc (PRewrite fc substfn rule sc newg)
10341057 = elabRewrite (elab' ina mfc) ist fc substfn rule sc newg
1058+ -- A common error case if trying to typecheck an autogenerated case block
1059+ elab' ina _ c@(PCase fc Placeholder opts)
1060+ = lift $ tfail (Msg "No expression for the case to inspect.\nYou need to replace the _ with an expression.")
10351061 elab' ina _ c@(PCase fc scr opts)
10361062 = do attack
10371063
@@ -1069,13 +1095,13 @@ elab ist info emode opts fn tm
10691095 -- unnecessarily (can only do this for unique things, since we
10701096 -- assume they don't appear implicitly in types)
10711097 ptm <- get_term
1072− let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
1098+ let inOpts = (filter (/= scvn) (map fstEnv args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
10731099
10741100 let argsDropped = filter (isUnique envU)
10751101 (nub $ allNamesIn scr ++ inApp ptm ++
10761102 inOpts)
10771103
1078− let args' = filter (\(n, _) -> n `notElem` argsDropped) args
1104+ let args' = filter (\(n, _, _) -> n `notElem` argsDropped) args
10791105
10801106 attack
10811107 cname' <- defer argsDropped (mkN (mkCaseName fc fn))
@@ -1126,8 +1152,8 @@ elab ist info emode opts fn tm
11261152 Just u -> u
11271153 _ -> False
11281154
1129− getKind env (n, _)
1130− = case lookup n env of
1155+ getKind env (n, _, _)
1156+ = case lookupBinder n env of
11311157 Nothing -> return (n, False) -- can't happen, actually...
11321158 Just b ->
11331159 do ty <- get_type (forget (binderTy b))
@@ -1210,13 +1236,13 @@ elab ist info emode opts fn tm
12101236 loadState
12111237 updateAux (\aux -> aux { highlighting = hs })
12121238
1213− let quoted = fmap (explicitNames . binderVal) $ lookup nTm env
1239+ let quoted = fmap (explicitNames . binderVal) $ lookupBinder nTm env
12141240 isRaw = case unApply (normaliseAll ctxt env finalTy) of
12151241 (P _ n _, []) | n == reflm "Raw" -> True
12161242 _ -> False
12171243 case quoted of
12181244 Just q -> do ctxt <- get_context
1219− (q', _, _) <- lift $ recheck (constraintNS info) ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q
1245+ (q', _, _) <- lift $ recheck (constraintNS info) ctxt [(uq, RigW, Lam RigW Erased) | uq <- unquoteNames] (forget q) q
12201246 if pattern
12211247 then if isRaw
12221248 then reflectRawQuotePattern unquoteNames (forget q')
@@ -1245,7 +1271,7 @@ elab ist info emode opts fn tm
12451271 elab' ina fc (PQuoteName n True nfc) =
12461272 do ctxt <- get_context
12471273 env <- get_env
1248− case lookup n env of
1274+ case lookupBinder n env of
12491275 Just _ -> do fill $ reflectName n
12501276 solve
12511277 highlightSource nfc (AnnBoundName n False)
@@ -1274,7 +1300,9 @@ elab ist info emode opts fn tm
12741300 dotterm
12751301 elab' ina fc t
12761302 elab' ina fc (PRunElab fc' tm ns) =
1277− do attack
1303+ do unless (ElabReflection `elem` idris_language_extensions ist) $
1304+ lift $ tfail $ At fc' (Msg "You must turn on the ElabReflection extension to use %runElab")
1305+ attack
12781306 n <- getNameFrom (sMN 0 "tacticScript")
12791307 let scriptTy = RApp (Var (sNS (sUN "Elab")
12801308 ["Elab", "Reflection", "Language"]))
@@ -1312,7 +1340,7 @@ elab ist info emode opts fn tm
13121340 env <- get_env
13131341 ctxt <- get_context
13141342 let v = fmap (normaliseAll ctxt env . finalise . binderVal)
1315− (lookup n env)
1343+ (lookupBinder n env)
13161344 loadState -- we have the highlighting - re-elaborate the value
13171345 elab' ina fc tm
13181346 case v of
@@ -1335,9 +1363,9 @@ elab ist info emode opts fn tm
13351363 delayElab pri t
13361364 = updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] })
13371365
1338− isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term))
1339− isScr (PRef _ _ n) (n', b) = (n', (n == n', b))
1340− isScr _ (n', b) = (n', (False, b))
1366+ isScr :: PTerm -> (Name, RigCount, Binder Term) -> (Name, (Bool, Binder Term))
1367+ isScr (PRef _ _ n) (n', _, b) = (n', (n == n', b))
1368+ isScr _ (n', _, b) = (n', (False, b))
13411369
13421370 caseBlock :: FC -> Name
13431371 -> PTerm -- original scrutinee
@@ -1437,8 +1465,8 @@ elab ist info emode opts fn tm
14371465 mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs)
14381466 mkDelay env t
14391467 = let fc = fileFC "Delay" in
1440− addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay"))
1441− [pexp t])
1468+ addImplBound ist (map fstEnv env) (PApp fc (PRef fc [] (sUN "Delay"))
1469+ [pexp t])
14421470
14431471
14441472 -- Don't put implicit coercions around applications which are marked
@@ -1463,7 +1491,7 @@ elab ist info emode opts fn tm
14631491 case fullApp tm of
14641492 -- if f is global, leave it alone because we've already
14651493 -- expanded it to the right arity
1466− PApp fc ftm@(PRef _ _ f) args | Just aty <- lookup f env ->
1494+ PApp fc ftm@(PRef _ _ f) args | Just aty <- lookupBinder f env ->
14671495 do let a = length (getArgTys (normalise (tt_ctxt ist) env (binderTy aty)))
14681496 return (mkPApp fc a ftm args)
14691497 _ -> return tm
@@ -1472,12 +1500,12 @@ elab ist info emode opts fn tm
14721500 fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
14731501 fullApp x = x
14741502
1475− insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs
1503+ insertScopedImps fc (Bind n (Pi _ im@(Just i) _ _) sc) xs
14761504 | tcimplementation i && not (toplevel_imp i)
14771505 = pimp n (PResolveTC fc) True : insertScopedImps fc sc xs
14781506 | not (toplevel_imp i)
14791507 = pimp n Placeholder True : insertScopedImps fc sc xs
1480− insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs)
1508+ insertScopedImps fc (Bind n (Pi _ _ _ _) sc) (x : xs)
14811509 = x : insertScopedImps fc sc xs
14821510 insertScopedImps _ _ xs = xs
14831511
@@ -1488,7 +1516,7 @@ elab ist info emode opts fn tm
14881516 addLam ty' t
14891517 where
14901518 -- just one level at a time
1491− addLam (Bind n (Pi (Just _) _ _) sc) t =
1519+ addLam (Bind n (Pi _ (Just _) _ _) sc) t =
14921520 do impn <- unique_hole n -- (sMN 0 "scoped_imp")
14931521 if e_isfn ina -- apply to an implicit immediately
14941522 then return (PApp emptyFC
@@ -1516,7 +1544,7 @@ elab ist info emode opts fn tm
15161544 mkCoerce env (PAlternative ms aty tms) n
15171545 = PAlternative ms aty (map (\t -> mkCoerce env t n) tms)
15181546 mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in
1519− addImplBound ist (map fst env)
1547+ addImplBound ist (map fstEnv env)
15201548 (PApp fc (PRef fc [] n) [pexp (PCoerced t)])
15211549
15221550 -- | Elaborate the arguments to a function
@@ -1575,7 +1603,7 @@ elab ist info emode opts fn tm
15751603 fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole
15761604
15771605 addAutoBind :: Plicity -> Name -> ElabD ()
1578− addAutoBind (Imp _ _ _ _ False) n
1606+ addAutoBind (Imp _ _ _ _ False _) n
15791607 = updateAux (\est -> est { auto_binds = n : auto_binds est })
15801608 addAutoBind _ _ = return ()
15811609
@@ -1625,17 +1653,17 @@ pruneAlt xs = map prune xs
16251653
16261654-- Rule out alternatives that don't return the same type as the head of the goal
16271655-- (If there are none left as a result, do nothing)
1628−pruneByType :: Env -> Term -> -- head of the goal
1656+pruneByType :: Bool -> Env -> Term -> -- head of the goal
16291657 Type -> -- goal
16301658 IState -> [PTerm] -> [PTerm]
16311659-- if an alternative has a locally bound name at the head, take it
1632−pruneByType env t goalty c as
1660+pruneByType imp env t goalty c as
16331661 | Just a <- locallyBound as = [a]
16341662 where
16351663 locallyBound [] = Nothing
16361664 locallyBound (t:ts)
16371665 | Just n <- getName t,
1638− n `elem` map fst env = Just t
1666+ n `elem` map fstEnv env = Just t
16391667 | otherwise = locallyBound ts
16401668 getName (PRef _ _ n) = Just n
16411669 getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays
@@ -1645,7 +1673,7 @@ pruneByType env t goalty c as
16451673 getName _ = Nothing
16461674
16471675-- 'n' is the name at the head of the goal type
1648−pruneByType env (P _ n _) goalty ist as
1676+pruneByType imp env (P _ n _) goalty ist as
16491677-- if the goal type is polymorphic, keep everything
16501678 | Nothing <- lookupTyExact n ctxt = as
16511679-- if the goal type is a ?metavariable, keep everything
@@ -1677,12 +1705,13 @@ pruneByType env (P _ n _) goalty ist as
16771705 Just ty -> case unApply (getRetTy ty) of
16781706 (P _ ctyn _, _) | isTConName ctyn ctxt && not (ctyn == f)
16791707 -> False
1680− _ -> let ty' = normalise ctxt [] ty in
1681−-- trace ("Trying " ++ show (getRetTy ty') ++ " for " ++ show goalty) $
1708+ _ -> let ty' = whnf ctxt [] ty in
1709+-- trace ("Trying " ++ show f' ++ " : " ++ show (getRetTy ty') ++ " for " ++ show goalty
1710+-- ++ "\nMATCH: " ++ show (pat, matching (getRetTy ty') goalty)) $
16821711 case unApply (getRetTy ty') of
16831712 (V _, _) ->
16841713 isPlausible ist var env n ty
1685− _ -> matching (getRetTy ty') goalty
1714+ _ -> matchingTypes imp (getRetTy ty') goalty
16861715 || isCoercion (getRetTy ty') goalty
16871716-- May be useful to keep for debugging purposes for a bit:
16881717-- let res = matching (getRetTy ty') goalty in
@@ -1690,9 +1719,12 @@ pruneByType env (P _ n _) goalty ist as
16901719-- ("Rejecting " ++ show (getRetTy ty', goalty)) res
16911720 _ -> False
16921721
1722+ matchingTypes True = matchingHead
1723+ matchingTypes False = matching
1724+
16931725 -- If the goal is a constructor, it must match the suggested function type
16941726 matching (P _ ctyn _) (P _ n' _)
1695− | isTConName n' ctxt = ctyn == n'
1727+ | isTConName n' ctxt && isTConName ctyn ctxt = ctyn == n'
16961728 | otherwise = True
16971729 -- Variables match anything
16981730 matching (V _) _ = True
@@ -1703,14 +1735,28 @@ pruneByType env (P _ n _) goalty ist as
17031735 matching (Bind n _ sc) _ = True
17041736 matching _ (Bind n _ sc) = True
17051737 -- If we hit a function name, it's a plausible match
1706− matching (App _ (P _ f _) _) _ | not (isConName f ctxt) = True
1707− matching _ (App _ (P _ f _) _) | not (isConName f ctxt) = True
1708− -- Otherwise, match the rest of the structure
1709− matching (App _ f a) (App _ f' a') = matching f f' && matching a a'
1738+ matching apl@(App _ _ _) apr@(App _ _ _)
1739+ | (P _ fl _, argsl) <- unApply apl,
1740+ (P _ fr _, argsr) <- unApply apr
1741+ = fl == fr && and (zipWith matching argsl argsr)
1742+ || (not (isConName fl ctxt && isConName fr ctxt))
1743+ -- If the application structures aren't easily comparable, it's a
1744+ -- plausible match
1745+ matching (App _ f a) (App _ f' a') = True
17101746 matching (TType _) (TType _) = True
17111747 matching (UType _) (UType _) = True
17121748 matching l r = l == r
17131749
1750+ -- In impossible-case mode, only look at the heads (this is to account for
1751+ -- the non type-directed case with 'impossible' - we'd be ruling out
1752+ -- too much and wouldn't find the mismatch we're looking for)
1753+ matchingHead apl@(App _ _ _) apr@(App _ _ _)
1754+ | (P _ fl _, argsl) <- unApply apl,
1755+ (P _ fr _, argsr) <- unApply apr,
1756+ isConName fl ctxt && isConName fr ctxt
1757+ = fl == fr
1758+ matchingHead _ _ = True
1759+
17141760 -- Return whether there is a possible coercion between the return type
17151761 -- of an alternative and the goal type
17161762 isCoercion rty gty | (P _ r _, _) <- unApply rty
@@ -1735,7 +1781,7 @@ pruneByType env (P _ n _) goalty ist as
17351781 _ -> False
17361782
17371783
1738−pruneByType _ t _ _ as = as
1784+pruneByType _ _ t _ _ as = as
17391785
17401786-- Could the name feasibly be the return type?
17411787-- If there is an interface constraint on the return type, and no implementation
@@ -1752,7 +1798,7 @@ isPlausible ist var env n ty
17521798 where
17531799 collectConstraints :: [Name] -> [(Term, [Name])] -> Type ->
17541800 (Maybe Name, [(Term, [Name])])
1755− collectConstraints env tcs (Bind n (Pi _ ty _) sc)
1801+ collectConstraints env tcs (Bind n (Pi _ _ ty _) sc)
17561802 = let tcs' = case unApply ty of
17571803 (P _ c _, _) ->
17581804 case lookupCtxtExact c (idris_interfaces ist) of
@@ -1770,7 +1816,7 @@ isPlausible ist var env n ty
17701816findHighlight :: Name -> ElabD OutputAnnotation
17711817findHighlight n = do ctxt <- get_context
17721818 env <- get_env
1773− case lookup n env of
1819+ case lookupBinder n env of
17741820 Just _ -> return $ AnnBoundName n False
17751821 Nothing -> case lookupTyExact n ctxt of
17761822 Just _ -> return $ AnnName n Nothing Nothing Nothing
@@ -1790,7 +1836,7 @@ solveAuto ist fn ambigok (n, failc)
17901836 when (not isg) $
17911837 proofSearch' ist True ambigok 100 True Nothing fn [] [])
17921838 (lift $ Error (addLoc failc
1793− (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))))
1839+ (CantSolveGoal g (map (\(n, _, b) -> (n, binderTy b)) env))))
17941840 return ()
17951841 where addLoc (FailContext fc f x : prev) err
17961842 = At fc (ElaboratingArg f x
@@ -1863,7 +1909,7 @@ case_ ind autoSolve ist fn tm = do
18631909 focus valn
18641910 elab ist toplevel ERHS [] (sMN 0 "tac") tm
18651911 env <- get_env
1866− let (Just binding) = lookup letn env
1912+ let (Just binding) = lookupBinder letn env
18671913 let val = binderVal binding
18681914 if ind then induction (forget val)
18691915 else casetac (forget val)
@@ -1886,7 +1932,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
18861932 returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased)
18871933
18881934 patvars :: [(Name, Term)] -> Term -> ([(Name, Term)], Term)
1889− patvars ns (Bind n (PVar t) sc) = patvars ((n, t) : ns) (instantiate (P Bound n t) sc)
1935+ patvars ns (Bind n (PVar _ t) sc) = patvars ((n, t) : ns) (instantiate (P Bound n t) sc)
18901936 patvars ns tm = (ns, tm)
18911937
18921938 pullVars :: (Term, Term) -> ([(Name, Term)], Term, Term)
@@ -1955,7 +2001,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
19552001
19562002 -- | Add another argument to a Pi
19572003 mkPi :: RFunArg -> Raw -> Raw
1958− mkPi arg rTy = RBind (argName arg) (Pi Nothing (argTy arg) (RUType AllTypes)) rTy
2004+ mkPi arg rTy = RBind (argName arg) (Pi RigW Nothing (argTy arg) (RUType AllTypes)) rTy
19592005
19602006 mustBeType ctxt tm ty =
19612007 case normaliseAll ctxt [] (finalise ty) of
@@ -2012,7 +2058,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
20122058 _ -> n
20132059
20142060 getRetTy :: Type -> Type
2015− getRetTy (Bind _ (Pi _ _ _) sc) = getRetTy sc
2061+ getRetTy (Bind _ (Pi _ _ _ _) sc) = getRetTy sc
20162062 getRetTy ty = ty
20172063
20182064 elabScriptStuck :: Term -> ElabD a
@@ -2220,7 +2266,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
22202266 = do ~[n, ty] <- tacTmArgs 2 tac args
22212267 n' <- reifyTTName n
22222268 ty' <- reifyRaw ty
2223− forall n' Nothing ty'
2269+ forall n' RigW Nothing ty'
22242270 returnUnit
22252271 | n == tacN "Prim__PatVar"
22262272 = do ~[n] <- tacTmArgs 1 tac args
@@ -2230,7 +2276,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
22302276 | n == tacN "Prim__PatBind"
22312277 = do ~[n] <- tacTmArgs 1 tac args
22322278 n' <- reifyTTName n
2233− patbind n'
2279+ patbind n' RigW
22342280 returnUnit
22352281 | n == tacN "Prim__LetBind"
22362282 = do ~[n, ty, tm] <- tacTmArgs 3 tac args
@@ -2252,7 +2298,7 @@ runElabAction info ist fc env tm ns = do tm' <- eval tm
22522298 = do ~[tm] <- tacTmArgs 1 tac args
22532299 tm' <- reifyTT tm
22542300 ctxt <- get_context
2255− fmap fst . checkClosed . reflect $ whnf ctxt tm'
2301+ fmap fst . checkClosed . reflect $ whnf ctxt [] tm'
22562302 | n == tacN "Prim__Converts"
22572303 = do ~[env, tm1, tm2] <- tacTmArgs 3 tac args
22582304 env' <- reifyEnv env
@@ -2426,11 +2472,11 @@ runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD ()
24262472runTac autoSolve ist perhapsFC fn tac
24272473 = do env <- get_env
24282474 g <- goal
2429− let tac' = fmap (addImplBound ist (map fst env)) tac
2475+ let tac' = fmap (addImplBound ist (map fstEnv env)) tac
24302476 if autoSolve
24312477 then runT tac'
24322478 else no_errors (runT tac')
2433− (Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))
2479+ (Just (CantSolveGoal g (map (\(n, _, b) -> (n, binderTy b)) env)))
24342480 where
24352481 runT (Intro []) = do g <- goal
24362482 attack; intro (bname g)
@@ -2460,7 +2506,7 @@ runTac autoSolve ist perhapsFC fn tac
24602506 tryAll tacs
24612507 when autoSolve solveAll
24622508 where envArgs n = do e <- get_env
2463− case lookup n e of
2509+ case lookupBinder n e of
24642510 Just t -> return $ map (const False)
24652511 (getArgTys (binderTy t))
24662512 _ -> return []
@@ -2478,7 +2524,7 @@ runTac autoSolve ist perhapsFC fn tac
24782524 where isImp (PImp _ _ _ _ _) = True
24792525 isImp _ = False
24802526 envArgs n = do e <- get_env
2481− case lookup n e of
2527+ case lookupBinder n e of
24822528 Just t -> return $ map (const False)
24832529 (getArgTys (binderTy t))
24842530 _ -> return []
@@ -2587,9 +2633,9 @@ runTac autoSolve ist perhapsFC fn tac
25872633 where tacticTy = Var (reflm "Tactic")
25882634 listTy = Var (sNS (sUN "List") ["List", "Prelude"])
25892635 scriptTy = (RBind (sMN 0 "__pi_arg")
2590− (Pi Nothing (RApp listTy envTupleType) RType)
2636+ (Pi RigW Nothing (RApp listTy envTupleType) RType)
25912637 (RBind (sMN 1 "__pi_arg")
2592− (Pi Nothing (Var $ reflm "TT") RType) tacticTy))
2638+ (Pi RigW Nothing (Var $ reflm "TT") RType) tacticTy))
25932639 runT (ByReflection tm) -- run the reflection function 'tm' on the
25942640 -- goal, then apply the resulting reflected Tactic
25952641 = do tgoal <- goal
@@ -2785,7 +2831,7 @@ processTacticDecls info steps =
27852831 mapM_ (addIBC . IBCDef . cn) ctors
27862832 ctxt <- getContext
27872833 let params = findParams tyn (normalise ctxt [] tyconTy) (map cty ctors)
2788− let typeInfo = TI (map cn ctors) False [] params []
2834+ let typeInfo = TI (map cn ctors) False [] params [] False
27892835 -- implicit precondition to IBCData is that idris_datatypes on the IState is populated.
27902836 -- otherwise writing the IBC just fails silently!
27912837 updateIState $ \i -> i { idris_datatypes =
@@ -2826,15 +2872,16 @@ processTacticDecls info steps =
28262872 RClausesInstrs n cs ->
28272873 do logElab 3 $ "Pattern-matching definition from tactics: " ++ show n
28282874 solveDeferred emptyFC n
2829− let lhss = map (\(_, lhs, _) -> lhs) cs
2875+ let lhss = map (\(ns, lhs, _) -> (map fst ns, lhs)) cs
28302876 let fc = fileFC "elab_reflected"
28312877 pmissing <-
28322878 do ist <- getIState
28332879 possible <- genClauses fc n lhss
2834− (map (\lhs ->
2880+ (map (\ (ns, lhs) ->
28352881 delab' ist lhs True True) lhss)
28362882 missing <- filterM (checkPossible n) possible
2837− return (filter (noMatch ist lhss) missing)
2883+ let undef = filter (noMatch ist (map snd lhss)) missing
2884+ return undef
28382885 let tot = if null pmissing
28392886 then Unchecked -- still need to check recursive calls
28402887 else Partial NotCovering -- missing cases implies not total
@@ -2871,16 +2918,16 @@ processTacticDecls info steps =
28712918 where
28722919 -- TODO: see if the code duplication with Idris.Elab.Clause can be
28732920 -- reduced or eliminated.
2921+ -- These are always cases generated by genClauses
28742922 checkPossible :: Name -> PTerm -> Idris Bool
28752923 checkPossible fname lhs_in =
28762924 do ctxt <- getContext
28772925 ist <- getIState
28782926 let lhs = addImplPat ist lhs_in
28792927 let fc = fileFC "elab_reflected_totality"
2880− let tcgen = False -- TODO: later we may support dictionary generation
28812928 case elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "refPatLHS") infP initEState
2882− (erun fc (buildTC ist info ELHS [] fname (allNamesIn lhs_in)
2883− (infTerm lhs))) of
2929+ (erun fc (buildTC ist info EImpossible [] fname (allNamesIn lhs_in)
2930+ (infTerm lhs))) of
28842931 OK (ElabResult lhs' _ _ _ _ _ name', _) ->
28852932 do -- not recursively calling here, because we don't
28862933 -- want to run infinitely many times
@@ -2890,9 +2937,7 @@ processTacticDecls info steps =
28902937 OK _ -> return True
28912938 err -> return False
28922939 -- if it's a recoverable error, the case may become possible
2893− Error err -> if tcgen then return (recoverableCoverage ctxt err)
2894− else return (validCoverageCase ctxt err ||
2895− recoverableCoverage ctxt err)
2940+ Error err -> return (recoverableCoverage ctxt err)
28962941
28972942
28982943 -- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause
src/Idris/Elab/Transform.hs+3−3
@@ -114,11 +114,11 @@ elabTransform info fc safe lhs_in@(PApp _ (PRef _ _ tf) _) rhs_in
114114 return (clhs_tm, crhs_tm)
115115
116116 where
117− depat (Bind n (PVar t) sc) = depat (instantiate (P Bound n t) sc)
117+ depat (Bind n (PVar _ t) sc) = depat (instantiate (P Bound n t) sc)
118118 depat x = x
119119
120− renamepats (n' : ns) (Bind n (PVar t) sc)
121− = Bind n' (PVar t) (renamepats ns sc) -- all Vs
120+ renamepats (n' : ns) (Bind n (PVar rig t) sc)
121+ = Bind n' (PVar rig t) (renamepats ns sc) -- all Vs
122122 renamepats _ sc = sc
123123
124124 -- names for transformation variables. Need to ensure these don't clash
src/Idris/Elab/Type.hs+9−4
@@ -16,6 +16,7 @@ import Idris.ASTUtils
1616import Idris.Core.CaseTree
1717import Idris.Core.Elaborate hiding (Tactic(..))
1818import Idris.Core.Evaluate
19+import Idris.Core.WHNF
1920import Idris.Core.Execute
2021import Idris.Core.TT
2122import Idris.Core.Typecheck
@@ -132,14 +133,18 @@ buildType info syn fc opts n ty' = do
132133 let fninfo = FnInfo (param_pos 0 pnames cty)
133134 setFnInfo n fninfo
134135 addIBC (IBCFnInfo n fninfo)
136+
137+ -- If we use any types with linear constructor arguments, we'd better
138+ -- make sure they are use-once
139+ tcliftAt fc $ linearCheck ctxt (whnfArgs ctxt [] cty)
135140
136141 return (cty, ckind, ty, inacc)
137142 where
138− patToImp (Bind n (PVar t) sc) = Bind n (Pi Nothing t (TType (UVar [] 0))) (patToImp sc)
143+ patToImp (Bind n (PVar rig t) sc) = Bind n (Pi rig Nothing t (TType (UVar [] 0))) (patToImp sc)
139144 patToImp (Bind n b sc) = Bind n b (patToImp sc)
140145 patToImp t = t
141146
142− param_pos i ns (Bind n (Pi _ t _) sc)
147+ param_pos i ns (Bind n (Pi _ _ t _) sc)
143148 | n `elem` ns = i : param_pos (i + 1) ns sc
144149 | otherwise = param_pos (i + 1) ns sc
145150 param_pos i ns t = []
@@ -192,7 +197,7 @@ elabType' norm info syn doc argDocs fc opts n nfc ty' = {- let ty' = piBind (par
192197 let (fam, _) = unApply (getRetTy nty')
193198 let corec = case fam of
194199 P _ rcty _ -> case lookupCtxt rcty (idris_datatypes i) of
195− [TI _ True _ _ _] -> True
200+ [TI _ True _ _ _ _] -> True
196201 _ -> False
197202 _ -> False
198203 -- Productivity checking now via checking for guarded 'Delay'
@@ -260,7 +265,7 @@ elabType' norm info syn doc argDocs fc opts n nfc ty' = {- let ty' = piBind (par
260265 lst = txt "List"
261266 errrep = txt "ErrorReportPart"
262267
263− tyIsHandler (Bind _ (Pi _ (P _ (NS (UN e) ns1) _) _)
268+ tyIsHandler (Bind _ (Pi _ _ (P _ (NS (UN e) ns1) _) _)
264269 (App _ (P _ (NS (UN m) ns2) _)
265270 (App _ (P _ (NS (UN l) ns3) _)
266271 (P _ (NS (UN r) ns4) _))))
src/Idris/Elab/Utils.hs+66−33
@@ -11,6 +11,7 @@ module Idris.Elab.Utils where
1111import Idris.AbsSyntax
1212import Idris.Core.Elaborate hiding (Tactic(..))
1313import Idris.Core.Evaluate
14+import Idris.Core.WHNF
1415import Idris.Core.TT
1516import Idris.Core.Typecheck
1617import Idris.DeepSeq
@@ -103,7 +104,7 @@ checkAddDef add toplvl info fc mkerr definable ((n, (i, top, t, psns)) : ns)
103104-- | Get the list of (index, name) of inaccessible arguments from an elaborated
104105-- type
105106inaccessibleImps :: Int -> Type -> [Bool] -> [(Int, Name)]
106−inaccessibleImps i (Bind n (Pi _ t _) sc) (inacc : ins)
107+inaccessibleImps i (Bind n (Pi _ _ t _) sc) (inacc : ins)
107108 | inacc = (i, n) : inaccessibleImps (i + 1) sc ins
108109 | otherwise = inaccessibleImps (i + 1) sc ins
109110inaccessibleImps _ _ _ = []
@@ -184,8 +185,8 @@ decorateid decorate (PClauses f o n cs)
184185
185186-- if 't' is an interface application, assume its arguments are injective
186187pbinds :: IState -> Term -> ElabD ()
187−pbinds i (Bind n (PVar t) sc)
188− = do attack; patbind n
188+pbinds i (Bind n (PVar rig t) sc)
189+ = do attack; patbind n rig
189190 env <- get_env
190191 case unApply (normalise (tt_ctxt i) env t) of
191192 (P _ c _, args) -> case lookupCtxt c (idris_interfaces i) of
@@ -198,26 +199,26 @@ pbinds i (Bind n (PVar t) sc)
198199 setinjArg _ = return ()
199200pbinds i tm = return ()
200201
201−pbty (Bind n (PVar t) sc) tm = Bind n (PVTy t) (pbty sc tm)
202+pbty (Bind n (PVar _ t) sc) tm = Bind n (PVTy t) (pbty sc tm)
202203pbty _ tm = tm
203204
204−getPBtys (Bind n (PVar t) sc) = (n, t) : getPBtys sc
205+getPBtys (Bind n (PVar _ t) sc) = (n, t) : getPBtys sc
205206getPBtys (Bind n (PVTy t) sc) = (n, t) : getPBtys sc
206207getPBtys _ = []
207208
208−psolve (Bind n (PVar t) sc) = do solve; psolve sc
209+psolve (Bind n (PVar _ t) sc) = do solve; psolve sc
209210psolve tm = return ()
210211
211−pvars ist (Bind n (PVar t) sc) = (n, delab ist t) : pvars ist sc
212+pvars ist (Bind n (PVar _ t) sc) = (n, delab ist t) : pvars ist sc
212213pvars ist _ = []
213214
214−getFixedInType i env (PExp _ _ _ _ : is) (Bind n (Pi _ t _) sc)
215+getFixedInType i env (PExp _ _ _ _ : is) (Bind n (Pi _ _ t _) sc)
215216 = nub $ getFixedInType i env [] t ++
216217 getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
217218 ++ case unApply t of
218219 (P _ n _, _) -> if n `elem` env then [n] else []
219220 _ -> []
220−getFixedInType i env (_ : is) (Bind n (Pi _ t _) sc)
221+getFixedInType i env (_ : is) (Bind n (Pi _ _ t _) sc)
221222 = getFixedInType i (n : env) is (instantiate (P Bound n t) sc)
222223getFixedInType i env is tm@(App _ f a)
223224 | (P _ tn _, args) <- unApply tm
@@ -231,7 +232,7 @@ getFixedInType i env is tm@(App _ f a)
231232 getFixedInType i env is a
232233getFixedInType i _ _ _ = []
233234
234−getFlexInType i env ps (Bind n (Pi _ t _) sc)
235+getFlexInType i env ps (Bind n (Pi _ _ t _) sc)
235236 = nub $ (if (not (n `elem` ps)) then getFlexInType i env ps t else []) ++
236237 getFlexInType i (n : env) ps (instantiate (P Bound n t) sc)
237238
@@ -260,7 +261,7 @@ getParamsInType i env ps t = let fix = getFixedInType i env ps t
260261 flex = getFlexInType i env fix t in
261262 [x | x <- fix, not (x `elem` flex)]
262263
263−getTCinj i (Bind n (Pi _ t _) sc)
264+getTCinj i (Bind n (Pi _ _ t _) sc)
264265 = getTCinj i t ++ getTCinj i (instantiate (P Bound n t) sc)
265266getTCinj i ap@(App _ f a)
266267 | (P _ n _, args) <- unApply ap,
@@ -292,13 +293,13 @@ getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []
292293 where
293294 getUniq :: Env -> [(Name, Bool)] -> Term -> State [Name] ()
294295 getUniq env us (Bind n b sc)
295− = let uniq = case check ctxt env (forgetEnv (map fst env) (binderTy b)) of
296+ = let uniq = case check ctxt env (forgetEnv (map fstEnv env) (binderTy b)) of
296297 OK (_, UType UniqueType) -> True
297298 OK (_, UType NullType) -> True
298299 OK (_, UType AllTypes) -> True
299300 _ -> False in
300301 do getUniqB env us b
301− getUniq ((n,b):env) ((n, uniq):us) sc
302+ getUniq ((n, RigW, b):env) ((n, uniq):us) sc
302303 getUniq env us (App _ f a) = do getUniq env us f; getUniq env us a
303304 getUniq env us (V i)
304305 | i < length us = if snd (us!!i) then use (fst (us!!i)) else return ()
@@ -310,14 +311,14 @@ getUniqueUsed ctxt tm = execState (getUniq [] [] tm) []
310311
311312 getUniqB env us (Let t v) = getUniq env us v
312313 getUniqB env us (Guess t v) = getUniq env us v
313−-- getUniqB env us (Pi t v) = do getUniq env us t; getUniq env us v
314+-- getUniqB env us (Pi _ _ t v) = do getUniq env us t; getUniq env us v
314315 getUniqB env us (NLet t v) = getUniq env us v
315316 getUniqB env us b = return () -- getUniq env us (binderTy b)
316317
317318-- In a functional application, return the names which are used
318319-- directly in a static position
319320getStaticNames :: IState -> Term -> [Name]
320−getStaticNames ist (Bind n (PVar _) sc)
321+getStaticNames ist (Bind n (PVar _ _) sc)
321322 = getStaticNames ist (instantiate (P Bound n Erased) sc)
322323getStaticNames ist tm
323324 | (P _ fn _, args) <- unApply tm
@@ -331,7 +332,7 @@ getStaticNames ist tm
331332getStaticNames _ _ = []
332333
333334getStatics :: [Name] -> Term -> [Bool]
334−getStatics ns (Bind n (Pi _ _ _) t)
335+getStatics ns (Bind n (Pi _ _ _ _) t)
335336 | n `elem` ns = True : getStatics ns t
336337 | otherwise = False : getStatics ns t
337338getStatics _ _ = []
@@ -407,7 +408,7 @@ findParams tyn famty ts =
407408 getDataApp f@(App _ _ _)
408409 | (P _ d _, args) <- unApply f
409410 = if (d == tyn) then [mParam args args] else []
410− getDataApp (Bind n (Pi _ t _) sc)
411+ getDataApp (Bind n (Pi _ _ t _) sc)
411412 = getDataApp t ++ getDataApp (instantiate (P Bound n t) sc)
412413 getDataApp _ = []
413414
@@ -478,9 +479,9 @@ orderPats tm = op [] tm
478479 where
479480 op [] (App s f a) = App s f (op [] a) -- for Infer terms
480481
481− op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
482+ op ps (Bind n (PVar r t) sc) = op ((n, PVar r t) : ps) sc
482483 op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
483− op ps (Bind n (Pi i t k) sc) = op ((n, Pi i t k) : ps) sc
484+ op ps (Bind n (Pi rig i t k) sc) = op ((n, Pi rig i t k) : ps) sc
484485 op ps sc = bindAll (sortP ps) sc
485486
486487 -- Keep explicit Pi in the same order, insert others as necessary,
@@ -488,8 +489,8 @@ orderPats tm = op [] tm
488489 sortP ps = let (exps, imps) = partition isExp ps in
489490 pick (reverse exps) imps
490491
491− isExp (_, Pi Nothing _ _) = True
492− isExp (_, Pi (Just i) _ _) = toplevel_imp i && not (machine_gen i)
492+ isExp (_, Pi rig Nothing _ _) = True
493+ isExp (_, Pi rig (Just i) _ _) = toplevel_imp i && not (machine_gen i)
493494 isExp _ = False
494495
495496 pick acc [] = acc
@@ -510,13 +511,13 @@ liftPats tm = let (tm', ps) = runState (getPats tm) [] in
510511 where
511512 bindPats [] tm = tm
512513 bindPats ((n, t):ps) tm
513− | n `notElem` map fst ps = Bind n (PVar t) (bindPats ps tm)
514+ | n `notElem` map fst ps = Bind n (PVar RigW t) (bindPats ps tm)
514515 | otherwise = bindPats ps tm
515516
516517 getPats :: Term -> State [(Name, Type)] Term
517− getPats (Bind n (PVar t) sc) = do ps <- get
518− put ((n, t) : ps)
519− getPats sc
518+ getPats (Bind n (PVar _ t) sc) = do ps <- get
519+ put ((n, t) : ps)
520+ getPats sc
520521 getPats (Bind n (Guess t v) sc) = do t' <- getPats t
521522 v' <- getPats v
522523 sc' <- getPats sc
@@ -525,13 +526,13 @@ liftPats tm = let (tm', ps) = runState (getPats tm) [] in
525526 v' <- getPats v
526527 sc' <- getPats sc
527528 return (Bind n (Let t' v') sc')
528− getPats (Bind n (Pi i t k) sc) = do t' <- getPats t
529− k' <- getPats k
530− sc' <- getPats sc
531− return (Bind n (Pi i t' k') sc')
532− getPats (Bind n (Lam t) sc) = do t' <- getPats t
533− sc' <- getPats sc
534− return (Bind n (Lam t') sc')
529+ getPats (Bind n (Pi rig i t k) sc) = do t' <- getPats t
530+ k' <- getPats k
531+ sc' <- getPats sc
532+ return (Bind n (Pi rig i t' k') sc')
533+ getPats (Bind n (Lam r t) sc) = do t' <- getPats t
534+ sc' <- getPats sc
535+ return (Bind n (Lam r t') sc')
535536 getPats (Bind n (Hole t) sc) = do t' <- getPats t
536537 sc' <- getPats sc
537538 return (Bind n (Hole t') sc')
@@ -568,6 +569,38 @@ isEmpty ctxt tyctxt ty
568569isEmpty ctxt tyinfo ty = False
569570
570571hasEmptyPat :: Context -> Ctxt TypeInfo -> Term -> Bool
571−hasEmptyPat ctxt tyctxt (Bind n (PVar ty) sc)
572+hasEmptyPat ctxt tyctxt (Bind n (PVar _ ty) sc)
572573 = isEmpty ctxt tyctxt ty || hasEmptyPat ctxt tyctxt sc
573574hasEmptyPat ctxt tyctxt _ = False
575+
576+-- Find names which are applied to a function in a Rig1 position
577+findLinear :: IState -> [Name] -> Term -> [(Name, RigCount)]
578+findLinear ist env tm | (P _ f _, args) <- unApply tm,
579+ f `notElem` env,
580+ Just ty_in <- lookupTyExact f (tt_ctxt ist)
581+ = let ty = whnfArgs (tt_ctxt ist) [] ty_in in
582+ nub $ concatMap (findLinear ist env) args ++ findLinArg ty args
583+ where
584+ findLinArg (Bind n (Pi c _ _ _) sc) (P _ a _ : as)
585+ | Rig0 <- c = (a, c) : findLinArg sc as
586+ | Rig1 <- c = (a, c) : findLinArg sc as
587+ findLinArg (Bind n (Pi _ _ _ _) sc) (a : as)
588+ = findLinArg (whnf (tt_ctxt ist) [] (substV a sc)) as
589+ findLinArg _ _ = []
590+findLinear ist env (App _ f a)
591+ = nub $ findLinear ist env f ++ findLinear ist env a
592+findLinear ist env (Bind n b sc) = findLinear ist (n : env) sc
593+findLinear ist _ _ = []
594+
595+setLinear :: [(Name, RigCount)] -> Term -> Term
596+setLinear ns (Bind n b@(PVar r t) sc)
597+ | Just r <- lookup n ns = Bind n (PVar r t) (setLinear ns sc)
598+ | otherwise = Bind n b (setLinear ns sc)
599+setLinear ns tm = tm
600+
601+linearArg :: Type -> Bool
602+linearArg (Bind n (Pi Rig1 _ _ _) sc) = True
603+linearArg (Bind n (Pi _ _ _ _) sc) = linearArg sc
604+linearArg _ = False
605+
606+
src/Idris/ElabDecls.hs+13−8
@@ -116,9 +116,9 @@ elabPrims = do i <- getIState
116116
117117 p_believeMe [_,_,x] = Just x
118118 p_believeMe _ = Nothing
119− believeTy = Bind (sUN "a") (Pi Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1))))
120− (Bind (sUN "b") (Pi Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1))))
121− (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar [] (-1)))) (V 1)))
119+ believeTy = Bind (sUN "a") (Pi RigW Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1))))
120+ (Bind (sUN "b") (Pi RigW Nothing (TType (UVar [] (-2))) (TType (UVar [] (-1))))
121+ (Bind (sUN "x") (Pi RigW Nothing (V 1) (TType (UVar [] (-1)))) (V 1)))
122122 elabBelieveMe
123123 = do let prim__believe_me = sUN "prim__believe_me"
124124 updateContext (addOperator prim__believe_me believeTy 3 p_believeMe)
@@ -141,10 +141,10 @@ elabPrims = do i <- getIState
141141 vnNothing = VP (DCon 0 1 False) (sNS (sUN "Nothing") ["Maybe", "Prelude"]) VErased
142142 vnRefl = VP (DCon 0 2 False) eqCon VErased
143143
144− synEqTy = Bind (sUN "a") (Pi Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2))))
145− (Bind (sUN "b") (Pi Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2))))
146− (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar [] (-2))))
147− (Bind (sUN "y") (Pi Nothing (V 1) (TType (UVar [] (-2))))
144+ synEqTy = Bind (sUN "a") (Pi RigW Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2))))
145+ (Bind (sUN "b") (Pi RigW Nothing (TType (UVar [] (-3))) (TType (UVar [] (-2))))
146+ (Bind (sUN "x") (Pi RigW Nothing (V 1) (TType (UVar [] (-2))))
147+ (Bind (sUN "y") (Pi RigW Nothing (V 1) (TType (UVar [] (-2))))
148148 (mkApp nMaybe [mkApp (P (TCon 0 4) eqTy Erased)
149149 [V 3, V 2, V 1, V 0]]))))
150150 elabSynEq
@@ -284,6 +284,8 @@ elabDecl' what info (PRecord doc rsyn fc opts name nfc ps pdocs fs cname cdoc cs
284284-}
285285elabDecl' _ info (PDSL n dsl)
286286 = do i <- getIState
287+ unless (DSLNotation `elem` idris_language_extensions i) $
288+ ifail "You must turn on the DSLNotation extension to use a dsl block"
287289 putIState (i { idris_dsls = addDef n dsl (idris_dsls i) })
288290 addIBC (IBCDSL n)
289291elabDecl' what info (PDirective i)
@@ -296,6 +298,9 @@ elabDecl' what info (PTransform fc safety old new)
296298 = do elabTransform info fc safety old new
297299 return ()
298300elabDecl' what info (PRunElabDecl fc script ns)
299− = do elabRunElab info fc script ns
301+ = do i <- getIState
302+ unless (ElabReflection `elem` idris_language_extensions i) $
303+ ierror $ At fc (Msg "You must turn on the ElabReflection extension to use %runElab")
304+ elabRunElab info fc script ns
300305 return ()
301306elabDecl' _ _ _ = return () -- skipped this time
src/Idris/Erasure.hs+7−7
@@ -366,8 +366,8 @@ buildDepMap ci used externs ctx startNames
366366 getDepsTerm vs bs cd (Bind n bdr body)
367367 -- here we just push IM.empty on the de bruijn stack
368368 -- the args will be marked as used at the usage site
369− | Lam ty <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
370− | Pi _ ty _ <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
369+ | Lam _ ty <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
370+ | Pi _ _ ty _ <- bdr = getDepsTerm vs ((n, const M.empty) : bs) cd body
371371
372372 -- let-bound variables can get partially evaluated
373373 -- it is sufficient just to plug the Cond in when the bound names are used
@@ -421,11 +421,11 @@ buildDepMap ci used externs ctx startNames
421421 V i -> snd (bs !! i) cd `union` unconditionalDeps args
422422
423423 -- we interpret applied lambdas as lets in order to reuse code here
424− Bind n (Lam ty) t -> getDepsTerm vs bs cd (lamToLet app)
424+ Bind n (Lam _ ty) t -> getDepsTerm vs bs cd (lamToLet app)
425425
426426 -- and we interpret applied lets as lambdas
427− Bind n ( Let ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam ty) t) t')
428− Bind n (NLet ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam ty) t) t')
427+ Bind n ( Let ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t')
428+ Bind n (NLet ty t') t -> getDepsTerm vs bs cd (App Complete (Bind n (Lam RigW ty) t) t')
429429
430430 Proj t i
431431 -> error $ "cannot[0] analyse projection !" ++ show i ++ " of " ++ show t
@@ -504,7 +504,7 @@ buildDepMap ci used externs ctx startNames
504504 (f, args) = unApply tm
505505
506506 lamToLet' :: [Term] -> Term -> Term
507− lamToLet' (v:vs) (Bind n (Lam ty) tm) = Bind n (Let ty v) $ lamToLet' vs tm
507+ lamToLet' (v:vs) (Bind n (Lam _ ty) tm) = Bind n (Let ty v) $ lamToLet' vs tm
508508 lamToLet' [] tm = tm
509509 lamToLet' vs tm = error $
510510 "Erasure.hs:lamToLet': unexpected input: "
@@ -512,7 +512,7 @@ buildDepMap ci used externs ctx startNames
512512
513513 -- split "\x_i -> T(x_i)" into [x_i] and T
514514 unfoldLams :: Term -> ([Name], Term)
515− unfoldLams (Bind n (Lam ty) t) = let (ns,t') = unfoldLams t in (n:ns, t')
515+ unfoldLams (Bind n (Lam _ ty) t) = let (ns,t') = unfoldLams t in (n:ns, t')
516516 unfoldLams t = ([], t)
517517
518518 union :: Deps -> Deps -> Deps
src/Idris/ErrReverse.hs+2−2
@@ -33,7 +33,7 @@ errReverse ist t = rewrite 5 t -- (elideLambdas t)
3333 -- Assume pattern bindings match in l and r (if they don't just treat
3434 -- the rule as invalid and return t)
3535
36− applyNames ns t (Bind n (PVar ty) scl) (Bind n' (PVar ty') scr)
36+ applyNames ns t (Bind n (PVar _ ty) scl) (Bind n' (PVar _ ty') scr)
3737 | n == n' = applyNames (n : ns) t (instantiate (P Ref n ty) scl)
3838 (instantiate (P Ref n' ty') scr)
3939 | otherwise = t
@@ -70,7 +70,7 @@ errReverse ist t = rewrite 5 t -- (elideLambdas t)
7070 -- it as it won't be very enlightening.
7171
7272 elideLambdas (App s f a) = App s (elideLambdas f) (elideLambdas a)
73− elideLambdas (Bind n (Lam t) sc)
73+ elideLambdas (Bind n (Lam _ t) sc)
7474 | size sc > 200 = P Ref (sUN "...") Erased
7575 elideLambdas (Bind n b sc)
7676 = Bind n (fmap elideLambdas b) (elideLambdas sc)
src/Idris/Error.hs+6
@@ -79,6 +79,12 @@ tclift (Error err@(At fc e)) = do setErrSpan fc; throwError err
7979tclift (Error err@(UniverseError fc _ _ _ _)) = do setErrSpan fc; throwError err
8080tclift (Error err) = throwError err
8181
82+tcliftAt :: FC -> TC a -> Idris a
83+tcliftAt fc (OK v) = return v
84+tcliftAt fc (Error err@(At _ e)) = do setErrSpan fc; throwError err
85+tcliftAt fc (Error err@(UniverseError _ _ _ _ _)) = do setErrSpan fc; throwError err
86+tcliftAt fc (Error err) = do setErrSpan fc; throwError (At fc err)
87+
8288tctry :: TC a -> TC a -> Idris a
8389tctry tc1 tc2
8490 = case tc1 of
src/Idris/IBC.hs+29−17
@@ -47,7 +47,7 @@ import System.Directory
4747import System.FilePath
4848
4949ibcVersion :: Word16
50−ibcVersion = 155
50+ibcVersion = 160
5151
5252-- | When IBC is being loaded - we'll load different things (and omit
5353-- different structures/definitions) depending on which phase we're in.
@@ -220,7 +220,9 @@ writeArchive fp i = do let a = L.foldl (\x y -> addEntryToArchive y x) emptyArch
220220
221221writeIBC :: FilePath -> FilePath -> Idris ()
222222writeIBC src f
223− = do logIBC 1 $ "Writing ibc " ++ show f
223+ = do
224+ logIBC 1 $ "Writing IBC for: " ++ show f
225+ iReport 2 $ "Writing IBC for: " ++ show f
224226 i <- getIState
225227-- case (Data.List.map fst (idris_metavars i)) \\ primDefs of
226228-- (_:_) -> ifail "Can't write ibc when there are unsolved metavariables"
@@ -313,7 +315,7 @@ ibc i (IBCCG n) f = case lookupCtxtExact n (idris_callgraph i) of
313315 _ -> ifail "IBC write failed"
314316ibc i (IBCCoercion n) f = return f { ibc_coercions = n : ibc_coercions f }
315317ibc i (IBCAccess n a) f = return f { ibc_access = (n,a) : ibc_access f }
316−ibc i (IBCFlags n) f
318+ibc i (IBCFlags n) f
317319 = case lookupCtxtExact n (idris_flags i) of
318320 Just a -> return f { ibc_flags = (n,a): ibc_flags f }
319321 _ -> ifail "IBC write failed"
@@ -1326,26 +1328,30 @@ instance Binary Static where
13261328instance Binary Plicity where
13271329 put x
13281330 = case x of
1329− Imp x1 x2 x3 x4 _ ->
1331+ Imp x1 x2 x3 x4 _ x5 ->
13301332 do putWord8 0
13311333 put x1
13321334 put x2
13331335 put x3
13341336 put x4
1335− Exp x1 x2 x3 ->
1337+ put x5
1338+ Exp x1 x2 x3 x4 ->
13361339 do putWord8 1
13371340 put x1
13381341 put x2
13391342 put x3
1340− Constraint x1 x2 ->
1343+ put x4
1344+ Constraint x1 x2 x3 ->
13411345 do putWord8 2
13421346 put x1
13431347 put x2
1344− TacImp x1 x2 x3 ->
1348+ put x3
1349+ TacImp x1 x2 x3 x4 ->
13451350 do putWord8 3
13461351 put x1
13471352 put x2
13481353 put x3
1354+ put x4
13491355 get
13501356 = do i <- getWord8
13511357 case i of
@@ -1353,18 +1359,22 @@ instance Binary Plicity where
13531359 x2 <- get
13541360 x3 <- get
13551361 x4 <- get
1356− return (Imp x1 x2 x3 x4 False)
1362+ x5 <- get
1363+ return (Imp x1 x2 x3 x4 False x5)
13571364 1 -> do x1 <- get
13581365 x2 <- get
13591366 x3 <- get
1360− return (Exp x1 x2 x3)
1367+ x4 <- get
1368+ return (Exp x1 x2 x3 x4)
13611369 2 -> do x1 <- get
13621370 x2 <- get
1363− return (Constraint x1 x2)
1371+ x3 <- get
1372+ return (Constraint x1 x2 x3)
13641373 3 -> do x1 <- get
13651374 x2 <- get
13661375 x3 <- get
1367− return (TacImp x1 x2 x3)
1376+ x4 <- get
1377+ return (TacImp x1 x2 x3 x4)
13681378 _ -> error "Corrupted binary data for Plicity"
13691379
13701380
@@ -2414,17 +2424,19 @@ instance Binary FnInfo where
24142424 return (FnInfo x1)
24152425
24162426instance Binary TypeInfo where
2417− put (TI x1 x2 x3 x4 x5) = do put x1
2418− put x2
2419− put x3
2420− put x4
2421− put x5
2427+ put (TI x1 x2 x3 x4 x5 x6) = do put x1
2428+ put x2
2429+ put x3
2430+ put x4
2431+ put x5
2432+ put x6
24222433 get = do x1 <- get
24232434 x2 <- get
24242435 x3 <- get
24252436 x4 <- get
24262437 x5 <- get
2427− return (TI x1 x2 x3 x4 x5)
2438+ x6 <- get
2439+ return (TI x1 x2 x3 x4 x5 x6)
24282440
24292441instance Binary SynContext where
24302442 put x
src/Idris/IdrisDoc.hs+2−2
@@ -19,7 +19,7 @@ import Idris.Docs
1919import Idris.Docstrings (nullDocstring)
2020import qualified Idris.Docstrings as Docstrings
2121import Idris.Parser.Helpers (opChars)
22−import IRTS.System (getDataFileName)
22+import IRTS.System (getIdrisDataFileByName)
2323
2424import Control.Applicative ((<|>))
2525import Control.Monad (forM_)
@@ -708,5 +708,5 @@ copyDependencies :: FilePath -- ^ The base directory to which
708708 -- dependencies should be written
709709 -> IO ()
710710copyDependencies dir =
711− do styles <- getDataFileName $ "idrisdoc" </> "styles.css"
711+ do styles <- getIdrisDataFileByName $ "idrisdoc" </> "styles.css"
712712 copyFile styles (dir </> "styles.css")
src/Idris/Info.hs+5
@@ -22,6 +22,7 @@ module Idris.Info
2222 , getIdrisHistoryFile
2323 , getIdrisInstalledPackages
2424 , getIdrisLoggingCategories
25+ , getIdrisDataFileByName
2526 ) where
2627
2728import Idris.AbsSyntax (loggingCatsStr)
@@ -34,6 +35,7 @@ import Version_idris (gitHash)
3435import Data.Version
3536import System.Directory
3637import System.FilePath
38+
3739getIdrisDataDir :: IO String
3840getIdrisDataDir = S.getIdrisDataDir
3941
@@ -88,3 +90,6 @@ getIdrisInstalledPackages = installedPackages
8890
8991getIdrisLoggingCategories :: IO [String]
9092getIdrisLoggingCategories = return $ words loggingCatsStr
93+
94+getIdrisDataFileByName :: String -> IO FilePath
95+getIdrisDataFileByName = S.getIdrisDataFileByName
src/Idris/Interactive.hs+8−8
@@ -390,10 +390,10 @@ makeLemma fn updatefile l n
390390 where getIndent s = length (takeWhile isSpace s)
391391
392392 appArgs skip 0 _ = ""
393− appArgs skip i (Bind n@(UN c) (Pi _ _ _) sc)
393+ appArgs skip i (Bind n@(UN c) (Pi _ _ _ _) sc)
394394 | (thead c /= '_' && n `notElem` skip)
395395 = " " ++ show n ++ appArgs skip (i - 1) sc
396− appArgs skip i (Bind _ (Pi _ _ _) sc) = appArgs skip (i - 1) sc
396+ appArgs skip i (Bind _ (Pi _ _ _ _) sc) = appArgs skip (i - 1) sc
397397 appArgs skip i _ = ""
398398
399399 stripMNBind _ args t | args <= 0 = stripImp t
@@ -416,7 +416,7 @@ makeLemma fn updatefile l n
416416 constraints i [n] ty = showSep ", " (showConstraints i [n] ty) ++ " => "
417417 constraints i ns ty = "(" ++ showSep ", " (showConstraints i ns ty) ++ ") => "
418418
419− showConstraints i ns (Bind n (Pi _ ty _) sc)
419+ showConstraints i ns (Bind n (Pi _ _ ty _) sc)
420420 | n `elem` ns = show (delab i ty) :
421421 showConstraints i ns (substV (P Bound n Erased) sc)
422422 | otherwise = showConstraints i ns (substV (P Bound n Erased) sc)
@@ -428,9 +428,9 @@ makeLemma fn updatefile l n
428428 -- Also, make interface implementations implicit
429429 guessImps :: IState -> Context -> Term -> [Name]
430430 -- machine names aren't lifted
431− guessImps ist ctxt (Bind n@(MN _ _) (Pi _ ty _) sc)
431+ guessImps ist ctxt (Bind n@(MN _ _) (Pi _ _ ty _) sc)
432432 = n : guessImps ist ctxt sc
433− guessImps ist ctxt (Bind n (Pi _ ty _) sc)
433+ guessImps ist ctxt (Bind n (Pi _ _ ty _) sc)
434434 | guarded ctxt n (substV (P Bound n Erased) sc)
435435 = n : guessImps ist ctxt sc
436436 | isInterface ist ty
@@ -441,7 +441,7 @@ makeLemma fn updatefile l n
441441 guessImps ist ctxt _ = []
442442
443443 paramty (TType _) = True
444− paramty (Bind _ (Pi _ (TType _) _) sc) = paramty sc
444+ paramty (Bind _ (Pi _ _ (TType _) _) sc) = paramty sc
445445 paramty _ = False
446446
447447 -- TMP HACK unusable name so don't lift
@@ -450,7 +450,7 @@ makeLemma fn updatefile l n
450450 _ -> False
451451
452452 guessInterfaces :: IState -> Context -> [Name] -> [Name] -> Term -> [Name]
453− guessInterfaces ist ctxt binders usednames (Bind n (Pi _ ty _) sc)
453+ guessInterfaces ist ctxt binders usednames (Bind n (Pi _ _ ty _) sc)
454454 | isParamInterface ist ty && any (\x -> elem x usednames)
455455 (paramNames binders ty)
456456 = n : guessInterfaces ist ctxt (n : binders) usednames sc
@@ -485,7 +485,7 @@ makeLemma fn updatefile l n
485485 isConName f ctxt = any (guarded ctxt n) args
486486-- guarded ctxt n (Bind (UN cn) (Pi t) sc) -- ignore shadows
487487-- | thead cn /= '_' = guarded ctxt n t || guarded ctxt n sc
488− guarded ctxt n (Bind _ (Pi _ t _) sc)
488+ guarded ctxt n (Bind _ (Pi _ _ t _) sc)
489489 = guarded ctxt n t || guarded ctxt n sc
490490 guarded ctxt n _ = False
491491
src/Idris/Main.hs+5−2
@@ -68,7 +68,6 @@ idrisMain opts =
6868 let nobanner = NoBanner `elem` opts
6969 let idesl = Idemode `elem` opts || IdemodeSocket `elem` opts
7070 let runrepl = not (NoREPL `elem` opts)
71− let verbose = runrepl || Verbose `elem` opts
7271 let output = opt getOutput opts
7372 let ibcsubdir = opt getIBCSubDir opts
7473 let importdirs = opt getImportDir opts
@@ -116,13 +115,16 @@ idrisMain opts =
116115 mapM_ addLangExt (opt getLanguageExt opts)
117116 setREPL runrepl
118117 setQuiet (quiet || isJust script || not (null immediate))
119− setVerbose verbose
118+
120119 setCmdLine opts
121120 setOutputTy outty
122121 setNoBanner nobanner
123122 setCodegen cgn
124123 mapM_ (addFlag cgn) cgFlags
125124 mapM_ makeOption opts
125+ vlevel <- verbose
126+ when (runrepl && vlevel == 0) $ setVerbose 1
127+
126128 -- if we have the --bytecode flag, drop into the bytecode assembler
127129 case bcs of
128130 [] -> return ()
@@ -215,6 +217,7 @@ idrisMain opts =
215217 where
216218 makeOption (OLogging i) = setLogLevel i
217219 makeOption (OLogCats cs) = setLogCats cs
220+ makeOption (Verbose v) = setVerbose v
218221 makeOption TypeCase = setTypeCase True
219222 makeOption TypeInType = setTypeInType True
220223 makeOption NoCoverage = setCoverage False
src/Idris/Package.hs+42−37
@@ -71,14 +71,14 @@ buildPkg copts warnonly (install, fp) = do
7171 make (makefile pkgdesc)
7272 case (execout pkgdesc) of
7373 Nothing -> do
74− case mergeOptions copts (idx : NoREPL : Verbose : idris_opts pkgdesc) of
74+ case mergeOptions copts (idx : NoREPL : Verbose 1 : idris_opts pkgdesc) of
7575 Left emsg -> do
7676 putStrLn emsg
7777 exitWith (ExitFailure 1)
7878 Right opts -> buildMods opts (modules pkgdesc)
7979 Just o -> do
8080 let exec = dir </> o
81− case mergeOptions copts (idx : NoREPL : Verbose : Output exec : idris_opts pkgdesc) of
81+ case mergeOptions copts (idx : NoREPL : Verbose 1 : Output exec : idris_opts pkgdesc) of
8282 Left emsg -> do
8383 putStrLn emsg
8484 exitWith (ExitFailure 1)
@@ -115,7 +115,7 @@ checkPkg copts warnonly quit fpath = do
115115 res <- inPkgDir pkgdesc $ do
116116 make (makefile pkgdesc)
117117
118− case mergeOptions copts (NoREPL : Verbose : idris_opts pkgdesc) of
118+ case mergeOptions copts (NoREPL : Verbose 1 : idris_opts pkgdesc) of
119119 Left emsg -> do
120120 putStrLn emsg
121121 exitWith (ExitFailure 1)
@@ -145,6 +145,7 @@ replPkg copts fp = do
145145 case mergeOptions copts (idris_opts pkgdesc) of
146146 Left emsg -> ifail emsg
147147 Right opts -> do
148+
148149 putIState orig
149150 dir <- runIO getCurrentDirectory
150151 runIO $ setCurrentDirectory $ dir </> sourcedir pkgdesc
@@ -194,7 +195,7 @@ documentPkg copts (install,fp) = do
194195 cd <- getCurrentDirectory
195196 let pkgDir = cd </> takeDirectory fp
196197 outputDir = cd </> pkgname pkgdesc ++ "_doc"
197− popts = NoREPL : Verbose : idris_opts pkgdesc
198+ popts = NoREPL : Verbose 1 : idris_opts pkgdesc
198199 mods = modules pkgdesc
199200 fs = map (foldl1' (</>) . splitOn "." . showCG) mods
200201 setCurrentDirectory $ pkgDir </> sourcedir pkgdesc
@@ -237,42 +238,45 @@ documentPkg copts (install,fp) = do
237238-- | Build a package with a sythesized main function that runs the tests
238239testPkg :: [Opt] -- ^ Command line options.
239240 -> FilePath -- ^ Path to ipkg file.
240− -> IO ()
241+ -> IO ExitCode
241242testPkg copts fp = do
242243 pkgdesc <- parseDesc fp
243244 ok <- mapM (testLib True (pkgname pkgdesc)) (libdeps pkgdesc)
244− when (and ok) $ do
245− m_ist <- inPkgDir pkgdesc $ do
246− make (makefile pkgdesc)
247− -- Get a temporary file to save the tests' source in
248− (tmpn, tmph) <- tempfile ".idr"
249− hPutStrLn tmph $
250− "module Test_______\n" ++
251− concat ["import " ++ show m ++ "\n" | m <- modules pkgdesc]
252− ++ "namespace Main\n"
253− ++ " main : IO ()\n"
254− ++ " main = do "
255− ++ concat [ show t ++ "\n "
256− | t <- idris_tests pkgdesc]
257− hClose tmph
258− (tmpn', tmph') <- tempfile ""
259− hClose tmph'
260− let popts = (Filename tmpn : NoREPL : Verbose : Output tmpn' : idris_opts pkgdesc)
261− case mergeOptions copts popts of
262− Left emsg -> do
263− putStrLn emsg
264− exitWith (ExitFailure 1)
265− Right opts -> do
266− m_ist <- idris opts
267− rawSystem tmpn' []
268− return m_ist
269− case m_ist of
270− Nothing -> exitWith (ExitFailure 1)
271− Just ist -> do
272− -- Quit with error code if problem building
273− case errSpan ist of
274− Just _ -> exitWith (ExitFailure 1)
275− _ -> return ()
245+ if and ok
246+ then do
247+ (m_ist, exitCode) <- inPkgDir pkgdesc $ do
248+ make (makefile pkgdesc)
249+ -- Get a temporary file to save the tests' source in
250+ (tmpn, tmph) <- tempfile ".idr"
251+ hPutStrLn tmph $
252+ "module Test_______\n" ++
253+ concat ["import " ++ show m ++ "\n" | m <- modules pkgdesc]
254+ ++ "namespace Main\n"
255+ ++ " main : IO ()\n"
256+ ++ " main = do "
257+ ++ concat [ show t ++ "\n "
258+ | t <- idris_tests pkgdesc]
259+ hClose tmph
260+ (tmpn', tmph') <- tempfile ""
261+ hClose tmph'
262+ let popts = (Filename tmpn : NoREPL : Verbose 1 : Output tmpn' : idris_opts pkgdesc)
263+ case mergeOptions copts popts of
264+ Left emsg -> do
265+ putStrLn emsg
266+ exitWith (ExitFailure 1)
267+ Right opts -> do
268+ m_ist <- idris opts
269+ let texe = if isWindows then addExtension tmpn' ".exe" else tmpn'
270+ exitCode <- rawSystem texe []
271+ return (m_ist, exitCode)
272+ case m_ist of
273+ Nothing -> exitWith (ExitFailure 1)
274+ Just ist -> do
275+ -- Quit with error code if problem building
276+ case errSpan ist of
277+ Just _ -> exitWith (ExitFailure 1)
278+ _ -> return exitCode
279+ else return (ExitFailure 1)
276280
277281-- ----------------------------------------------------------- [ Installation ]
278282
@@ -438,6 +442,7 @@ mergeOptions copts popts =
438442 chkOpt o@(IBCSubDir _) = Right o
439443 chkOpt o@(ImportDir _ ) = Right o
440444 chkOpt o@(UseCodegen _) = Right o
445+ chkOpt o@(Verbose _) = Right o
441446 chkOpt o = Left (unwords ["\t", show o, "\n"])
442447
443448 genErrMsg :: [String] -> String
src/Idris/Parser.hs+15−8
@@ -763,7 +763,7 @@ Params ::=
763763params :: SyntaxInfo -> IdrisParser [PDecl]
764764params syn =
765765 do reservedHL "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')'
766− let ns' = [(n, ty) | (n, _, ty) <- ns]
766+ let ns' = [(n, ty) | (_, n, _, ty) <- ns]
767767 openBlock
768768 let pvars = syn_params syn
769769 ds <- many (decl syn { syn_params = pvars ++ ns' })
@@ -903,7 +903,7 @@ interface_ syn = do (doc, argDocs, acc)
903903 return (doc, argDocs, acc))
904904 fc <- getFC
905905 cons <- constraintList syn
906− let cons' = [(c, ty) | (c, _, ty) <- cons]
906+ let cons' = [(c, ty) | (_, c, _, ty) <- cons]
907907 (n_in, nfc) <- fnName
908908 let n = expandNS syn n_in
909909 cs <- many carg
@@ -953,11 +953,11 @@ implementation kwopt syn
953953 fc <- getFC
954954 en <- optional implementationName
955955 cs <- constraintList syn
956− let cs' = [(c, ty) | (c, _, ty) <- cs]
956+ let cs' = [(c, ty) | (_, c, _, ty) <- cs]
957957 (cn, cnfc) <- fnName
958958 args <- many (simpleExpr syn)
959959 let sc = PApp fc (PRef cnfc [cnfc] cn) (map pexp args)
960− let t = bindList (PPi constraint) cs sc
960+ let t = bindList (\r -> PPi constraint { pcount = r }) cs sc
961961 pnames <- implementationUsing
962962 ds <- implementationBlock syn
963963 return [PImplementation doc argDocs syn fc cs' pnames acc opts cn cnfc args [] t en ds]
@@ -1429,6 +1429,11 @@ directive syn = do try (lchar '%' *> reserved "lib")
14291429pLangExt :: IdrisParser LanguageExt
14301430pLangExt = (reserved "TypeProviders" >> return TypeProviders)
14311431 <|> (reserved "ErrorReflection" >> return ErrorReflection)
1432+ <|> (reserved "UniquenessTypes" >> return UniquenessTypes)
1433+ <|> (reserved "LinearTypes" >> return LinearTypes)
1434+ <|> (reserved "DSLNotation" >> return DSLNotation)
1435+ <|> (reserved "ElabReflection" >> return ElabReflection)
1436+ <|> (reserved "FirstClassReflection" >> return FCReflection)
14321437
14331438{-| Parses a totality
14341439
@@ -1696,6 +1701,7 @@ loadSource' lidr r maxline
16961701loadSource :: Bool -> FilePath -> Maybe Int -> Idris ()
16971702loadSource lidr f toline
16981703 = do logParser 1 ("Reading " ++ f)
1704+ iReport 2 ("Reading " ++ f)
16991705 i <- getIState
17001706 let def_total = default_total i
17011707 file_in <- runIO $ readSource f
@@ -1783,8 +1789,7 @@ loadSource lidr f toline
17831789 logLvl 10 (show (toAlist (idris_implicits i)))
17841790 logLvl 3 (show (idris_infixes i))
17851791 -- Now add all the declarations to the context
1786− v <- verbose
1787− when v $ iputStrLn $ "Type checking " ++ f
1792+ iReport 1 $ "Type checking " ++ f
17881793 -- we totality check after every Mutual block, so if
17891794 -- anything is a single definition, wrap it in a
17901795 -- mutual block on its own
@@ -1799,7 +1804,8 @@ loadSource lidr f toline
17991804 setContext ctxt')
18001805 (map snd (idris_totcheck i))
18011806 -- build size change graph from simplified definitions
1802− logLvl 1 "Totality checking"
1807+ iReport 3 $ "Totality checking " ++ f
1808+ logLvl 1 $ "Totality checking " ++ f
18031809 i <- getIState
18041810 mapM_ buildSCG (idris_totcheck i)
18051811 mapM_ checkDeclTotality (idris_totcheck i)
@@ -1822,7 +1828,8 @@ loadSource lidr f toline
18221828
18231829 logLvl 1 ("Finished " ++ f)
18241830 ibcsd <- valIBCSubDir i
1825− logLvl 1 "Universe checking"
1831+ logLvl 1 $ "Universe checking " ++ f
1832+ iReport 3 $ "Universe checking " ++ f
18261833 iucheck
18271834 let ibc = ibcPathNoFallback ibcsd f
18281835 i <- getIState
src/Idris/Parser/Expr.hs+31−27
@@ -261,8 +261,8 @@ updateSynMatch = update
261261 updTactic ns (TDocStr (Left n)) = TDocStr . Left . fst $ updateB ns (n, NoFC)
262262 updTactic ns t = fmap (update ns) t
263263
264− updTacImp ns (TacImp o st scr) = TacImp o st (update ns scr)
265− updTacImp _ x = x
264+ updTacImp ns (TacImp o st scr r) = TacImp o st (update ns scr) r
265+ updTacImp _ x = x
266266
267267 dropn :: Name -> [(Name, a)] -> [(Name, a)]
268268 dropn n [] = []
@@ -914,7 +914,7 @@ TypeExpr ::= ConstraintList? Expr;
914914typeExpr :: SyntaxInfo -> IdrisParser PTerm
915915typeExpr syn = do cs <- if implicitAllowed syn then constraintList syn else return []
916916 sc <- expr (allowConstr syn)
917− return (bindList (PPi constraint) cs sc)
917+ return (bindList (\r -> PPi (constraint { pcount = r })) cs sc)
918918 <?> "type signature"
919919
920920{- | Parses a lambda expression
@@ -941,7 +941,7 @@ lambda syn = do lchar '\\' <?> "lambda expression"
941941 ((do xt <- try $ tyOptDeclList (disallowImp syn)
942942 fc <- getFC
943943 sc <- lambdaTail
944− return (bindList (PLam fc) xt sc))
944+ return (bindList (\r -> PLam fc) xt sc))
945945 <|>
946946 (do ps <- sepBy (do fc <- getFC
947947 e <- simpleExpr (disallowImp (syn { inPattern = True }))
@@ -1072,13 +1072,13 @@ Pi' ::=
10721072
10731073bindsymbol opts st syn
10741074 = do symbol "->"
1075− return (Exp opts st False)
1075+ return (Exp opts st False RigW)
10761076
10771077explicitPi opts st syn
10781078 = do xt <- try (lchar '(' *> typeDeclList syn <* lchar ')')
10791079 binder <- bindsymbol opts st syn
10801080 sc <- expr (allowConstr syn)
1081− return (bindList (PPi binder) xt sc)
1081+ return (bindList (\r -> PPi (binder { pcount = r })) xt sc)
10821082
10831083autoImplicit opts st syn
10841084 = do kw <- reservedFC "auto"
@@ -1088,8 +1088,8 @@ autoImplicit opts st syn
10881088 symbol "->"
10891089 sc <- expr (allowConstr syn)
10901090 highlightP kw AnnKeyword
1091− return (bindList (PPi
1092− (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]))) xt sc)
1091+ return (bindList (\r -> PPi
1092+ (TacImp [] Dynamic (PTactics [ProofSearch True True 100 Nothing [] []]) r)) xt sc)
10931093
10941094defaultImplicit opts st syn = do
10951095 kw <- reservedFC "default"
@@ -1102,7 +1102,7 @@ defaultImplicit opts st syn = do
11021102 symbol "->"
11031103 sc <- expr (allowConstr syn)
11041104 highlightP kw AnnKeyword
1105− return (bindList (PPi (TacImp [] Dynamic script)) xt sc)
1105+ return (bindList (\r -> PPi (TacImp [] Dynamic script r)) xt sc)
11061106
11071107normalImplicit opts st syn = do
11081108 xt <- typeDeclList syn <* lchar '}'
@@ -1111,19 +1111,19 @@ normalImplicit opts st syn = do
11111111 sc <- expr syn
11121112 let (im,cl)
11131113 = if implicitAllowed syn
1114− then (Imp opts st False (Just (Impl False True False)) True,
1114+ then (Imp opts st False (Just (Impl False True False)) True RigW,
11151115 constraint)
1116− else (Imp opts st False (Just (Impl False False False)) True,
1117− Imp opts st False (Just (Impl True False False)) True)
1118− return (bindList (PPi im) xt
1119− (bindList (PPi cl) cs sc))
1116+ else (Imp opts st False (Just (Impl False False False)) True RigW,
1117+ Imp opts st False (Just (Impl True False False)) True RigW)
1118+ return (bindList (\r -> PPi (im { pcount = r })) xt
1119+ (bindList (\r -> PPi (cl { pcount = r })) cs sc))
11201120
11211121constraintPi opts st syn =
11221122 do cs <- constraintList1 syn
11231123 sc <- expr syn
11241124 if implicitAllowed syn
1125− then return (bindList (PPi constraint) cs sc)
1126− else return (bindList (PPi (Imp opts st False (Just (Impl True False False)) True))
1125+ then return (bindList (\r -> PPi constraint { pcount = r }) cs sc)
1126+ else return (bindList (\r -> PPi (Imp opts st False (Just (Impl True False False)) True r))
11271127 cs sc)
11281128
11291129implicitPi opts st syn =
@@ -1181,11 +1181,11 @@ ConstraintList ::=
11811181 ;
11821182@
11831183-}
1184−constraintList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)]
1184+constraintList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]
11851185constraintList syn = try (constraintList1 syn)
11861186 <|> return []
11871187
1188−constraintList1 :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)]
1188+constraintList1 :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]
11891189constraintList1 syn = try (do lchar '('
11901190 tys <- sepBy1 nexpr (lchar ',')
11911191 lchar ')'
@@ -1193,13 +1193,13 @@ constraintList1 syn = try (do lchar '('
11931193 return tys)
11941194 <|> try (do t <- opExpr (disallowImp syn)
11951195 reservedOp "=>"
1196− return [(defname, NoFC, t)])
1196+ return [(RigW, defname, NoFC, t)])
11971197 <?> "type constraint list"
11981198 where nexpr = try (do (n, fc) <- name; lchar ':'
11991199 e <- expr (disallowImp syn)
1200− return (n, fc, e))
1200+ return (RigW, n, fc, e))
12011201 <|> do e <- expr (disallowImp syn)
1202− return (defname, NoFC, e)
1202+ return (RigW, defname, NoFC, e)
12031203 defname = sMN 0 "constraint"
12041204
12051205{- | Parses a type declaration list
@@ -1217,17 +1217,21 @@ FunctionSignatureList ::=
12171217 ;
12181218@
12191219-}
1220−typeDeclList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)]
1221−typeDeclList syn = try (sepBy1 (do (x, xfc) <- fnName
1220+typeDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]
1221+typeDeclList syn = try (sepBy1 (do rig <- option RigW rigCount
1222+ (x, xfc) <- fnName
12221223 lchar ':'
12231224 t <- typeExpr (disallowImp syn)
1224− return (x, xfc, t))
1225+ return (rig, x, xfc, t))
12251226 (lchar ','))
12261227 <|> do ns <- sepBy1 name (lchar ',')
12271228 lchar ':'
12281229 t <- typeExpr (disallowImp syn)
1229− return (map (\(x, xfc) -> (x, xfc, t)) ns)
1230+ return (map (\(x, xfc) -> (RigW, x, xfc, t)) ns)
12301231 <?> "type declaration list"
1232+ where
1233+ rigCount = do lchar '1'; return Rig1
1234+ <|> do lchar '0'; return Rig0
12311235
12321236{- | Parses a type declaration list with optional parameters
12331237@
@@ -1241,11 +1245,11 @@ TypeOptDeclList ::=
12411245NameOrPlaceHolder ::= Name | '_';
12421246@
12431247-}
1244−tyOptDeclList :: SyntaxInfo -> IdrisParser [(Name, FC, PTerm)]
1248+tyOptDeclList :: SyntaxInfo -> IdrisParser [(RigCount, Name, FC, PTerm)]
12451249tyOptDeclList syn = sepBy1 (do (x, fc) <- nameOrPlaceholder
12461250 t <- option Placeholder (do lchar ':'
12471251 expr syn)
1248− return (x, fc, t))
1252+ return (RigW, x, fc, t))
12491253 (lchar ',')
12501254 <?> "type declaration list"
12511255 where nameOrPlaceholder :: IdrisParser (Name, FC)
src/Idris/Parser/Helpers.hs+3−3
@@ -455,9 +455,9 @@ getFC = do s <- position
455455
456456{-* Syntax helpers-}
457457-- | Bind constraints to term
458−bindList :: (Name -> FC -> PTerm -> PTerm -> PTerm) -> [(Name, FC, PTerm)] -> PTerm -> PTerm
459−bindList b [] sc = sc
460−bindList b ((n, fc, t):bs) sc = b n fc t (bindList b bs sc)
458+bindList :: (RigCount -> Name -> FC -> PTerm -> PTerm -> PTerm) -> [(RigCount, Name, FC, PTerm)] -> PTerm -> PTerm
459+bindList b [] sc = sc
460+bindList b ((r, n, fc, t):bs) sc = b r n fc t (bindList b bs sc)
461461
462462{- | @commaSeparated p@ parses one or more occurences of `p`,
463463 separated by commas and optional whitespace. -}
src/Idris/PartialEval.hs+14−14
@@ -97,37 +97,37 @@ specType args ty = let (t, args') = runState (unifyEq args ty) [] in
9797 where
9898 -- Specialise static argument in type by let-binding provided value instead
9999 -- of expecting it as a function argument
100− st ((ExplicitS, v) : xs) (Bind n (Pi _ t _) sc)
100+ st ((ExplicitS, v) : xs) (Bind n (Pi _ _ t _) sc)
101101 = Bind n (Let t v) (st xs sc)
102− st ((ImplicitS _, v) : xs) (Bind n (Pi _ t _) sc)
102+ st ((ImplicitS _, v) : xs) (Bind n (Pi _ _ t _) sc)
103103 = Bind n (Let t v) (st xs sc)
104− st ((ConstraintS, v) : xs) (Bind n (Pi _ t _) sc)
104+ st ((ConstraintS, v) : xs) (Bind n (Pi _ _ t _) sc)
105105 = Bind n (Let t v) (st xs sc)
106106 -- Erase argument from function type
107− st ((UnifiedD, _) : xs) (Bind n (Pi _ t _) sc)
107+ st ((UnifiedD, _) : xs) (Bind n (Pi _ _ t _) sc)
108108 = st xs sc
109109 -- Keep types as is
110− st (_ : xs) (Bind n (Pi i t k) sc)
111− = Bind n (Pi i t k) (st xs sc)
110+ st (_ : xs) (Bind n (Pi rig i t k) sc)
111+ = Bind n (Pi rig i t k) (st xs sc)
112112 st _ t = t
113113
114114 -- Erase implicit dynamic argument if existing argument shares it value,
115115 -- by substituting the value of previous argument
116− unifyEq (imp@(ImplicitD _, v) : xs) (Bind n (Pi i t k) sc)
116+ unifyEq (imp@(ImplicitD _, v) : xs) (Bind n (Pi rig i t k) sc)
117117 = do amap <- get
118118 case lookup imp amap of
119119 Just n' ->
120120 do put (amap ++ [((UnifiedD, Erased), n)])
121121 sc' <- unifyEq xs (subst n (P Bound n' Erased) sc)
122− return (Bind n (Pi i t k) sc') -- erase later
122+ return (Bind n (Pi rig i t k) sc') -- erase later
123123 _ -> do put (amap ++ [(imp, n)])
124124 sc' <- unifyEq xs sc
125− return (Bind n (Pi i t k) sc')
126− unifyEq (x : xs) (Bind n (Pi i t k) sc)
125+ return (Bind n (Pi rig i t k) sc')
126+ unifyEq (x : xs) (Bind n (Pi rig i t k) sc)
127127 = do args <- get
128128 put (args ++ [(x, n)])
129129 sc' <- unifyEq xs sc
130− return (Bind n (Pi i t k) sc')
130+ return (Bind n (Pi rig i t k) sc')
131131 unifyEq xs t = do args <- get
132132 put (args ++ (zip xs (repeat (sUN "_"))))
133133 return t
@@ -141,13 +141,13 @@ specType args ty = let (t, args') = runState (unifyEq args ty) [] in
141141mkPE_TyDecl :: IState -> [(PEArgType, Term)] -> Type -> PTerm
142142mkPE_TyDecl ist args ty = mkty args ty
143143 where
144− mkty ((ExplicitD, v) : xs) (Bind n (Pi _ t k) sc)
144+ mkty ((ExplicitD, v) : xs) (Bind n (Pi rig _ t k) sc)
145145 = PPi expl n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
146− mkty ((ConstraintD, v) : xs) (Bind n (Pi _ t k) sc)
146+ mkty ((ConstraintD, v) : xs) (Bind n (Pi rig _ t k) sc)
147147 | concreteInterface ist t = mkty xs sc
148148 | interfaceConstraint ist t
149149 = PPi constraint n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
150− mkty ((ImplicitD _, v) : xs) (Bind n (Pi _ t k) sc)
150+ mkty ((ImplicitD _, v) : xs) (Bind n (Pi rig _ t k) sc)
151151 = PPi impl n NoFC (delab ist (generaliseIn t)) (mkty xs sc)
152152
153153 mkty (_ : xs) t
src/Idris/Primitives.hs+5−5
@@ -32,7 +32,7 @@ data Prim = Prim { p_name :: Name,
3232
3333ty :: [Const] -> Const -> Type
3434ty [] x = Constant x
35−ty (t:ts) x = Bind (sMN 0 "T") (Pi Nothing (Constant t) (TType (UVar [] (-3)))) (ty ts x)
35+ty (t:ts) x = Bind (sMN 0 "T") (Pi RigW Nothing (Constant t) (TType (UVar [] (-3)))) (ty ts x)
3636
3737total, partial, iopartial :: Totality
3838total = Total []
@@ -455,8 +455,8 @@ getInt _ = []
455455
456456strToInt :: IntTy -> [Const] -> Maybe Const
457457strToInt ity [Str x] = case reads x of
458− [(n,"")] -> Just $ toInt ity (n :: Integer)
459− _ -> Just $ I 0
458+ [(n,s)] -> Just $ if all isSpace s then toInt ity (n :: Integer) else I 0
459+ _ -> Just $ I 0
460460strToInt _ _ = Nothing
461461
462462intToFloat :: [Const] -> Maybe Const
@@ -481,8 +481,8 @@ c_floatToStr :: [Const] -> Maybe Const
481481c_floatToStr [Fl x] = Just $ Str (show x)
482482c_floatToStr _ = Nothing
483483c_strToFloat [Str x] = case reads x of
484− [(n,"")] -> Just $ Fl n
485− _ -> Just $ Fl 0
484+ [(n,s)] -> Just $ Fl (if all isSpace s then n else 0)
485+ _ -> Just $ Fl 0
486486c_strToFloat _ = Nothing
487487
488488p_fPrim :: (Double -> Double) -> [Const] -> Maybe Const
src/Idris/ProofSearch.hs+8−8
@@ -49,7 +49,7 @@ trivialHoles psnames ok elab ist
4949 return ()) True
5050 where
5151 tryAll [] = fail "No trivial solution"
52− tryAll ((x, b):xs)
52+ tryAll ((x, _, b):xs)
5353 = do -- if type of x has any holes in it, move on
5454 hs <- get_holes
5555 let badhs = hs -- filter (flip notElem holesOK) hs
@@ -85,7 +85,7 @@ trivialTCs ok elab ist
8585 return ()) True
8686 where
8787 tryAll [] = fail "No trivial solution"
88− tryAll ((x, b):xs)
88+ tryAll ((x, _, b):xs)
8989 = do -- if type of x has any holes in it, move on
9090 hs <- get_holes
9191 let badhs = hs -- filter (flip notElem holesOK) hs
@@ -123,7 +123,7 @@ cantSolveGoal :: ElabD a
123123cantSolveGoal = do g <- goal
124124 env <- get_env
125125 lift $ tfail $
126− CantSolveGoal g (map (\(n,b) -> (n, binderTy b)) env)
126+ CantSolveGoal g (map (\(n,_,b) -> (n, binderTy b)) env)
127127
128128proofSearch :: Bool -- ^ recursive search (False for 'refine')
129129 -> Bool -- ^ invoked from a tactic proof. If so, making new metavariables is meaningless, and there should be an error reported instead.
@@ -300,7 +300,7 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot psnames hi
300300 tryLocals d locs tys env
301301
302302 tryLocals d locs tys [] = fail "Locals failed"
303− tryLocals d locs tys ((x, t) : xs)
303+ tryLocals d locs tys ((x, _, t) : xs)
304304 | x `elem` locs || x `notElem` psnames = tryLocals d locs tys xs
305305 | otherwise = try' (tryLocal d (x : locs) tys x t)
306306 (tryLocals d locs tys xs) True
@@ -346,7 +346,7 @@ proofSearch rec fromProver ambigok deferonfail maxDepth elab fn nroot psnames hi
346346 TermPart ty,
347347 TextPart "using proof search, but proof search only works on datatypes with constructors."] ++
348348 case ty of
349− (Bind _ (Pi _ _ _) _) -> [TextPart "In particular, function types are not supported."]
349+ (Bind _ (Pi _ _ _ _) _) -> [TextPart "In particular, function types are not supported."]
350350 _ -> []
351351
352352-- | Resolve interfaces. This will only pick up 'normal'
@@ -475,9 +475,9 @@ resTC' tcs defaultOn openOK topholes depth topg fn elab ist
475475
476476 introImps = do g <- goal
477477 case g of
478− (Bind _ (Pi _ _ _) sc) -> do attack; intro Nothing
479− num <- introImps
480− return (num + 1)
478+ (Bind _ (Pi _ _ _ _) sc) -> do attack; intro Nothing
479+ num <- introImps
480+ return (num + 1)
481481 _ -> return 0
482482
483483 solven n = replicateM_ n solve
src/Idris/Prover.hs+12−12
@@ -82,8 +82,8 @@ assumptionNames e
8282 = case envAtFocus (proof e) of
8383 OK env -> names env
8484 where names [] = []
85− names ((MN _ _, _) : bs) = names bs
86− names ((n, _) : bs) = show n : names bs
85+ names ((MN _ _, _, _) : bs) = names bs
86+ names ((n, _, _) : bs) = show n : names bs
8787
8888prove :: Bool -> ElabInfo -> Ctxt OptInfo -> Context -> Bool -> Name -> Type -> Idris ()
8989prove mode info opt ctxt lit n ty
@@ -174,18 +174,18 @@ dumpState ist inElab menv ps | (h : hs) <- holes ps = do
174174 delab ist t
175175
176176 assumptionNames :: Env -> [Name]
177− assumptionNames = map fst
177+ assumptionNames = map fstEnv
178178
179179 prettyPs :: Bool -> Binder Type -> [(Name, Bool)] -> Env -> Doc OutputAnnotation
180180 prettyPs all g bnd [] = empty
181− prettyPs all g bnd ((n@(MN _ r), _) : bs)
181+ prettyPs all g bnd ((n@(MN _ r), _, _) : bs)
182182 | not all && r == txt "rewrite_rule" = prettyPs all g ((n, False):bnd) bs
183− prettyPs all g bnd ((n@(MN _ _), _) : bs)
183+ prettyPs all g bnd ((n@(MN _ _), _, _) : bs)
184184 | not (all || n `elem` freeEnvNames bs || n `elem` goalNames g) = prettyPs all g bnd bs
185− prettyPs all g bnd ((n, Let t v) : bs) =
185+ prettyPs all g bnd ((n, _, Let t v) : bs) =
186186 line <> bindingOf n False <+> text "=" <+> tPretty bnd v <+> colon <+>
187187 align (tPretty bnd t) <> prettyPs all g ((n, False):bnd) bs
188− prettyPs all g bnd ((n, b) : bs) =
188+ prettyPs all g bnd ((n, _, b) : bs) =
189189 line <> bindingOf n False <+> colon <+>
190190 align (tPretty bnd (binderTy b)) <> prettyPs all g ((n, False):bnd) bs
191191
@@ -227,7 +227,7 @@ dumpState ist inElab menv ps | (h : hs) <- holes ps = do
227227 nest nestingSize (align . cat . punctuate (text ",") . map (`bindingOf` False) $ hs)
228228
229229 freeEnvNames :: Env -> [Name]
230− freeEnvNames = concatMap (\(n, b) -> freeNames (Bind n b Erased))
230+ freeEnvNames = concatMap (\(n, _, b) -> freeNames (Bind n b Erased))
231231
232232lifte :: ElabState EState -> ElabD a -> Idris a
233233lifte st e = do (v, _) <- elabStep st e
@@ -468,7 +468,7 @@ ploop fn d prompt prf e h
468468 (ploop fn d prompt prf e h')
469469
470470
471−envCtxt env ctxt = foldl (\c (n, b) -> addTyDecl n Bound (binderTy b) c) ctxt env
471+envCtxt env ctxt = foldl (\c (n, _, b) -> addTyDecl n Bound (binderTy b) c) ctxt env
472472
473473checkNameType :: ElabState EState -> [String] -> Name -> Idris (Bool, ElabState EState, Bool, [String], Either Err (Idris ()))
474474checkNameType e prf n = do
@@ -478,7 +478,7 @@ checkNameType e prf n = do
478478 idrisCatch (do
479479 let OK env = envAtFocus (proof e)
480480 ctxt' = envCtxt env ctxt
481− bnd = map (\x -> (fst x, False)) env
481+ bnd = map (\x -> (fstEnv x, False)) env
482482 ist' = ist { tt_ctxt = ctxt' }
483483 putIState ist'
484484 -- Unlike the REPL, metavars have no special treatment, to
@@ -505,7 +505,7 @@ checkType e prf t = do
505505 action = case tm of
506506 TType _ ->
507507 iPrintTermWithType (prettyImp ppo (PType emptyFC)) type1Doc
508− _ -> let bnd = map (\x -> (fst x, False)) env in
508+ _ -> let bnd = map (\x -> (fstEnv x, False)) env in
509509 iPrintTermWithType (pprintPTerm ppo bnd [] infixes (delab ist tm))
510510 (pprintPTerm ppo bnd [] infixes (delab ist ty))
511511 putIState ist
@@ -522,7 +522,7 @@ evalTerm e prf t = withErrorReflection $
522522 let OK env = envAtFocus (proof e)
523523 ctxt' = envCtxt env ctxt
524524 ist' = ist { tt_ctxt = ctxt' }
525− bnd = map (\x -> (fst x, False)) env
525+ bnd = map (\x -> (fstEnv x, False)) env
526526 putIState ist'
527527 (tm, ty) <- elabVal (recinfo proverfc) ERHS t
528528 let tm' = force (normaliseAll ctxt' env tm)
src/Idris/REPL.hs+25−15
@@ -194,7 +194,7 @@ processNetCmd orig i h fn cmd
194194 setErrContext True
195195 setOutH h
196196 setQuiet True
197− setVerbose False
197+ setVerbose 0
198198 mods <- loadInputs [f] toline
199199 ist <- getIState
200200 return (ist, f)
@@ -396,10 +396,15 @@ runIdeModeCommand h id orig fn mods (IdeMode.SetOpt IdeMode.ErrContext b) =
396396 runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id
397397runIdeModeCommand h id orig fn mods (IdeMode.Metavariables cols) =
398398 do ist <- getIState
399− let mvs = reverse $ map fst (idris_metavars ist) \\ primDefs
399+ let mvs = reverse $ [ (n, i)
400+ | (n, (_, i, _, _, _)) <- idris_metavars ist
401+ , not (n `elem` primDefs)
402+ ]
400403 let ppo = ppOptionIst ist
401404 -- splitMvs is a list of pairs of names and their split types
402− let splitMvs = mapSnd (splitPi ist) (mvTys ist mvs)
405+ let splitMvs = [ (n, (premises, concl, tm))
406+ | (n, i, ty) <- mvTys ist mvs
407+ , let (premises, concl, tm) = splitPi ist i ty]
403408 -- mvOutput is the pretty-printed version ready for conversion to SExpr
404409 let mvOutput = map (\(n, (hs, c)) -> (n, hs, c)) $
405410 mapPair show
@@ -413,20 +418,24 @@ runIdeModeCommand h id orig fn mods (IdeMode.Metavariables cols) =
413418 runIO . hPutStrLn h $
414419 IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", mvOutput) id
415420 where mapPair f g xs = zip (map (f . fst) xs) (map (g . snd) xs)
416− mapSnd f xs = zip (map fst xs) (map (f . snd) xs)
421+ firstOfThree (x, y, z) = x
422+ mapThird f xs = map (\(x, y, z) -> (x, y, f z)) xs
417423
418424 -- | Split a function type into a pair of premises, conclusion.
419425 -- Each maintains both the original and delaborated versions.
420− splitPi :: IState -> Type -> ([(Name, Type, PTerm)], Type, PTerm)
421− splitPi ist (Bind n (Pi _ t _) rest) =
422− let (hs, c, pc) = splitPi ist rest in
426+ splitPi :: IState -> Int -> Type -> ([(Name, Type, PTerm)], Type, PTerm)
427+ splitPi ist i (Bind n (Pi _ _ t _) rest) | i > 0 =
428+ let (hs, c, pc) = splitPi ist (i - 1) rest in
423429 ((n, t, delabTy' ist [] t False False True):hs,
424430 c, delabTy' ist [] c False False True)
425− splitPi ist tm = ([], tm, delabTy' ist [] tm False False True)
431+ splitPi ist i tm = ([], tm, delabTy' ist [] tm False False True)
426432
427433 -- | Get the types of a list of metavariable names
428− mvTys :: IState -> [Name] -> [(Name, Type)]
429− mvTys ist = mapSnd vToP . mapMaybe (flip lookupTyNameExact (tt_ctxt ist))
434+ mvTys :: IState -> [(Name, Int)] -> [(Name, Int, Type)]
435+ mvTys ist mvs = [ (n, i, ty)
436+ | (n, i) <- mvs
437+ , ty <- maybeToList (fmap (vToP . snd) (lookupTyNameExact n (tt_ctxt ist)))
438+ ]
430439
431440 -- | Show a type and its corresponding PTerm in a format suitable
432441 -- for the IDE - that is, pretty-printed and annotated.
@@ -1215,8 +1224,10 @@ process fn (WHNF t)
12151224 = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t
12161225 ctxt <- getContext
12171226 ist <- getIState
1218− let tm' = whnf ctxt tm
1219− iPrintResult (show (delab ist tm'))
1227+ let tm' = whnf ctxt [] tm
1228+ let tmArgs' = whnfArgs ctxt [] tm
1229+ iPrintResult $ "WHNF: " ++ (show (delab ist tm'))
1230+ iPrintResult $ "WHNF args: " ++ (show (delab ist tmArgs'))
12201231process fn (TestInline t)
12211232 = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t
12221233 ctxt <- getContext
@@ -1271,7 +1282,7 @@ process fn (Missing n)
12711282 case lookupCtxt n (idris_patdefs i) of
12721283 [] -> iPrintError $ "Unknown name " ++ show n
12731284 [(_, tms)] ->
1274− iRenderResult (vsep (map (pprintPTerm ppOpts {ppopt_impl = True}
1285+ iRenderResult (vsep (map (pprintPTerm ppOpts
12751286 []
12761287 []
12771288 (idris_infixes i))
@@ -1515,7 +1526,7 @@ pprintDef asCore n =
15151526 ppMissing _ = empty
15161527
15171528 ppTy :: Bool -> IState -> (Name, TypeInfo) -> Doc OutputAnnotation
1518− ppTy amb ist (n, TI constructors isCodata _ _ _)
1529+ ppTy amb ist (n, TI constructors isCodata _ _ _ _)
15191530 = kwd key <+> prettyName True amb [] n <+> colon <+>
15201531 align (pprintDelabTy ist n) <+> kwd "where" <$>
15211532 indent 2 (vsep (map (ppCon False ist) constructors))
@@ -1536,4 +1547,3 @@ replSettings :: Maybe FilePath -> Settings Idris
15361547replSettings hFile = setComplete replCompletion $ defaultSettings {
15371548 historyFile = hFile
15381549 }
1539−
src/Idris/REPL/Commands.hs+1
@@ -32,6 +32,7 @@ data Command = Quit
3232 | Universes
3333 | LogLvl Int
3434 | LogCategory [LogCat]
35+ | Verbosity Int
3536 | Spec PTerm
3637 | WHNF PTerm
3738 | TestInline PTerm
src/Idris/REPL/Parser.hs+8−1
@@ -118,6 +118,7 @@ parserCommandsForHelp =
118118 , (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
119119 , "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
120120 , cmd_pprint)
121+ , (["verbosity"], NumberArg, "Set verbosity level", cmd_verb)
121122 ]
122123 where optionsList = intercalate ", " $ map fst setOptions
123124
@@ -146,7 +147,7 @@ parserCommands =
146147 , proofArgCmd ["mc", "makecase"] MakeCase
147148 ":mc <line> <name> adds a case block for the definition of the metavariable on the line"
148149 , proofArgCmd ["ml", "makelemma"] MakeLemma "?"
149− , (["log"], NumberArg, "Set logging verbosity level", cmd_log)
150+ , (["log"], NumberArg, "Set logging level", cmd_log)
150151 , ( ["logcats"]
151152 , ManyArgs NameArg
152153 , "Set logging categories"
@@ -405,6 +406,12 @@ cmd_log name = do
405406 eof
406407 return (Right (LogLvl i))
407408
409+cmd_verb :: String -> P.IdrisParser (Either String Command)
410+cmd_verb name = do
411+ i <- fmap (fromIntegral . fst) P.natural
412+ eof
413+ return (Right (Verbosity i))
414+
408415cmd_cats :: String -> P.IdrisParser (Either String Command)
409416cmd_cats name = do
410417 cs <- sepBy pLogCats (P.whiteSpace)
src/Idris/Reflection.hs+20−13
@@ -314,9 +314,9 @@ reifyTTBinder _ _ t = fail ("Unknown reflection binder: " ++ show t)
314314
315315reifyTTBinderApp :: (Term -> ElabD a) -> Name -> [Term] -> ElabD (Binder a)
316316reifyTTBinderApp reif f [t]
317− | f == reflm "Lam" = liftM Lam (reif t)
317+ | f == reflm "Lam" = liftM (Lam RigW) (reif t)
318318reifyTTBinderApp reif f [t, k]
319− | f == reflm "Pi" = liftM2 (Pi Nothing) (reif t) (reif k)
319+ | f == reflm "Pi" = liftM2 (Pi RigW Nothing) (reif t) (reif k)
320320reifyTTBinderApp reif f [x, y]
321321 | f == reflm "Let" = liftM2 Let (reif x) (reif y)
322322reifyTTBinderApp reif f [t]
@@ -326,7 +326,7 @@ reifyTTBinderApp reif f [t]
326326reifyTTBinderApp reif f [x, y]
327327 | f == reflm "Guess" = liftM2 Guess (reif x) (reif y)
328328reifyTTBinderApp reif f [t]
329− | f == reflm "PVar" = liftM PVar (reif t)
329+ | f == reflm "PVar" = liftM (PVar RigW) (reif t)
330330reifyTTBinderApp reif f [t]
331331 | f == reflm "PVTy" = liftM PVTy (reif t)
332332reifyTTBinderApp _ f args = fail ("Unknown reflection binder: " ++ show (f, args))
@@ -491,6 +491,9 @@ reflectTTQuotePattern unq Erased
491491reflectTTQuotePattern unq Impossible
492492 = lift . tfail . InternalMsg $
493493 "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration."
494+reflectTTQuotePattern unq (Inferred t)
495+ = lift . tfail . InternalMsg $
496+ "Phase error! The Inferred constructor is for coverage checking only and should not have been reflected during elaboration."
494497reflectTTQuotePattern unq (TType exp)
495498 = do ue <- getNameFrom (sMN 0 "uexp")
496499 claim ue (Var (sNS (sUN "TTUExp") ["Reflection", "Language"]))
@@ -574,12 +577,12 @@ reflectRawQuotePattern unq (RConstant c) =
574577 fill (reflectConstant c); solve
575578
576579reflectBinderQuotePattern :: ([Name] -> a -> ElabD ()) -> Raw -> [Name] -> Binder a -> ElabD ()
577−reflectBinderQuotePattern q ty unq (Lam t)
580+reflectBinderQuotePattern q ty unq (Lam _ t)
578581 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
579582 fill $ reflCall "Lam" [ty, Var t']
580583 solve
581584 focus t'; q unq t
582−reflectBinderQuotePattern q ty unq (Pi _ t k)
585+reflectBinderQuotePattern q ty unq (Pi _ _ t k)
583586 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
584587 k' <- claimTy (sMN 0 "k") ty; movelast k';
585588 fill $ reflCall "Pi" [ty, Var t', Var k']
@@ -616,7 +619,7 @@ reflectBinderQuotePattern q ty unq (Guess x y)
616619 solve
617620 focus x'; q unq x
618621 focus y'; q unq y
619−reflectBinderQuotePattern q ty unq (PVar t)
622+reflectBinderQuotePattern q ty unq (PVar _ t)
620623 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
621624 fill $ reflCall "PVar" [ty, Var t']
622625 solve
@@ -654,6 +657,8 @@ reflectTTQuote _ (Proj _ _) =
654657reflectTTQuote unq Erased = Var (reflm "Erased")
655658reflectTTQuote _ Impossible =
656659 error "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration."
660+reflectTTQuote _ (Inferred tm) =
661+ error "Phase error! The Inferred constructor is for coverage checking only and should not have been reflected during elaboration."
657662
658663reflectRawQuote :: [Name] -> Raw -> Raw
659664reflectRawQuote unq (Var n)
@@ -744,9 +749,9 @@ reflectBinder :: Binder Term -> Raw
744749reflectBinder = reflectBinderQuote reflectTTQuote (reflm "TT") []
745750
746751reflectBinderQuote :: ([Name] -> a -> Raw) -> Name -> [Name] -> Binder a -> Raw
747−reflectBinderQuote q ty unq (Lam t)
752+reflectBinderQuote q ty unq (Lam _ t)
748753 = reflCall "Lam" [Var ty, q unq t]
749−reflectBinderQuote q ty unq (Pi _ t k)
754+reflectBinderQuote q ty unq (Pi _ _ t k)
750755 = reflCall "Pi" [Var ty, q unq t, q unq k]
751756reflectBinderQuote q ty unq (Let x y)
752757 = reflCall "Let" [Var ty, q unq x, q unq y]
@@ -758,7 +763,7 @@ reflectBinderQuote q ty unq (GHole _ _ t)
758763 = reflCall "GHole" [Var ty, q unq t]
759764reflectBinderQuote q ty unq (Guess x y)
760765 = reflCall "Guess" [Var ty, q unq x, q unq y]
761−reflectBinderQuote q ty unq (PVar t)
766+reflectBinderQuote q ty unq (PVar _ t)
762767 = reflCall "PVar" [Var ty, q unq t]
763768reflectBinderQuote q ty unq (PVTy t)
764769 = reflCall "PVTy" [Var ty, q unq t]
@@ -799,7 +804,7 @@ reflectUExp (UVal i) = reflCall "UVal" [RConstant (I i)]
799804
800805-- | Reflect the environment of a proof into a List (TTName, Binder TT)
801806reflectEnv :: Env -> Raw
802−reflectEnv = foldr consToEnvList emptyEnvList
807+reflectEnv = foldr consToEnvList emptyEnvList . envBinders
803808 where
804809 consToEnvList :: (Name, Binder Term) -> Raw -> Raw
805810 consToEnvList (n, b) l
@@ -818,8 +823,10 @@ reflectEnv = foldr consToEnvList emptyEnvList
818823 emptyEnvList = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"]))
819824 [envTupleType]
820825
826+-- Reflected environments don't get the RigCount (for the moment, at least)
821827reifyEnv :: Term -> ElabD Env
822−reifyEnv = reifyList (reifyPair reifyTTName (reifyTTBinder reifyTT (reflm "TT")))
828+reifyEnv tm = do preEnv <- reifyList (reifyPair reifyTTName (reifyTTBinder reifyTT (reflm "TT"))) tm
829+ return $ map (\(n, b) -> (n, RigW, b)) preEnv
823830
824831-- | Reflect an error into the internal datatype of Idris -- TODO
825832rawBool :: Bool -> Raw
@@ -1083,7 +1090,7 @@ reflectList ty (x:xs) = RApp (RApp (RApp (Var (sNS (sUN "::") ["List", "Prelude"
10831090-- come from a lookup in idris_implicits on IState.
10841091getArgs :: [PArg] -> Raw -> ([RFunArg], Raw)
10851092getArgs [] r = ([], r)
1086−getArgs (a:as) (RBind n (Pi _ ty _) sc) =
1093+getArgs (a:as) (RBind n (Pi _ _ ty _) sc) =
10871094 let (args, res) = getArgs as sc
10881095 erased = if InaccessibleArg `elem` argopts a then RErased else RNotErased
10891096 arg' = case a of
@@ -1114,7 +1121,7 @@ buildFunDefns ist n =
11141121 mkFunClause ([], lhs, rhs) = RMkFunClause lhs rhs
11151122 mkFunClause (((n, ty) : ns), lhs, rhs) = mkFunClause (ns, bind lhs, bind rhs) where
11161123 bind Impossible = Impossible
1117− bind tm = Bind n (PVar ty) tm
1124+ bind tm = Bind n (PVar RigW ty) tm
11181125
11191126-- | Build the reflected datatype definition(s) that correspond(s) to
11201127-- a provided unqualified name
src/Idris/Termination.hs+10−10
@@ -1,6 +1,6 @@
11{-|
2−Module : Idris.Coverage
3−Description : The coverage and totality checkers for Idris are in this module.
2+Module : Idris.Termination
3+Description : The termination checker for Idris
44Copyright :
55License : BSD3
66Maintainer : The Idris Community.
@@ -112,13 +112,13 @@ checkPositive mut_ns (cn, ty')
112112 where
113113 args t = [0..length (getArgTys t)-1]
114114
115− cp i (Bind n (Pi _ aty _) sc)
115+ cp i (Bind n (Pi _ _ aty _) sc)
116116 = posArg i aty && cp i sc
117117 cp i t | (P _ n' _ , args) <- unApply t,
118118 n' `elem` mut_ns = all noRec args
119119 cp i _ = True
120120
121− posArg ist (Bind _ (Pi _ nty _) sc) = noRec nty && posArg ist sc
121+ posArg ist (Bind _ (Pi _ _ nty _) sc) = noRec nty && posArg ist sc
122122 posArg ist t = posParams ist t
123123
124124 noRec arg = all (\x -> x `notElem` mut_ns) (allTTNames arg)
@@ -185,7 +185,7 @@ checkTotality path fc n
185185 case unApply (getRetTy ty) of
186186 (P _ tyn _, _) -> do
187187 let ms = case lookupCtxt tyn (idris_datatypes i) of
188− [TI _ _ _ _ xs@(_:_)] -> xs
188+ [TI _ _ _ _ xs@(_:_) _] -> xs
189189 ts -> [tyn]
190190 checkPositive ms (n, ty)
191191 _-> return $ Total []
@@ -429,8 +429,8 @@ buildSCG' ist topfn pats args = nub $ concatMap scgPat pats where
429429 = case lookupTy n (tt_ctxt ist) of
430430 [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args
431431 _ -> args
432− where expand i (Bind n (Pi _ _ _) sc) (x : xs) = x : expand (i + 1) sc xs
433− expand i (Bind n (Pi _ _ _) sc) [] = Just (i, Same) : expand (i + 1) sc []
432+ where expand i (Bind n (Pi _ _ _ _) sc) (x : xs) = x : expand (i + 1) sc xs
433+ expand i (Bind n (Pi _ _ _ _) sc) [] = Just (i, Same) : expand (i + 1) sc []
434434 expand i _ xs = xs
435435
436436 mkChange n args pargs = [(n, expandToArity n (sizes args))]
@@ -471,15 +471,15 @@ buildSCG' ist topfn pats args = nub $ concatMap scgPat pats where
471471
472472 isInductive (P _ nty _) (P _ nty' _) =
473473 let (co, muts) = case lookupCtxt nty (idris_datatypes ist) of
474− [TI _ x _ _ muts] -> (x, muts)
474+ [TI _ x _ _ muts _] -> (x, muts)
475475 _ -> (False, []) in
476476 (nty == nty' || any (== nty') muts) && not co
477477 isInductive _ _ = False
478478
479− dePat (Bind x (PVar ty) sc) = dePat (instantiate (P Bound x ty) sc)
479+ dePat (Bind x (PVar _ ty) sc) = dePat (instantiate (P Bound x ty) sc)
480480 dePat t = t
481481
482− patvars (Bind x (PVar _) sc) = x : patvars sc
482+ patvars (Bind x (PVar _ _) sc) = x : patvars sc
483483 patvars _ = []
484484
485485 allGuarded n ist = case lookupCtxtExact n (idris_flags ist) of
src/Idris/Transforms.hs+2−2
@@ -86,7 +86,7 @@ applyRule (lhs, rhs) tm
8686-- (In general, this would not be true, but when we elaborate transformation
8787-- rules we mangle the names so that it is true. While this feels a bit
8888-- hacky, it's much easier to think about than mangling de Bruijn indices).
89− where depat ms (Bind n (PVar t) sc)
89+ where depat ms (Bind n (PVar _ t) sc)
9090 = case lookup n ms of
9191 Just tm -> depat ms (subst n tm sc)
9292 _ -> depat ms sc -- no occurrence? Shouldn't happen
@@ -95,7 +95,7 @@ applyRule (lhs, rhs) tm
9595matchTerm :: Term -> Term -> Maybe [(Name, Term)]
9696matchTerm lhs tm = matchVars [] lhs tm
9797 where
98− matchVars acc (Bind n (PVar t) sc) tm
98+ matchVars acc (Bind n (PVar _ t) sc) tm
9999 = matchVars (n : acc) (instantiate (P Bound n t) sc) tm
100100 matchVars acc sc tm
101101 = -- trace (show acc ++ ": " ++ show (sc, tm)) $
src/Idris/TypeSearch.hs+4−4
@@ -104,8 +104,8 @@ searchPred istate ty1 = matcher where
104104 matcher = matchTypesBulk istate maxScore ty1
105105
106106
107−typeFromDef :: (Def, i, b, c, d) -> Maybe Type
108−typeFromDef (def, _, _, _, _) = get def where
107+typeFromDef :: (Def, r, i, b, c, d) -> Maybe Type
108+typeFromDef (def, _, _, _, _, _) = get def where
109109 get :: Def -> Maybe Type
110110 get (Function ty _) = Just ty
111111 get (TyDecl _ ty) = Just ty
@@ -142,7 +142,7 @@ computeDagP removePred t = (reverse (map f arguments), reverse theRemovedArgs ,
142142 (arguments, theRemovedArgs, retTy) = go [] [] t
143143
144144 -- NOTE : args are in reverse order
145− go args removedArgs (Bind n (Pi _ ty _) sc) = let arg = (n, ty) in
145+ go args removedArgs (Bind n (Pi _ _ ty _) sc) = let arg = (n, ty) in
146146 if removePred ty
147147 then go args (arg : removedArgs) sc
148148 else go (arg : args) removedArgs sc
@@ -439,7 +439,7 @@ matchTypesBulk istate maxScore type1 types = getAllResults startQueueOfQueues wh
439439 unifyQueue state [] = return state
440440 unifyQueue state ((ty1, ty2) : queue) = do
441441 --trace ("go: \n" ++ show state) True `seq` return ()
442− res <- tcToMaybe $ match_unify ctxt [ (n, Pi Nothing ty (TType (UVar [] 0))) | (n, ty) <- holes state]
442+ res <- tcToMaybe $ match_unify ctxt [ (n, RigW, Pi RigW Nothing ty (TType (UVar [] 0))) | (n, ty) <- holes state]
443443 (ty1, Nothing)
444444 (ty2, Nothing) [] (map fst $ holes state) []
445445 (state', queueAdditions) <- resolveUnis res state
stack-shell.nix+1−1
@@ -2,7 +2,7 @@ with (import <nixpkgs> {});
22
33let
44 # MUST match resolver in stack.yaml
5− resolver = haskell.packages.lts-7_10.ghc;
5+ resolver = haskell.packages.lts-7_14.ghc;
66
77 native_libs = [
88 libffi
stack.yaml+2−2
@@ -1,4 +1,4 @@
1−resolver: lts-7.10
1+resolver: lts-7.14
22
33packages:
44 - location: .
@@ -10,7 +10,7 @@ flags:
1010
1111extra-deps:
1212 - libffi-0.1
13− - safe-0.3.9
13+
1414nix:
1515 enable: false
1616 shell-file: stack-shell.nix
test/TestData.hs+6−3
@@ -70,7 +70,8 @@ testFamiliesData = [
7070 ( 15, ANY ),
7171 ( 16, ANY ),
7272 ( 17, ANY ),
73− ( 18, ANY )]),
73+ ( 18, ANY ),
74+ ( 19, ANY )]),
7475 ("bignum", "Bignum",
7576 [ ( 1, ANY ),
7677 ( 2, ANY )]),
@@ -178,7 +179,8 @@ testFamiliesData = [
178179 ( 4, ANY ),
179180 ( 5, ANY ),
180181 ( 6, ANY ),
181− ( 7, ANY )]),
182+ ( 7, ANY ),
183+ ( 8, ANY )]),
182184 ("prelude", "Prelude",
183185 [ ( 1, ANY )]),
184186 ("primitives", "Primitive types",
@@ -276,7 +278,8 @@ testFamiliesData = [
276278 ( 15, ANY ),
277279 ( 16, ANY ),
278280 ( 17, ANY ),
279− ( 18, ANY )]),
281+ ( 18, ANY ),
282+ ( 19, ANY )]),
280283 ("tutorial", "Tutorial examples",
281284 [ ( 1, ANY ),
282285 ( 2, ANY ),
test/TestRun.hs+14−8
@@ -107,11 +107,17 @@ runTest path flags = do
107107 normalise [] = []
108108
109109main :: IO ()
110−main =
111− defaultMainWithIngredients ingredients $
112− askOption $ \(NodeOpt node) ->
113− let (codegen, flags) = if node then (JS, ["--codegen", "node"])
114− else (C , [])
115− in
116− mkGoldenTests (testFamiliesForCodegen codegen)
117− (flags ++ idrisFlags)
110+main = do
111+ node <- findExecutable "node"
112+ case node of
113+ Nothing -> do
114+ putStrLn "For running the test suite against Node, node must be installed."
115+ exitFailure
116+ Just _ -> do
117+ defaultMainWithIngredients ingredients $
118+ askOption $ \(NodeOpt node) ->
119+ let (codegen, flags) = if node then (JS, ["--codegen", "node"])
120+ else (C , [])
121+ in
122+ mkGoldenTests (testFamiliesForCodegen codegen)
123+ (flags ++ idrisFlags)
test/basic018/expected+1−1
@@ -8,7 +8,7 @@ basic018.idr:13:6:When checking right hand side of test with expected type
88Type mismatch between
99 42 = 42 (Type of Refl)
1010and
11− thing = 42 (Expected type)
11+ thing = S (fromIntegerNat 41) (Expected type)
1212
1313Specifically:
1414 Type mismatch between
test/basic019/basic019.idrnew file+10
@@ -0,0 +1,10 @@
1+printRange : (t : Type) -> (Show t, Num t, Enum t) => IO ()
2+printRange t = do printLn [(the t 1)..10]
3+ printLn [(the t 10),9..1]
4+ printLn (take 10 [(the t 1)..])
5+ printLn (take 10 [(the t 1),3..])
6+
7+main : IO ()
8+main = do printRange Nat
9+ printRange Int
10+ printRange Integer
test/basic019/expectednew file+12
@@ -0,0 +1,12 @@
1+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2+[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
3+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4+[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
5+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6+[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
7+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
8+[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
9+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10+[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
11+[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12+[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
test/basic019/runnew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+${IDRIS:-idris} $@ basic019.idr -o basic019
3+./basic019
4+rm -f basic019 *.ibc
test/dsl001/expected+4−4
@@ -1,13 +1,13 @@
1124
2212
33testFac : Int
4−testFac = PE_interp_f79b3e31 [] (PE_fromInteger_d6648df 4)
5−PE_interp_f79b3e31 : Env G -> Int -> Int
6−PE_interp_f79b3e31 (3arg) = \x =>
4+testFac = PE_interp_e04a79ff [] (PE_fromInteger_d6648df 4)
5+PE_interp_e04a79ff : Env G -> Int -> Int
6+PE_interp_e04a79ff (3arg) = \x =>
77 ifThenElse (PE_==_ba2f651f x
88 (PE_fromInteger_d6648df 0))
99 (Delay (PE_fromInteger_d6648df 1))
10− (Delay (PE_*_ba2f651f (PE_interp_f79b3e31 (x ::
10+ (Delay (PE_*_ba2f651f (PE_interp_e04a79ff (x ::
1111 (3arg))
1212 (PE_-_ba2f651f x
1313 (PE_fromInteger_d6648df 1)))
test/dsl001/input+1−1
@@ -1,2 +1,2 @@
11:printdef testFac
2−:printdef PE_interp_f79b3e31
2+:printdef PE_interp_e04a79ff
test/dsl001/test001.idr+2
@@ -3,6 +3,8 @@ module Main
33import Data.Vect
44import Data.Fin
55
6+%language DSLNotation
7+
68data Ty = TyInt | TyBool| TyFun Ty Ty
79
810interpTy : Ty -> Type
test/dsl002/Resimp.idr+1
@@ -3,6 +3,7 @@ module Resimp
33import public Data.Vect
44import public Data.Fin
55
6+%language DSLNotation
67%access public export
78
89-- IO operations which read a resource
test/dsl003/DSLPi.idr+2
@@ -3,6 +3,8 @@ module DSLPi
33import Data.Fin
44import Data.Vect
55
6+%language DSLNotation
7+
68data Ty = BOOL | INT | UNIT | ARR Ty Ty
79
810arr_ : _ -> Ty -> Ty -> Ty
test/dsl004/Door0.idr+3−1
@@ -1,6 +1,8 @@
11import IOu
22
3−data Result : (a : Type) -> (a -> Type) -> Type* where
3+%language UniquenessTypes
4+
5+data Result : (a : Type) -> (a -> Type) -> AnyType where
46 Res : {k : a -> Type} -> (val : a) -> k val -> Result a k
57
68
test/dsl004/Door1.idr+2
@@ -2,6 +2,8 @@ import IOu
22
33import Data.Vect
44
5+%language UniquenessTypes
6+
57data Result : (a : AnyType) -> (a -> AnyType) -> AnyType where
68 Res : {k : a -> AnyType} -> (val : a) -> (h : k val) -> Result a k
79
test/dsl004/Door2.idr+2
@@ -1,5 +1,7 @@
11import IOu
22
3+%language UniquenessTypes
4+
35data DoorState = OPEN | CLOSED
46
57data DoorH : DoorState -> UniqueType where
test/dsl004/Door3.idr+2
@@ -1,5 +1,7 @@
11import IOu
22
3+%language UniquenessTypes
4+
35data DoorState = OPEN | CLOSED
46
57data DoorH : DoorState -> UniqueType where
test/dsl004/IOu.idr+2
@@ -1,5 +1,7 @@
11module IOu
22
3+%language UniquenessTypes
4+
35-------- An IO type supporting possibly unique values
46
57data IOu : AnyType -> AnyType where
test/interactive010/expected+2−2
@@ -4,9 +4,9 @@ a is not an implicit argument of Prelude.Interfaces./
44Usage is :doc <functionname>
55Usage is :wc <functionname>
66Usage is :printdef <functionname>
7−pat {ty504} : Type toplevel.u. pat {__interface505} : Prelude.Interfaces.Fractional {ty504}. Prelude.Interfaces./ {ty504} {__interface505}
7+pat {ty503} : Type toplevel.u. pat {__interface504} : Prelude.Interfaces.Fractional {ty503}. Prelude.Interfaces./ {ty503} {__interface504}
88
9− : pty {ty504} : Type toplevel.u. pty {__interface505} : Prelude.Interfaces.Fractional {ty504}. {ty504} -> {ty504} -> {ty504}
9+ : pty {ty503} : Type toplevel.u. pty {__interface504} : Prelude.Interfaces.Fractional {ty503}. {ty503} -> {ty503} -> {ty503}
1010(input):1:1: error: expected: ":",
1111 dependent type signature,
1212 end of input
test/meta001/Finite.idr+2
@@ -4,6 +4,8 @@ import Data.Fin
44import Language.Reflection.Elab
55import Language.Reflection.Utils
66
7+%language ElabReflection
8+
79-- Test various features of reflected elaboration, including looking
810-- up datatypes, defining functions, and totality checking
911
test/meta002/AgdaStyleReflection.idr+1−1
@@ -13,7 +13,7 @@ import Language.Reflection.Utils
1313import Pruviloj
1414
1515%default total
16−
16+%language ElabReflection
1717
1818
1919||| Function arguments as provided at the application site
test/meta002/DataDef.idr+2
@@ -1,5 +1,7 @@
11module DataDef
22
3+%language ElabReflection
4+
35foo : Elab ()
46foo = do declareDatatype $ Declare `{{DataDef.N}} [MkFunArg `{{n}} `(Nat) Explicit NotErased] `(Type)
57 defineDatatype $ DefineDatatype `{{DataDef.N}} [
test/meta002/Deriving.idr+2
@@ -1,6 +1,8 @@
11||| Test some deriving features
22module Deriving
33
4+%language ElabReflection
5+
46-- NB: test disabled due to excess memory consumption
57
68import Pruviloj
test/meta002/Tacs.idr+1
@@ -16,6 +16,7 @@ import Language.Reflection.Utils
1616import Pruviloj.Core
1717
1818%default total
19+%language ElabReflection
1920
2021-- Tactics can now query the elaborator and bind variables
2122
test/meta002/expected+2−2
@@ -1,7 +1,7 @@
1−DataDef.idr:72:1-9:
1+DataDef.idr:74:1-9:
22While running an elaboration script, the following error occurred:
33Prelude.Either.Either is already defined as a datatype.
4−Tacs.idr:298:15:
4+Tacs.idr:299:15:
55When checking right hand side of testElab3 with expected type
66 DPair Ty (Tm [])
77
test/meta003/BadDef.idr+2
@@ -2,6 +2,8 @@ module BadDef
22
33import Language.Reflection.Elab
44
5+%language ElabReflection
6+
57mkN : String -> TTName
68mkN n = NS (UN n) ["BadDef"]
79
test/meta003/expected+1−1
@@ -1,4 +1,4 @@
1−BadDef.idr:12:1-9:
1+BadDef.idr:14:1-9:
22While running an elaboration script, the following error occurred:
33Type mismatch between
44 ()
test/meta004/expected+1−1
@@ -1,3 +1,3 @@
1−meta004.idr:48:1-9:
1+meta004.idr:50:1-9:
22While running an elaboration script, the following error occurred:
33Not an impossible case
test/meta004/meta004.idr+2
@@ -2,6 +2,8 @@ import Data.Fin
22import Language.Reflection.Utils
33import Pruviloj.Core
44
5+%language ElabReflection
6+
57rename : TTName -> TTName -> Raw -> Raw
68rename old new (RBind name b body) = RBind name (map (rename old new) b) (rename old new body)
79rename old new (RApp f arg) = RApp (rename old new f) (rename old new arg)
test/pkg008/expectednew file+13
@@ -0,0 +1,13 @@
1+Entering directory `./src'
2+Type checking ./NumOps.idr
3+Type checking ./Test.idr
4+Leaving directory `./src'
5+Test Passed
6+Test Passed
7+Entering directory `./src'
8+Leaving directory `./src'
9+Entering directory `./src'
10+Removed: NumOps.ibc
11+Removed: Test.ibc
12+Removed: 00maths-idx.ibc
13+Leaving directory `./src'
test/pkg008/maths.ipkgnew file+9
@@ -0,0 +1,9 @@
1+package maths
2+
3+sourcedir = src
4+
5+modules = NumOps
6+ , Test
7+
8+tests = Test.testDouble
9+ , Test.testTriple
test/pkg008/runnew file+9
@@ -0,0 +1,9 @@
1+#!/usr/bin/env bash
2+
3+${IDRIS:-idris} $@ --build maths.ipkg
4+${IDRIS:-idris} $@ --testpkg maths.ipkg | grep -v -e "idris"
5+
6+# Idris only appears in the randomly generated name of test so we grep
7+# to remove it to make output consistent.
8+
9+${IDRIS:-idris} $@ --clean maths.ipkg
test/pkg008/src/NumOps.idrnew file+9
@@ -0,0 +1,9 @@
1+module NumOps
2+
3+%access export -- to make functions under test visible
4+
5+double : Num a => a -> a
6+double a = a + a
7+
8+triple : Num a => a -> a
9+triple a = a + double a
test/pkg008/src/Test.idrnew file+21
@@ -0,0 +1,21 @@
1+module Test
2+
3+import NumOps
4+
5+%access export -- to make the test functions visible
6+
7+assertEq : Eq a => (given : a) -> (expected : a) -> IO ()
8+assertEq g e = if g == e
9+ then putStrLn "Test Passed"
10+ else putStrLn "Test Failed"
11+
12+assertNotEq : Eq a => (given : a) -> (expected : a) -> IO ()
13+assertNotEq g e = if not (g == e)
14+ then putStrLn "Test Passed"
15+ else putStrLn "Test Failed"
16+
17+testDouble : IO ()
18+testDouble = assertEq (double 2) 4
19+
20+testTriple : IO ()
21+testTriple = assertNotEq (triple 2) 5
test/proof002/Reflect.idr+1
@@ -4,6 +4,7 @@ import Decidable.Equality
44
55%access public export
66%default total
7+%language FirstClassReflection
78
89using (xs : List a, ys : List a, G : List (List a))
910
test/proof002/expected+3−3
@@ -1,8 +1,8 @@
1−Reflect.idr:174:21-26:
1+Reflect.idr:175:21-26:
22This style of tactic proof is deprecated. See %runElab for the replacement.
3−Reflect.idr:183:21-26:
3+Reflect.idr:184:21-26:
44This style of tactic proof is deprecated. See %runElab for the replacement.
5−Reflect.idr:191:15-20:
5+Reflect.idr:192:15-20:
66This style of tactic proof is deprecated. See %runElab for the replacement.
77test030a.idr:12:26-14:1:
88When checking right hand side of testReflect1 with expected type
test/pruviloj001/pruviloj001.idr+1
@@ -5,6 +5,7 @@ import Pruviloj
55import Pruviloj.Induction
66
77%default total
8+%language ElabReflection
89
910||| Try some simplification and rewriting heuristics, then attempt to
1011||| solve the goal
test/regression001/coverage001.idrnew file+79
@@ -0,0 +1,79 @@
1+module Data.AVL.Tree
2+
3+%default total
4+%access export
5+
6+data Balance : Nat -> Nat -> Type where
7+ LHeavy : Balance (S n) n
8+ RHeavy : Balance n (S n)
9+ Balanced : Balance n n
10+
11+%name Balance b, bal
12+
13+height : Balance n m -> Nat
14+height b = S (height' b)
15+ where
16+ height' : Balance n m -> Nat
17+ height' (LHeavy {n}) = S n
18+ height' (RHeavy {n}) = S n
19+ height' {n} (Balanced {n}) = n
20+
21+public export
22+data Tree : (keyTy : Type) -> (valTy : Type) -> Type
23+ where
24+ ||| An empty Tree node.
25+ Empty : Tree k v
26+
27+ Node : (key : k)
28+ -> (val : v)
29+ -> (left : Tree k v)
30+ -> (right : Tree k v)
31+ -> Tree k v
32+
33+%name Tree t, tree
34+
35+public export
36+data AVLInvariant : (height : Nat)
37+ -> (tree : Tree k v)
38+ -> Type
39+ where
40+ AVLEmpty : AVLInvariant 0 Empty
41+
42+ AVLNode : (left : AVLInvariant n l) ->
43+ (right : AVLInvariant m r) ->
44+ (b : Balance n m) ->
45+ AVLInvariant (height b) (Node k v l r)
46+
47+%name AVLInvariant inv
48+
49+public export
50+AVLTree : (height : Nat) -> (keyTy : Type) -> (valueTy : Type) -> Type
51+AVLTree n k v = Subset (Tree k v) (AVLInvariant n)
52+
53+-- --------------------------------------------------------------- [ Rotations ]
54+private
55+data InsertRes : Nat -> (k : Type) -> Type -> Type where
56+ Same : AVLTree n k v -> InsertRes n k v
57+ Grew : AVLTree (S n) k v -> InsertRes n k v
58+
59+%name InsertRes res, r
60+
61+private
62+runInsertRes : InsertRes n k v -> (n : Nat ** AVLTree n k v)
63+runInsertRes (Same t) = (_ ** t)
64+runInsertRes (Grew t) = (_ ** t)
65+
66+||| Perform a Left roation.
67+private
68+rotLeft : k
69+ -> v
70+ -> AVLTree n k v
71+ -> AVLTree (S (S n)) k v
72+ -> InsertRes (S (S n)) k v
73+-- Impossible because Empty has depth 0 and we know the depth is at least 2 from the type
74+rotLeft key val l (Element Empty AVLEmpty) impossible
75+rotLeft key val (Element l invl) (Element (Node key' val' rl rr) (AVLNode invrl invrr Balanced)) = ?rl1
76+rotLeft key val (Element l invl) (Element (Node key' val' (Node key'' val'' rll rlr) rr) (AVLNode (AVLNode invrll invrlr LHeavy) invrr LHeavy)) = ?rl2
77+rotLeft key val (Element l invl) (Element (Node key' val' (Node key'' val'' rll rlr) rr) (AVLNode (AVLNode invrll invrlr RHeavy) invrr LHeavy)) = ?rl3
78+rotLeft key val (Element l invl) (Element (Node key' val' (Node key'' val'' rll rlr) rr) (AVLNode (AVLNode invrll invrlr Balanced) invrr LHeavy)) = ?rl4
79+rotLeft key val (Element l invl) (Element (Node key' val' rl rr) (AVLNode invrl invrr RHeavy)) = ?rl5
test/regression001/eff001.idrnew file+39
@@ -0,0 +1,39 @@
1+module Test.Random
2+
3+import Effects
4+import Effect.Random
5+
6+genKVPair : (genA : Eff a [RND])
7+ -> (genB : Eff b [RND])
8+ -> Eff (Pair a b) [RND]
9+genKVPair f g = pure (!f, !g)
10+
11+genRndListKVUE : (Eq a, Eq b) =>
12+ (seed : Integer)
13+ -> (len : Nat)
14+ -> (genA : Eff a [RND])
15+ -> (genB : Eff b [RND])
16+ -> Eff (List (Pair a b)) [RND]
17+genRndListKVUE s l f g = do srand s; pure !(doGen l (genKVPair f g))
18+ where
19+ genElem : (Eq a, Eq b)
20+ => (generator : Eff (Pair a b) [RND])
21+ -> (existing : List (Pair a b))
22+ -> Eff (Pair a b) [RND]
23+ genElem j xs = do
24+ x <- j
25+ if elem x xs
26+ then genElem j xs
27+ else if isJust $ lookup (fst x) xs
28+ then genElem j xs
29+ else pure x
30+
31+ doGen : (Eq a, Eq b)
32+ => (count : Nat)
33+ -> (generator : Eff (Pair a b) [RND])
34+ -> Eff (List (Pair a b)) [RND]
35+ doGen Z j = pure Nil
36+ doGen (S n) j = do
37+ xs <- doGen n j
38+ x <- genElem j xs
39+ pure (x::xs)
test/regression001/run+5−1
@@ -3,7 +3,11 @@ ${IDRIS:-idris} $@ --check \
33 reg001.idr reg036.idr reg037.idr reg038.idr reg046.idr \
44 reg047a.idr reg053.idr reg057.idr reg058.idr reg058a.idr \
55 reg059.idr reg060.idr reg061.idr reg062.idr reg063.idr \
6− reg064.idr reg065.idr reg066.idr reg071.idr reg074.idr
6+ reg064.idr reg065.idr reg066.idr reg071.idr reg074.idr \
7+ coverage001.idr
8+
9+${IDRIS:-idris} $@ --check \
10+ eff001.idr -p effects
711
812${IDRIS:-idris} $@ --check --nobuiltins reg047.idr
913
test/sourceLocation001/SourceLoc.idr+1
@@ -6,6 +6,7 @@ import Language.Reflection
66import Language.Reflection.Utils
77
88%default total
9+%language DSLNotation
910
1011||| A "function" that returns where it is called in the source
1112getLoc : {default tactics { sourceLocation } x : SourceLocation} -> SourceLocation
test/sourceLocation001/expected+8−8
@@ -1,19 +1,19 @@
1−SourceLoc.idr:11:19-26:
1+SourceLoc.idr:12:19-26:
22This style of tactic proof is deprecated. See %runElab for the replacement.
3−SourceLoc.idr:20:19-24:
3+SourceLoc.idr:21:19-24:
44This style of tactic proof is deprecated. See %runElab for the replacement.
5−SourceLoc.idr:40:20-27:
5+SourceLoc.idr:41:20-27:
66This style of tactic proof is deprecated. See %runElab for the replacement.
7−SourceLoc.idr:98:18-23:
7+SourceLoc.idr:99:18-23:
88This style of tactic proof is deprecated. See %runElab for the replacement.
99Testing using definition
10−FileLoc "SourceLoc.idr" (16, 11) (16, 17)
10+FileLoc "SourceLoc.idr" (17, 11) (17, 17)
1111Testing using inline tactics
12−FileLoc "SourceLoc.idr" (20, 17) (20, 17)
12+FileLoc "SourceLoc.idr" (21, 17) (21, 17)
1313Testing using metavariable with later definition
14−FileLoc "SourceLoc.idr" (98, 16) (98, 16)
14+FileLoc "SourceLoc.idr" (99, 16) (99, 16)
1515-----------------------
1616Success!
17−Error at FileLoc "SourceLoc.idr" (72, 23) (72, 26)
17+Error at FileLoc "SourceLoc.idr" (73, 23) (73, 26)
1818Success!
1919Success!
test/tactics001/Tactics.idr+5−3
@@ -4,7 +4,7 @@ import Language.Reflection.Elab
44
55import Data.Vect
66
7−
7+%language ElabReflection
88%default total
99
1010-- Test that basic proofs with new-style tactics work
@@ -18,14 +18,16 @@ refl t x = RApp (RApp (Var (UN "Refl")) t) x
1818plusZeroRightNeutralNew : (n : Nat) -> plus n 0 = n
1919plusZeroRightNeutralNew Z = Refl
2020plusZeroRightNeutralNew (S k) =
21− %runElab (do rewriteWith `(sym $ plusZeroRightNeutralNew ~(Var `{k}))
21+ %runElab (do compute
22+ rewriteWith `(sym $ plusZeroRightNeutralNew ~(Var `{k}))
2223 fill $ refl `(Nat : Type) `(S ~(Var `{k}))
2324 solve)
2425
2526plusSuccRightSuccNew : (j, k : Nat) -> plus j (S k) = S (plus j k)
2627plusSuccRightSuccNew Z k = Refl
2728plusSuccRightSuccNew (S j) k =
28− %runElab (do rewriteWith `(sym $ plusSuccRightSuccNew ~(Var `{j}) ~(Var `{k}))
29+ %runElab (do compute
30+ rewriteWith `(sym $ plusSuccRightSuccNew ~(Var `{j}) ~(Var `{k}))
2931 fill $ refl `(Nat : Type) `(S (S (plus ~(Var `{j}) ~(Var `{k}))))
3032 solve)
3133
test/totality019/expectednew file+2
@@ -0,0 +1,2 @@
1+totality019.idr:8:1:Main.testCov is not total as there are missing cases
2+totality019.idr:12:1:Main.testCov' is not total as there are missing cases
test/totality019/runnew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+${IDRIS:-idris} $@ totality019.idr --check
3+${IDRIS:-idris} $@ totality019a.idr --check
4+rm -f *.ibc
test/totality019/totality019.idrnew file+14
@@ -0,0 +1,14 @@
1+%default total
2+
3+MkThing : Bool -> Type
4+MkThing True = Nat
5+MkThing False = Bool
6+
7+testCov : (x : Bool) -> MkThing x -> Nat
8+testCov False False = ?testCov_rhs_3
9+testCov False True = ?testCov_rhs_4
10+
11+testCov' : (x : Bool ** MkThing x) -> Nat
12+testCov' (False ** False) = ?testCov_rhs_3
13+testCov' (False ** True) = ?testCov_rhs_4
14+
test/totality019/totality019a.idrnew file+81
@@ -0,0 +1,81 @@
1+module Test
2+
3+import Data.Vect
4+%default total
5+
6+genT : Vect n Type -> Type
7+genT [] = Type
8+genT (x :: xs) = x -> genT xs
9+
10+data FunLang: Type where
11+ Atom : {dt : Vect n Type} -> genT dt -> FunLang
12+ And : FunLang -> FunLang -> FunLang
13+ Uor : FunLang -> FunLang -> FunLang
14+ Xor : FunLang -> FunLang -> FunLang -- d decides on that
15+
16+data IndexFL : FunLang -> FunLang -> Type where
17+ LHere : IndexFL fl fl
18+ LLeftAnd : IndexFL x rfl -> IndexFL (And x y) rfl
19+ LRightAnd : IndexFL y rfl -> IndexFL (And x y) rfl
20+ LLeftUor : IndexFL x rfl -> IndexFL (Uor x y) rfl
21+ LRightUor : IndexFL y rfl -> IndexFL (Uor x y) rfl
22+ LLeftXor : IndexFL x rfl -> IndexFL (Xor x y) rfl
23+ LRightXor : IndexFL y rfl -> IndexFL (Xor x y) rfl
24+
25+data SetFL : FunLang -> Type where
26+ SEmpty : SetFL fl
27+ SElem : SetFL fl
28+ SLeftAnd : SetFL x -> SetFL (And x y)
29+ SRightAnd : SetFL y -> SetFL (And x y)
30+ SBothAnd : SetFL x -> SetFL y -> SetFL (And x y)
31+ SLeftUor : SetFL x -> SetFL (Uor x y)
32+ SRightUor : SetFL y -> SetFL (Uor x y)
33+ SBothUor : SetFL x -> SetFL y -> SetFL (Uor x y)
34+ SLeftXor : SetFL x -> SetFL (Xor x y)
35+ SRightXor : SetFL y -> SetFL (Xor x y)
36+ SBothXor : SetFL x -> SetFL y -> SetFL (Xor x y)
37+
38+addIndexFLEmpty : IndexFL fl _ -> SetFL fl
39+addIndexFLEmpty LHere = SElem
40+addIndexFLEmpty (LLeftAnd z) = SLeftAnd $ addIndexFLEmpty z
41+addIndexFLEmpty (LRightAnd z) = SRightAnd $ addIndexFLEmpty z
42+addIndexFLEmpty (LLeftUor z) = SLeftUor $ addIndexFLEmpty z
43+addIndexFLEmpty (LRightUor z) = SRightUor $ addIndexFLEmpty z
44+addIndexFLEmpty (LLeftXor z) = SLeftXor $ addIndexFLEmpty z
45+addIndexFLEmpty (LRightXor z) = SRightXor $ addIndexFLEmpty z
46+
47+addIndexFL : SetFL fl -> IndexFL fl _ -> SetFL fl
48+addIndexFL SEmpty y = addIndexFLEmpty y
49+addIndexFL SElem y = SElem
50+addIndexFL x LHere = SElem
51+addIndexFL (SLeftAnd x) (LLeftAnd w) = SLeftAnd $ addIndexFL x w
52+addIndexFL (SLeftAnd SElem) (LRightAnd LHere) = SElem
53+addIndexFL (SLeftAnd x) (LRightAnd w) = SBothAnd x (addIndexFLEmpty w)
54+addIndexFL (SRightAnd SElem) (LLeftAnd LHere) = SElem
55+addIndexFL (SRightAnd x) (LLeftAnd w) = SBothAnd (addIndexFLEmpty w) x
56+addIndexFL (SRightAnd x) (LRightAnd w) = SRightAnd $ addIndexFL x w
57+addIndexFL (SBothAnd x SElem) (LLeftAnd LHere) = SElem
58+addIndexFL (SBothAnd SElem y) (LRightAnd LHere) = SElem
59+addIndexFL (SBothAnd x y) (LLeftAnd w) = SBothAnd (addIndexFL x w) y
60+addIndexFL (SBothAnd x y) (LRightAnd w) = SBothAnd x (addIndexFL y w)
61+addIndexFL (SLeftUor x) (LLeftUor w) = SLeftUor $ addIndexFL x w
62+addIndexFL (SLeftUor SElem) (LRightUor LHere) = SElem
63+addIndexFL (SLeftUor x) (LRightUor w) = SBothUor x (addIndexFLEmpty w)
64+addIndexFL (SRightUor SElem) (LLeftUor LHere) = SElem
65+addIndexFL (SRightUor x) (LLeftUor w) = SBothUor (addIndexFLEmpty w) x
66+addIndexFL (SRightUor x) (LRightUor w) = SRightUor $ addIndexFL x w
67+addIndexFL (SBothUor x SElem) (LLeftUor LHere) = SElem
68+addIndexFL (SBothUor SElem y) (LRightUor LHere) = SElem
69+addIndexFL (SBothUor x y) (LLeftUor w) = SBothUor (addIndexFL x w) y
70+addIndexFL (SBothUor x y) (LRightUor w) = SBothUor x (addIndexFL y w)
71+addIndexFL (SLeftXor x) (LLeftXor w) = SLeftXor $ addIndexFL x w
72+addIndexFL (SLeftXor SElem) (LRightXor LHere) = SElem
73+addIndexFL (SLeftXor x) (LRightXor w) = SBothXor x (addIndexFLEmpty w)
74+addIndexFL (SRightXor SElem) (LLeftXor LHere) = SElem
75+addIndexFL (SRightXor x) (LLeftXor w) = SBothXor (addIndexFLEmpty w) x
76+addIndexFL (SRightXor x) (LRightXor w) = SRightXor $ addIndexFL x w
77+addIndexFL (SBothXor x SElem) (LLeftXor LHere) = SElem
78+addIndexFL (SBothXor SElem y) (LRightXor LHere) = SElem
79+addIndexFL (SBothXor x y) (LLeftXor w) = SBothXor (addIndexFL x w) y
80+addIndexFL (SBothXor x y) (LRightXor w) = SBothXor x (addIndexFL y w)
81+
test/unique001/unique001.idr+2
@@ -1,5 +1,7 @@
11module Main
22
3+%language UniquenessTypes
4+
35data UList : Type -> UniqueType where
46 Nil : UList a
57 (::) : a -> UList a -> UList a
test/unique004/expected+10−10
@@ -1,26 +1,26 @@
1−unique001a.idr:33:11:Type mismatch between
1+unique001a.idr:35:11:Type mismatch between
22 Int -> String
33and
44 UniqueType (Int -> String)
5−unique001a.idr:44:12:Type mismatch between
5+unique001a.idr:46:12:Type mismatch between
66 Int -> String
77and
88 UniqueType (Int -> String)
9−unique001a.idr:55:12:Type mismatch between
9+unique001a.idr:57:12:Type mismatch between
1010 UniqueType (Int -> String)
1111and
1212 Int -> String
13−unique001b.idr:16:7:Borrowed name xs must not be used on RHS
14−unique001c.idr:46:6:Unique name f is used more than once
15−unique001d.idr:3:7:Borrowed name x must not be used on RHS
16−unique001e.idr:3:10:
13+unique001b.idr:18:7:Borrowed name xs must not be used on RHS
14+unique001c.idr:47:6:Unique name f is used more than once
15+unique001d.idr:4:7:Borrowed name x must not be used on RHS
16+unique001e.idr:4:10:
1717Constructor Main.Nil has a UniqueType, but the data type does not
18−unique002.idr:15:5:Unique name xs is used more than once
19−unique002a.idr:15:5:Type mismatch between
18+unique002.idr:17:5:Unique name xs is used more than once
19+unique002a.idr:17:5:Type mismatch between
2020 Int -> String
2121and
2222 UniqueType (Int -> String)
23−unique003.idr:18:5:Type mismatch between
23+unique003.idr:20:5:Type mismatch between
2424 Int -> String
2525and
2626 UniqueType (Int -> String)
test/unique004/unique001a.idr+2
@@ -1,5 +1,7 @@
11module Main
22
3+%language UniquenessTypes
4+
35data UList : Type -> UniqueType where
46 Nil : UList a
57 (::) : a -> UList a -> UList a
test/unique004/unique001b.idr+2
@@ -1,5 +1,7 @@
11module Main
22
3+%language UniquenessTypes
4+
35data UList : Type -> UniqueType where
46 Nil : UList a
57 (::) : a -> UList a -> UList a
test/unique004/unique001c.idr+1
@@ -1,3 +1,4 @@
1+%language UniquenessTypes
12
23data UList : Type -> UniqueType where
34 UNil : UList a
test/unique004/unique001d.idr+1
@@ -1,3 +1,4 @@
1+%language UniquenessTypes
12
23steal : {a : UniqueType} -> Borrowed a -> a
34steal (Read x) = x
test/unique004/unique001e.idr+1
@@ -1,3 +1,4 @@
1+%language UniquenessTypes
12
23data BadList : UniqueType -> Type where
34 Nil : {a : UniqueType} -> BadList a
test/unique004/unique002.idr+2
@@ -1,3 +1,5 @@
1+%language UniquenessTypes
2+
13data UList : Type -> UniqueType where
24 Nil : UList a
35 (::) : a -> UList a -> UList a
test/unique004/unique002a.idr+2
@@ -1,3 +1,5 @@
1+%language UniquenessTypes
2+
13data UList : Type -> UniqueType where
24 Nil : UList a
35 (::) : a -> UList a -> UList a
test/unique004/unique003.idr+2
@@ -1,5 +1,7 @@
11module Main
22
3+%language UniquenessTypes
4+
35data UList : Type -> UniqueType where
46 Nil : UList a
57 (::) : a -> UList a -> UList a