├── .gitignore
├── LICENSE
├── README.md
├── dev.pl
├── pack.pl
├── prolog
├── mavis.pl
└── readme.txt
├── t
├── determinism.pl
├── intersection.pl
├── predicates.pl
└── subtypes.pl
└── test.pl
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | doc/
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright © 2007 Free Software Foundation, Inc.
5 |
6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7 |
8 | This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
9 |
10 | 0. Additional Definitions.
11 | As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
12 |
13 | “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
14 |
15 | An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
16 |
17 | A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
18 |
19 | The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
20 |
21 | The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
22 |
23 | 1. Exception to Section 3 of the GNU GPL.
24 | You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
25 |
26 | 2. Conveying Modified Versions.
27 | If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
28 |
29 | a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
30 | b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
31 | 3. Object Code Incorporating Material from Library Header Files.
32 | The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
33 |
34 | a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
35 | b) Accompany the object code with a copy of the GNU GPL and this license document.
36 | 4. Combined Works.
37 | You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
38 |
39 | a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
40 | b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
41 | c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
42 | d) Do one of the following:
43 | 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
44 | 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
45 | e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
46 | 5. Combined Libraries.
47 | You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
48 |
49 | a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
50 | b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
51 | 6. Revised Versions of the GNU Lesser General Public License.
52 | The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
53 |
54 | Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
55 |
56 | If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Synopsis
2 |
3 | :- use_module(library(mavis)).
4 |
5 | %% even(+X:integer) is semidet.
6 | even(X) :-
7 | 0 is X mod 2.
8 |
9 | # Description
10 |
11 | The =mavis= module (because she helps with typing ;-) allows one to
12 | use optional type declarations in Prolog code. During *development*,
13 | these declarations throw informative exceptions when values don't match
14 | types. A typical development environment converts this into a helpful
15 | stack track which assists in locating the error.
16 |
17 | In *production*, the declarations are completely removed by macros
18 | and do nothing. Production time is defined as any time when optimization is enabled:
19 | `current_prolog_flag(optimise, true)`.
20 |
21 | Type declarations can be give manually by calling the/2. `mavis` also inserts
22 | type declarations for you based on your PlDoc structured comments. For
23 | example, during development, the definition of `even` above becomes
24 |
25 | even(A) :-
26 | the(integer, A),
27 | 0 is A mod 2.
28 |
29 | The library also takes into account groundedness and determinsm as
30 | specified in the mode line given to PlDoc. Currently the library recognises
31 |
32 | `erroneous`, `failure`,`semidet`,`det`,`multi`,`nondet`
33 |
34 | The different determinism qualifiers are interpreted as follows:
35 |
36 | * `failure`: 0 solutions
37 | * `semidet`: 0 or 1 solution
38 | * `det`: 1 solution
39 | * `multi`: more than one solution
40 | * `nondet`: Any number of solutions including 0
41 |
42 | The groundedness currently must be one of:
43 |
44 | `++`,`+`,`?`,`--`,`-`,`:`,`@`,`!`
45 |
46 | These are interpreted as follows:
47 |
48 | * `++` means *completely* ground on entry.
49 | * `+` means ground in a way compatible with type declaration. For `any`,
50 | this provides no checkable information.
51 | * `?` means either ground, unground or mixed. If it is not a variable, we will demote the determinism as follows:
52 | - `det` => `semidet`
53 | - `multi` => `nondet`
54 | * `--` means variable input, and type compatible output.
55 | * `-` means an output parameter. The output should be compatible with the type. If it is not a variable, we will demote the determinism as follows:
56 | - `det` => `semidet`
57 | - `multi` => `nondet`
58 | * `:` means a goal. Currently no checking is done.
59 | * `@` means not further bound than on input. Currently no checking is done.
60 | * `!` means side-effectable variable. Currently no checking is done.
61 |
62 | "Compatibility" means that running the double-negated type over the
63 | variable is successful, i.e. the input structure which is defined does
64 | not contradict the type.
65 |
66 | ## Why?
67 |
68 | We love dynamic types. That's one reason we love Prolog. But
69 | sometimes it is useful to distinguish between a failure, and an
70 | incorrect utlisation of the calling contract. Types can:
71 |
72 | * offer documentation to those reading our code
73 | * help find errors during development
74 | * structure our thinking during development
75 | * provide data for static analysis tools
76 |
77 | # Defining new types
78 |
79 | Mavis types are defined using error:has_type/2. We might define an
80 | `even_integer` type with
81 |
82 | error:has_type(even_integer, X) :-
83 | 0 is X mod 2.
84 |
85 | We can use the definition manually:
86 |
87 | frobnify(A, B) :-
88 | the(integer, A),
89 | the(even_integer, B),
90 | B is 2*A.
91 |
92 | or simply add it to our PlDoc comments:
93 |
94 | %% frobnify(+A:integer, -B:even_integer)
95 | frobnify(A, B) :-
96 | B is 2*A.
97 |
98 | We can declare types for bound variables, like `A`, and
99 | not-yet-bound variables, like `B`. The type constraints are implemented
100 | with when/2 so they apply as soon as a variable is ground.
101 |
102 | To disable type checking in production, start Prolog with the
103 | `-O` command line argument. A macro eliminates calls to the/2 so they
104 | have no runtime overhead.
105 |
106 | # Changes in this Version
107 |
108 | * Fix packaging error
109 | * Add determinism checking
110 | * Add groundedness checking
111 |
112 | # TODO
113 |
114 | There should be a less ad-hoc method of mode selection. It would also
115 | be useful to extend the groundedness criteria
116 |
117 | In future versions we hope to incorporate a gradual typing discipline
118 | using abstract interpretation. This could potentially find type,
119 | groundedness and determinacy errors before we have run the
120 | program. Ultimately it may also provide performance improvements.
121 |
122 | It would also be very nice to include polymorphism, however, this
123 | requires that we have some way to select a type. As there is no
124 | principle typing, this is potentially a (very interesting) can of
125 | worms.
126 |
127 | Also of some interest would be dependent type checking, which at least
128 | in the dynamic case, might be tractable.
129 |
130 | # Issues
131 |
132 | When using metapredicates such as maplist, goal expansion will get
133 | confused and generate incorrect clauses unless the predicate has the
134 | appropriate number of arguments. This can be achieved by wrapping the
135 | call in a suitable lambda form. e.g. If p is given a modeline then:
136 |
137 | ```
138 | maplist(p,Xs,Ys)
139 | ```
140 |
141 | should be replaced with:
142 |
143 | ```
144 | maplist([X,Y]>>(p(X,Y)),Xs,Ys
145 | ```
146 |
147 | # Installation
148 |
149 | Using SWI-Prolog 6.3.16 or later:
150 |
151 | $ swipl
152 | 1 ?- pack_install(mavis).
153 |
154 | Source code available and pull requests accepted on GitHub:
155 | https://github.com/GavinMendelGleason/mavis
156 |
157 | # Authors
158 |
159 | * Michael Hendricks
160 | * Gavin Mendel-Gleason
161 |
--------------------------------------------------------------------------------
/dev.pl:
--------------------------------------------------------------------------------
1 | :- debug(mavis).
2 | :- user:asserta(file_search_path(library,prolog)).
3 | :- guitracer.
4 |
--------------------------------------------------------------------------------
/pack.pl:
--------------------------------------------------------------------------------
1 | name(mavis).
2 | title('Optional type declarations').
3 |
4 | version('0.2.3').
5 | download('http://packs.ndrix.com/mavis/mavis-0.2.3.tgz').
6 |
7 | keywords([types]).
8 |
9 | requires(list_util).
10 | requires(quickcheck).
11 |
12 | author( 'Michael Hendricks', 'michael@ndrix.org' ).
13 | packager( 'Michael Hendricks', 'michael@ndrix.org' ).
14 | maintainer( 'Michael Hendricks', 'michael@ndrix.org' ).
15 | home('http://packs.ndrix.com/mavis/index.html').
16 |
--------------------------------------------------------------------------------
/prolog/mavis.pl:
--------------------------------------------------------------------------------
1 | :- module(mavis, [ the/2
2 | , has_intersection/2
3 | , has_subtype/2
4 | , known_type/1
5 | , build_type_assertions/3
6 | , build_determinism_assertions/2
7 | , run_goal_at_mode/4
8 | ]).
9 |
10 |
11 | :- use_module(library(quickcheck)).
12 | :- use_module(library(error)).
13 |
14 |
15 | /** Optional type declarations
16 | Declare optional types which are checked during development time.
17 | See pack documentation for more information.
18 | */
19 |
20 | module_wants_mavis(Module) :-
21 | Module \= mavis,
22 | predicate_property(Module:the(_,_), imported_from(mavis)).
23 |
24 | %% the(+Type:type, ?Value) is det.
25 | %
26 | % Declare that Value has the given Type.
27 | % Succeeds if Value is bound to a value that's compatible
28 | % with Type. Throws an informative exception if Value
29 | % is bound to a value that's not compatible with Type.
30 | % If Value is not bound, the type check is delayed until
31 | % Value becomes ground.
32 | %
33 | % When optimizations are enabled
34 | % (=|current_prolog_flag(optimise, true)|=) a macro removes =the=
35 | % entirely so that it always succeeds.
36 | :- if(current_prolog_flag(optimise,true)).
37 |
38 | the(_,_). % avoid "Exported procedure mavis:the/2 is not defined"
39 | user:goal_expansion(the(_,_), true).
40 |
41 | build_determinism_assertions(_,_) :- fail.
42 | build_type_assertions(_,_,_) :- fail.
43 | run_goal_at_mode(_,_,_,_) :- fail.
44 |
45 | :- else.
46 |
47 | :- use_module(library(apply), [exclude/3]).
48 | :- use_module(library(charsio), [read_term_from_chars/3]).
49 | :- use_module(library(list_util), [xfy_list/3,split_at/4]).
50 | :- use_module(library(pldoc)).
51 | :- use_module(library(pldoc/doc_wiki), [indented_lines/3]).
52 | :- use_module(library(when), [when/2]).
53 | :- doc_collect(true).
54 |
55 | % extract mode declaration from a structured comment
56 | mode_declaration(Comment, ModeCodes) :-
57 | string_to_list(Comment, Codes),
58 | phrase(pldoc_process:structured_comment(Prefixes,_), Codes, _),
59 | indented_lines(Codes, Prefixes, Lines),
60 | pldoc_modes:mode_lines(Lines, ModeCodes, [], _).
61 |
62 | % There may be more varieties of this that we have to handle
63 | % see read_term/2
64 | end_pos(Pos,End) :-
65 | ( Pos=term_position(_, End, _, _, _)
66 | -> true
67 | ; Pos=_-End).
68 |
69 | exhaustive_read_term(Codes,[Term|Terms]) :-
70 | Options = [module(pldoc_modes),
71 | variable_names(Vars),
72 | subterm_positions(Pos)],
73 | read_term_from_chars(Codes,Term,Options),
74 | end_pos(Pos,End),
75 | Term \= end_of_file,
76 | !,
77 | maplist(call,Vars),
78 | Next is End + 2, % one for 0 offset, one for '.'
79 | split_at(Next,Codes,_,NewCodes),
80 | exhaustive_read_term(NewCodes,Terms).
81 | exhaustive_read_term(_Codes,[]).
82 |
83 | % read all mode declarations from character codes
84 | read_mode_declarations(ModeCodes, Modes) :-
85 | exhaustive_read_term(ModeCodes, Modes).
86 |
87 | % convert mode declarations to a standard form
88 | normalize_mode(Mode0, Args, Det) :-
89 | (Mode0 = is(Mode1, Det) -> true; Mode1=Mode0, Det=nondet),
90 | (Mode1 = //(Mode2) -> Slash='//'; Mode2=Mode1, Slash='/' ),
91 | _ = Slash, % avoid singleton warnings (until Slash is needed)
92 | Mode2 =.. [_|RawArgs],
93 | maplist(normalize_args, RawArgs, Args).
94 |
95 | normalize_args(X0, arg(Mode,Name,Type)) :-
96 | ( var(X0) -> X1 = ?(X0:any) ; X1=X0 ),
97 | ( X1 =.. [Mode0,Arg] -> true; Mode0='?', Arg=X1 ),
98 | ( member(Mode0, [++,+,-,--,?,:,@,!]) -> Mode=Mode0; Mode='?' ),
99 | ( nonvar(Arg), Arg=Name:Type -> true; Name=Arg, Type=any).
100 |
101 | the(Type, Value) :-
102 | when(ground(Value), error:must_be(Type, Value)).
103 |
104 | % create a the/2 type assertion based on a variable and
105 | % the declared mode information for that variable.
106 | type_declaration(Var, arg(_,_,Type), the(Type, Var)).
107 |
108 | % convert a clause head into a goal which asserts all types
109 | % associated with that head. Slash is '/' for a normal
110 | % predicate and '//' for a DCG. Pneumonic: foo/1 vs foo//1
111 | build_type_assertions(Slash, Head, TypeGoal) :-
112 | % does this module want mavis type assertions?
113 | prolog_load_context(module, Module),
114 | mavis:module_wants_mavis(Module),
115 |
116 | % fetch this predicate's structured comment
117 | functor(Head, Name, Arity),
118 | Indicator =.. [Slash, Name, Arity],
119 | pldoc_process:doc_comment(Module:Indicator,_,_,Comment),
120 |
121 | % parse and normalize mode description
122 | mode_declaration(Comment, ModeText),
123 | %debug(mavis, "~q has modeline `~s`~n", [Module:Indicator, ModeText]),
124 | % Warning: Potential bug!!!
125 | % We assume type consistency between modes...
126 | %debug(mavis, "~q has modeline `~s`~n", [Module:Indicator, ModeText]),
127 | read_mode_declarations(ModeText, [RawMode|_]),
128 | debug(mavis, "~q has types from `~q`~n", [Module:Indicator, RawMode]),
129 | normalize_mode(RawMode, ModeArgs, _Determinism),
130 |
131 | Head =.. [Name|HeadArgs],
132 | maplist(type_declaration, HeadArgs, ModeArgs, AllTypes),
133 | exclude(=@=(the(any, _)), AllTypes, Types),
134 | xfy_list(',', TypeGoal, Types).
135 |
136 | build_determinism_assertions(Goal,Wrapped) :-
137 | % does this module want mavis type assertions?
138 | prolog_load_context(module, Module),
139 | mavis:module_wants_mavis(Module),
140 |
141 | % fetch this predicate's structured comment
142 | functor(Goal, Name, Arity),
143 | Indicator =.. ['/', Name, Arity],
144 |
145 | pldoc_process:doc_comment(Module:Indicator,_,_,Comment),
146 |
147 | % parse and normalize mode description
148 | mode_declaration(Comment, ModeText),
149 | read_mode_declarations(ModeText, RawModes),
150 | % fail if there are no mode declarations (to leave the goal unchanged)
151 | \+ RawModes = [],
152 | maplist([RawMode,mode(ModeArgs,Determinism)]>>normalize_mode(RawMode, ModeArgs, Determinism),
153 | RawModes,Modes),
154 | %%debug(mavis, "~q has modeline `~s`~n", [Module:Indicator, Modes]),
155 | % We should really check for mode consistency here.
156 |
157 | Goal =.. [Name|Args],
158 | Wrapped = mavis:run_goal_at_mode(Module,Name,Modes,Args).
159 |
160 | % pre_check_groundedness(arg(Groundedness,_,Type),Arg,Demote) is det.
161 | % Promote holds a 0 or 1 depending on whether we should demote
162 | % in the event of increased nondeterminism.
163 | pre_check_groundedness(arg('++',_,Type),Arg,0) :-
164 | ground(Arg),
165 | ( \+ error:has_type(Type,Arg)
166 | -> throw(domain_error(Type,Arg))
167 | ; true).
168 | pre_check_groundedness(arg('+',_,Type),Arg,0) :-
169 | % This will be type checked too late due to suspension
170 | % unless we do it now.
171 | % (negation avoids bindings)
172 | \+ var(Arg),
173 | ( \+ error:has_type(Type,Arg)
174 | -> throw(domain_error(Type,Arg))
175 | ; true).
176 | pre_check_groundedness(arg('-',_,_),Arg,Demote) :-
177 | ( var(Arg)
178 | -> Demote = 0
179 | ; Demote = 1).
180 | pre_check_groundedness(arg('--',_,_),Arg,0) :-
181 | var(Arg).
182 | pre_check_groundedness(arg('?',_,_),Arg,Demote) :-
183 | ( var(Arg)
184 | -> Demote = 0
185 | ; Demote = 1).
186 | pre_check_groundedness(arg(':',_,_),_Arg,0).
187 | pre_check_groundedness(arg('!',_,_),_Arg,0).
188 | pre_check_groundedness(arg('@',_,_),_Arg,0).
189 |
190 | post_check_groundedness(arg('-',_,Type),Arg) :-
191 | !,
192 | ( \+ error:has_type(Type,Arg)
193 | -> throw(domain_error(Type,Arg))
194 | ; true).
195 | post_check_groundedness(arg('--',_,Type),Arg) :-
196 | !,
197 | ( \+ error:has_type(Type,Arg)
198 | -> throw(domain_error(Type,Arg))
199 | ; true).
200 | post_check_groundedness(arg(_,_,_),_Arg).
201 |
202 | demote(det,1,semidet).
203 | demote(multi,1,nondet).
204 | demote(fail,1,fail).
205 | demote(semidet,1,semidet).
206 | demote(nondet,1,nondet).
207 | demote(erroneous,1,erroneous).
208 | demote(X,0,X).
209 |
210 | choose_mode([mode(Mode,Determinism)|_Modes],Args,_Module,_Name,
211 | mode(Mode,DeterminismPrime)) :-
212 | maplist(pre_check_groundedness,Mode,Args,DemotionVotes),
213 | foldl([X,Y,R]>>(R is X \/ Y),DemotionVotes,0,Demote),
214 | demote(Determinism,Demote,DeterminismPrime),
215 | !.
216 | choose_mode([_|Modes],Args,Module,Name,Mode) :-
217 | choose_mode(Modes,Args,Module,Name,Mode).
218 |
219 | run_goal_at_mode(Module,Name,Modes,Args) :-
220 | Goal =.. [Name|Args],
221 | ( choose_mode(Modes,Args,Module,Name,mode(Mode,Determinism))
222 | -> true
223 | ; throw(mode_error(Modes,apply(Module:Name,Args)))),
224 | run_goal_with_determinism(Determinism,Module,Goal),
225 | ( maplist(post_check_groundedness,Mode,Args)
226 | -> true
227 | ; throw(mode_error(Modes,apply(Module:Name,Args)))).
228 |
229 | run_goal_with_determinism(erroneous,Module,Goal) :-
230 | !,
231 | throw(determinism_error(Module:Goal,erroneous)).
232 | run_goal_with_determinism(failure,Module,Goal) :-
233 | !,
234 | call(Module:Goal),
235 | throw(determinism_error(Module:Goal,failure)).
236 | run_goal_with_determinism(det,Module,Goal) :-
237 | !,
238 | ( call_cleanup(Module:Goal, Det=true),
239 | ( Det == true
240 | -> true
241 | ; throw(determinism_error(Module:Goal, det))
242 | )
243 | -> true
244 | ; throw(determinism_error(Module:Goal, det))
245 | ).
246 | run_goal_with_determinism(semidet,Module,Goal) :-
247 | !,
248 | ( call_cleanup(Module:Goal, Det=true),
249 | ( Det == true
250 | -> true
251 | ; throw(determinism_error(Module:Goal, semidet))
252 | )
253 | -> true
254 | ; fail
255 | ).
256 | run_goal_with_determinism(multi,Module,Goal) :-
257 | !,
258 | ( call(Module:Goal)
259 | *-> true
260 | ; throw(determinism_error(Module:Goal,multi))
261 | ).
262 | run_goal_with_determinism(_,Module,Goal) :-
263 | call(Module:Goal).
264 |
265 | bodyless_predicate(Term) :-
266 | \+ Term = (:-_),
267 | \+ Term = (_:-_),
268 | \+ Term = (_-->_),
269 | \+ Term = end_of_file.
270 |
271 | user:term_expansion((Head:-Body), (Head:-TypeGoal,Body)) :-
272 | Slash = '/',
273 | build_type_assertions(Slash, Head, TypeGoal).
274 |
275 | user:term_expansion(Head,(Head:-TypeGoal)) :-
276 | bodyless_predicate(Head),
277 | Slash = '/',
278 | build_type_assertions(Slash, Head, TypeGoal).
279 |
280 | user:term_expansion((Head-->Body), (Head-->{TypeGoal},Body)) :-
281 | Slash = '//',
282 | build_type_assertions(Slash, Head, TypeGoal).
283 |
284 | % TODO:
285 | % We need to check mode assignments and discover if they are
286 | % A) disjoint
287 | % a) if they are disjoint we need to check groundedness
288 | % 1) Add dynamic check groudedness.
289 | % 2) Do a separate determinism check per groudedness.
290 | % b) Throw runtime error if not disjoint.
291 | %
292 | % TODO:
293 | % Later it would be nice if we had skeletons (ala mercury).
294 | user:goal_expansion(Goal,Wrapped) :-
295 | build_determinism_assertions(Goal,Wrapped),
296 | debug(mavis,'~q => ~q~n', [Goal,Wrapped]).
297 |
298 | :- multifile prolog:message//1.
299 | prolog:message(determinism_error(Goal, Det)) -->
300 | [ 'The Goal ~q is not of determinism ~q'-[Goal,Det]].
301 | prolog:message(domain_error(Domain, Term)) -->
302 | [ 'The term ~q is not in the domain ~q'-[Term,Domain]].
303 | prolog:message(mode_error(Mode, Term)) -->
304 | [ 'The term ~q does not have a valid mode in ~q'-[Term,Mode]].
305 |
306 | :- endif.
307 |
308 |
309 | % below here, code that loads all the time
310 |
311 | %% type_subtype(?Type, ?Subtype)
312 | %
313 | % Multifile predicate for declaring that a Type has a Subtype. It
314 | % should only be necessary to add clauses to this predicate if
315 | % has_subtype/2 has trouble deriving this information based on
316 | % your definition of `quickcheck:arbitrary/2`.
317 | :- dynamic type_subtype/2.
318 | :- multifile type_subtype/2.
319 |
320 | %% has_subtype(+Type, +Subtype) is semidet.
321 | %
322 | % True if all values of Subtype are also values of Type. This can be
323 | % used to determine whether arguments of one type can be passed to a
324 | % predicate which demands arguments of another type.
325 | %
326 | % This predicate performs probabilistic subtype detection by leveraging
327 | % your definitions for `error:has_type/2` and `quickcheck:arbitrary/2`.
328 | % If this predicate is not detecting your types correctly, either
329 | % improve your quickcheck:arbitrary/2 definition or add clauses to
330 | % the multifile predicate type_subtype/2.
331 | has_subtype(Type, Subtype) :-
332 | ( var(Type); var(Subtype) ),
333 | !,
334 | fail.
335 | has_subtype(Type, Subtype) :-
336 | type_subtype(Type, Subtype),
337 | !.
338 | has_subtype(Type, Subtype) :-
339 | error:must_be(nonvar, Type),
340 | error:must_be(arbitrary_type, Subtype),
341 | \+ counter_example(Type, Subtype, _),
342 | assert(type_subtype(Type, Subtype)).
343 |
344 | % find a value (Example) which belongs to Subtype but not
345 | % to Type. This demonstrates that Subtype is not a strict
346 | % subset of Type.
347 | counter_example(Type, Subtype, Example) :-
348 | between(1,100,_),
349 | quickcheck:arbitrary(Subtype, Example),
350 | \+ error:is_of_type(Type, Example),
351 | !.
352 |
353 |
354 | %% type_intersection(?Type, ?IntersectionType)
355 | %
356 | % Multifile predicate for declaring that Type has an IntersectionType.
357 | % See type_subtype/2 for further details.
358 | :- dynamic type_intersection/2.
359 | :- multifile type_intersection/2.
360 |
361 |
362 | %% has_intersection(Type, IntersectionType) is semidet
363 | %
364 | % True if some value of IntersectionType is also of Type. See
365 | % has_subtype/2 for further details.
366 | has_intersection(Type, Intersection) :-
367 | ( var(Type); var(Intersection) ),
368 | !,
369 | fail.
370 | has_intersection(Type, Intersection) :-
371 | type_intersection(Type, Intersection),
372 | !.
373 | has_intersection(Type, Subtype) :-
374 | error:must_be(nonvar, Type),
375 | error:must_be(arbitrary_type, Subtype),
376 | shared_value(Type, Subtype, _),
377 | assert(type_intersection(Type, Subtype)).
378 |
379 | % Find a value shared by both Type and Subtype
380 | shared_value(Type, Subtype, Value) :-
381 | between(1,100,_),
382 | quickcheck:arbitrary(Subtype, Value),
383 | error:is_of_type(Type, Value),
384 | !.
385 |
386 |
387 | %% known_type(?Type:type) is semidet.
388 | %
389 | % True if Type is a type known to error:has_type/2. Iterates
390 | % all known types on backtracking. Be aware that some types are
391 | % polymorphic (like `list(T)`) so Type may be a non-ground term.
392 | %
393 | % As a convenience, the type named `type` describes the set of all
394 | % values for which `known_type/1` is true.
395 | known_type(Type) :-
396 | dif(Type, impossible), % library(error) implementation detail
397 | clause(error:has_type(Type, _), _Body, _Ref).
398 |
399 |
400 | :- multifile error:has_type/2.
401 | error:has_type(type, T) :-
402 | known_type(T).
403 |
--------------------------------------------------------------------------------
/prolog/readme.txt:
--------------------------------------------------------------------------------
1 | ../README.md
--------------------------------------------------------------------------------
/t/determinism.pl:
--------------------------------------------------------------------------------
1 | :- use_module(library(mavis)).
2 | :- use_module(library(tap)).
3 |
4 | %! even(+X:integer) is semidet.
5 | even(X) :-
6 | 0 is X mod 2.
7 |
8 | %! is_graph(+Graph) is semidet.
9 | %
10 | % True if Graph is a well formed graph
11 | is_graph(graph(Instance,Inference,Schema)) :-
12 | atom(Instance),
13 | atom(Inference),
14 | atom(Schema).
15 |
16 | error:has_type(graph, X) :-
17 | is_graph(X).
18 |
19 | :- multifile quickcheck:arbitrary/2.
20 | quickcheck:arbitrary(graph, graph(A,B,C)) :-
21 | arbitrary(atom, A),
22 | arbitrary(atom, B),
23 | arbitrary(atom, C).
24 |
25 | %! graph_instance(+Graph:graph, ?GraphName:atom) is det.
26 | graph_instance(graph(Instance,_,_),Instance).
27 |
28 | frobnify(A,B) :-
29 | the(integer,A), A=B.
30 |
31 | brofnify(A,B) :-
32 | the(string,A),A=B.
33 |
34 | %! first_string(+X:list(string), ?Y:string) is det.
35 | first_string([X|_],X).
36 |
37 | %! back_and_forth(+X,-Y) is det.
38 | % back_and_forth(-X,+Y) is semidet.
39 | back_and_forth(X,Y) :-
40 | Y=[1|X].
41 |
42 | %! something(+X:integer,-Y:integer) is det.
43 | something(X,Y) :-
44 | ( even(X)
45 | -> Y is X * 2
46 | ; Y is X * 3
47 | ).
48 |
49 | %! dependent_type(+X:integer,+Y:([A]>>(A
14 | "hello ",
15 | string(Name).
16 |
17 | %% from_name(Codes, Atom, Extra:atom)
18 | from_name(Codes, Atom, Extra) :-
19 | Extra = extra,
20 | atom_codes(Atom, Codes).
21 |
22 | %% lazy(Foo)
23 | lazy(_).
24 |
25 | /**
26 | * elt(+X,List) is nondet.
27 | * elt(-X,+List) is nondet.
28 | *
29 | * Two modelines with no typing information
30 | */
31 | elt(X,L) :-
32 | member(X,L).
33 |
34 | /**
35 | * elt_det(+X:integer,+List:list(integer)) is det.
36 | *
37 | * Two modelines with no typing information
38 | */
39 | elt_det(X,L) :-
40 | ( member(X,L)
41 | -> true
42 | ; false).
43 |
44 |
--------------------------------------------------------------------------------