1 % (c) 2009-2024 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(translate,
6 [print_bexpr_or_subst/1, l_print_bexpr_or_subst/1,
7 print_bexpr/1, debug_print_bexpr/1,
8 nested_print_bexpr/1, nested_print_bexpr_as_classicalb/1,
9 print_bexpr_stream/2,
10 print_components/1,
11 print_bexpr_with_limit/2, print_bexpr_with_limit_and_typing/3,
12 print_unwrapped_bexpr_with_limit/1,print_bvalue/1, l_print_bvalue/1, print_bvalue_stream/2,
13 translate_params_for_dot/2, translate_params_for_dot_nl/2,
14 print_machine/1,
15 translate_machine/3,
16 set_unicode_mode/0, unset_unicode_mode/0, unicode_mode/0,
17 unicode_translation/2, % unicode translation of a symbol/keyword
18 set_latex_mode/0, unset_latex_mode/0, latex_mode/0,
19 set_atelierb_mode/1, unset_atelierb_mode/0,
20 set_force_eventb_mode/0, unset_force_eventb_mode/0,
21 get_translation_mode/1, set_translation_mode/1, unset_translation_mode/1,
22 with_translation_mode/2,
23 get_language_mode/1, set_language_mode/1, with_language_mode/2,
24 translate_bexpression_to_unicode/2,
25 translate_bexpression/2, translate_subst_or_bexpr_in_mode/3,
26 translate_bexpression_with_limit/3, translate_bexpression_with_limit/2,
27 translate_bexpression_to_codes/2,
28 translate_bexpr_to_parseable/2,
29 translate_predicate_into_machine/3, nested_print_sequent_as_classicalb/6,
30 get_bexpression_column_template/4,
31 translate_subst_or_bexpr/2, translate_subst_or_bexpr_with_limit/3,
32 translate_substitution/2, print_subst/1,
33 convert_and_ajoin_ids/2,
34 translate_bvalue/2, translate_bvalue_to_codes/2, translate_bvalue_to_codes_with_limit/3,
35 translate_bvalue_to_parseable_classicalb/2,
36 translate_bvalue_for_dot/2,
37 translate_bvalue_with_limit/3,
38 translate_bvalue_with_type/3, translate_bvalue_with_type_and_limit/4,
39 translate_bvalue_for_expression/3, translate_bvalue_for_expression_with_limit/4,
40 translate_bvalue_with_tlatype/3,
41 translate_bvalue_kind/2,
42 print_state/1,
43 translate_bstate/2, translate_bstate_limited/2, translate_bstate_limited/3,
44 print_bstate/1, print_bstate_limited/3,
45 translate_b_state_to_comma_list/3,
46 translate_context/2, print_context/1,
47 translate_any_state/2,
48 print_value_variable/1,
49 print_cspm_state/1, translate_cspm_state/2,
50 print_csp_value/1, translate_csp_value/2,
51 translate_cspm_expression/2,
52 translate_properties_with_limit/2,
53 translate_event/2,translate_events/2,
54 translate_event_with_target_id/4,
55 translate_event_with_src_and_target_id/4, translate_event_with_src_and_target_id/5,
56 get_non_det_modified_vars_in_target_id/3,
57 translate_event_with_limit/3,
58 translate_state_errors/2,translate_state_error/2,
59 translate_event_error/2,
60 translate_call_stack/2,
61 translate_prolog_constructor/2, translate_prolog_constructor_in_mode/2,
62 get_texpr_top_level_symbol/4,
63 pretty_type/2, % pretty-prints a type (pp_type, translate_type)
64 explain_state_error/3, get_state_error_span/2,
65 explain_event_trace/3,
66 generate_typing_predicates/2, % keeps sequence typing info
67
68 print_raw_machine_terms/1,
69 print_raw_bexpr/1, l_print_raw_bexpr/1,
70 translate_raw_bexpr_with_limit/3,
71
72 print_span/1, print_span_nl/1, translate_span/2,
73 translate_span_with_filename/2,
74 get_definition_context_from_span/2,
75
76 %set_type_to_maximal_texpr/2, type_set/2, % now in typing_tools as create_type_set
77
78 translate_error_term/2, translate_error_term/3,
79 translate_prolog_exception/2,
80
81 set_translation_constants/1, set_translation_context/1,
82 clear_translation_constants/0,
83
84 set_print_type_infos/1,
85 set_print_type_infos/2, reset_print_type_infos/1,
86 suppress_rodin_positions/1, reset_suppress_rodin_positions/1,
87 add_normal_typing_predicates/3,
88
89 install_b_portray_hook/0,remove_b_portray_hook/0,
90
91 translate_eventb_to_classicalb/3,
92 translate_eventb_direct_definition_header/3, translate_eventb_direct_definition_body/2,
93 return_csp_closure_value/2,
94 latex_to_unicode/2, get_latex_keywords/1, get_latex_keywords_with_backslash/1,
95 ascii_to_unicode/2
96
97 ]).
98
99 :- meta_predicate call_pp_with_no_limit_and_parseable(0).
100 :- meta_predicate with_translation_mode(+, 0).
101 :- meta_predicate with_language_mode(+, 0).
102
103 :- use_module(tools).
104 :- use_module(tools_lists,[is_list_simple/1]).
105 :- use_module(extrasrc(json_parser), [json_write_stream/1]).
106
107 :- use_module(module_information).
108 :- module_info(group,tools).
109 :- module_info(description,'This module is responsible for pretty-printing B and CSP, source spans, ...').
110
111 :- use_module(library(lists)).
112 :- use_module(library(codesio)).
113 :- use_module(library(terms)).
114 :- use_module(library(avl)).
115
116 :- use_module(debug).
117 :- use_module(error_manager).
118 :- use_module(self_check).
119 :- use_module(b_global_sets).
120 :- use_module(specfile,[csp_with_bz_mode/0,process_algebra_mode/0,
121 animation_minor_mode/1,set_animation_minor_mode/1,
122 remove_animation_minor_mode/0,
123 animation_mode/1,set_animation_mode/1, csp_mode/0,
124 translate_operation_name/2]).
125 :- use_module(bsyntaxtree).
126 %:- use_module('smv/smv_trans',[smv_print_initialisation/2]).
127 :- use_module(preferences,[get_preference/2, set_preference/2, eclipse_preference/2]).
128 :- use_module(bmachine_structure).
129 :- use_module(avl_tools,[check_is_non_empty_avl/1]).
130
131 :- set_prolog_flag(double_quotes, codes).
132
133 % print a list of expressions or substitutions
134 l_print_bexpr_or_subst([]).
135 l_print_bexpr_or_subst([H|T]) :-
136 print_bexpr_or_subst(H),
137 (T=[] -> true
138 ; (get_texpr_type(H,Type),is_subst_type(Type) -> print('; ') ; print(', '),
139 l_print_bexpr_or_subst(T))
140 ).
141
142 is_subst_type(T) :- var(T),!,fail.
143 is_subst_type(subst).
144 is_subst_type(op(_,_)).
145
146 print_bexpr_or_subst(E) :- get_texpr_type(E,T),is_subst_type(T),!, print_subst(E).
147 print_bexpr_or_subst(precondition(A,B)) :- !, print_subst(precondition(A,B)).
148 print_bexpr_or_subst(any(A,B,C)) :- !, print_subst(any(A,B,C)).
149 print_bexpr_or_subst(select(A)) :- !, print_subst(select(A)). % TO DO: add more cases ?
150 print_bexpr_or_subst(E) :- print_bexpr(E).
151
152 print_unwrapped_bexpr_with_limit(Expr) :- print_unwrapped_bexpr_with_limit(Expr,200).
153 print_unwrapped_bexpr_with_limit(Expr,Limit) :-
154 translate:print_bexpr_with_limit(b(Expr,pred,[]),Limit),nl.
155 debug_print_bexpr(E) :- debug:debug_mode(off) -> true ; print_bexpr(E).
156 print_bexpr(Expr) :- translate_bexpression(Expr,R), write(R).
157 print_bexpr_with_limit(Expr,Limit) :- translate_bexpression_with_limit(Expr,Limit,R), write(R).
158 print_bvalue(Val) :- translate_bvalue(Val,TV), write(TV).
159 print_bexpr_stream(S,Expr) :- translate_bexpression(Expr,R), write(S,R).
160 print_bvalue_stream(S,Val) :- translate_bvalue(Val,R), write(S,R).
161
162 print_bexpr_with_limit_and_typing(Expr,Limit,TypeInfos) :-
163 set_print_type_infos(TypeInfos,CHNG),
164 (get_texpr_type(Expr,pred)
165 -> find_typed_identifier_uses(Expr, TUsedIds),
166 add_typing_predicates(TUsedIds,Expr,Expr2)
167 ; Expr2=Expr),
168 call_cleanup(print_bexpr_with_limit(Expr2,Limit),
169 reset_print_type_infos(CHNG)).
170
171 print_components(C) :- print_components(C,0).
172 print_components([],Nr) :- write('Nr of components: '),write(Nr),nl.
173 print_components([component(Pred,Vars)|T],Nr) :- N1 is Nr+1,
174 write('Component: '), write(N1), write(' over '), write(Vars),nl,
175 print_bexpr(Pred),nl,
176 print_components(T,N1).
177
178 l_print_bvalue([]).
179 l_print_bvalue([H|T]) :- print_bvalue(H), write(' : '),l_print_bvalue(T).
180
181 nested_print_bexpr_as_classicalb(E) :- nested_print_bexpr_as_classicalb2(E,0).
182
183 nested_print_bexpr_as_classicalb2(E,InitialPeanoIndent) :-
184 (animation_minor_mode(X)
185 -> remove_animation_minor_mode,
186 call_cleanup(nested_print_bexpr2(E,InitialPeanoIndent), set_animation_minor_mode(X))
187 ; nested_print_bexpr2(E,InitialPeanoIndent)).
188
189 % can also print lists of predicates and lists of lists, ...
190 nested_print_bexpr(Expr) :- nested_print_bexpr2(Expr,0).
191
192 % a version where one can specify the initial indent in peano numbering
193 nested_print_bexpr2([],_) :- !.
194 nested_print_bexpr2([H],InitialIndent) :- !,nested_print_bexpr2(H,InitialIndent).
195 nested_print_bexpr2([H|T],II) :- !,
196 nested_print_bexpr2(H,II),
197 print_indent(II), write('&'),nl,
198 nested_print_bexpr2(T,II).
199 nested_print_bexpr2(Expr,II) :- nbp(Expr,conjunct,II).
200
201 nbp(b(E,_,Info),Type,Indent) :- !,nbp2(E,Type,Info,Indent).
202 nbp(E,Type,Indent) :- format(user_error,'Missing b/3 wrapper!~n',[]),
203 nbp2(E,Type,[],Indent).
204 nbp2(E,Type,_Info,Indent) :- get_binary_connective(E,NewType,Ascii,LHS,RHS),!,
205 inc_indent(NewType,Type,Indent,NIndent),
206 print_bracket(Indent,NIndent,'('),
207 nbp(LHS,NewType,NIndent),
208 print_indent(NIndent),
209 translate_in_mode(NewType,Ascii,Symbol), print(Symbol),nl,
210 (is_associative(NewType) -> NewTypeR=NewType % no need for parentheses if same operator on right
211 ; NewTypeR=right(NewType)),
212 nbp(RHS,NewTypeR,NIndent),
213 print_bracket(Indent,NIndent,')').
214 nbp2(lazy_let_pred(TID,LHS,RHS),Type,_Info,Indent) :-
215 def_get_texpr_id(TID,ID),!,
216 NewType=lazy_let_pred(TID),
217 inc_indent(NewType,Type,Indent,NIndent),
218 print_indent(Indent), format('LET ~w = (~n',[ID]),
219 nbp(LHS,NewType,NIndent),
220 print_indent(NIndent), print(') IN ('),nl,
221 nbp(RHS,NewType,NIndent),
222 print_indent(NIndent),print(')'),nl.
223 nbp2(negation(LHS),_Type,_Info,Indent) :- !,
224 inc_indent(negation,false,Indent,NIndent),
225 print_indent(Indent),
226 translate_in_mode(negation,'not',Symbol), format('~s(~n',[Symbol]),
227 nbp(LHS,negation,NIndent),
228 print_indent(Indent), print(')'),nl.
229 nbp2(let_predicate(Ids,Exprs,Pred),_Type,_Info,Indent) :- !,
230 inc_indent(let_predicate,false,Indent,NIndent),
231 pp_expr_ids_in_mode(Ids,_LR,Codes,[]),
232 print_indent(Indent),format('#~s.( /* LET */~n',[Codes]),
233 pp_expr_let_pred_exprs(Ids,Exprs,_LimitReached,Codes2,[]),
234 print_indent(Indent), format('~s~n',[Codes2]),
235 print_indent(NIndent), print('&'),nl,
236 nbp(Pred,let_predicate,NIndent),
237 print_indent(Indent), print(')'),nl.
238 nbp2(exists(Ids,Pred),_Type,_Infos,Indent) :- !,
239 inc_indent(exists,false,Indent,NIndent),
240 pp_expr_ids_in_mode(Ids,_LR,Codes,[]),
241 print_indent(Indent),
242 %(member(allow_to_lift_exists,_Infos) -> write('/* LIFT */ ') ; true),
243 exists_symbol(ExistsSymbol,[]), format('~s~s.(~n',[ExistsSymbol,Codes]),
244 nbp(Pred,exists,NIndent),
245 print_indent(Indent), print(')'),nl.
246 nbp2(forall(Ids,LHS,RHS),_Type,_Info,Indent) :- !,
247 inc_indent(forall,false,Indent,NIndent),
248 pp_expr_ids_in_mode(Ids,_LR,Codes,[]),
249 print_indent(Indent),
250 forall_symbol(ForallSymbol,[]), format('~s~s.(~n',[ForallSymbol,Codes]),
251 nbp(LHS,forall,NIndent),
252 print_indent(NIndent),
253 translate_in_mode(implication,'=>',Symbol),print(Symbol),nl,
254 nbp(RHS,forall,NIndent),
255 print_indent(Indent), print(')'),nl.
256 nbp2(if_then_else(Test,LHS,RHS),_Type,_Info,Indent) :- !,
257 inc_indent(if_then_else,false,Indent,NIndent),
258 print_indent(Indent), print('IF'),nl,
259 nbp(Test,if_then_else,NIndent),
260 print_indent(Indent), print('THEN'),nl,
261 nbp(LHS,if_then_else,NIndent),
262 print_indent(Indent), print('ELSE'),nl,
263 nbp(RHS,if_then_else,NIndent),
264 print_indent(Indent), print('END'),nl.
265 %nbp2(equal(LHS,RHS),pred,_Info,Indent) :-
266 % get_texpr_id(LHS,_Id),!,
267 % print_indent(Indent),print_bexpr(LHS),print(' ='),nl,
268 % inc_indent(equal,false,Indent,NIndent),
269 nbp2(value(V),_,Info,Indent) :- !,
270 print_indent(Indent), print_bexpr(b(value(V),any,Info)),nl.
271 nbp2(E,_,Info,Indent) :- print_indent(Indent), print_bexpr(b(E,pred,Info)),nl.
272
273 % all left-associative
274 get_binary_connective(conjunct(LHS,RHS),conjunct,'&',LHS,RHS).
275 get_binary_connective(disjunct(LHS,RHS),disjunct,'or',LHS,RHS).
276 get_binary_connective(implication(LHS,RHS),implication,'=>',LHS,RHS).
277 get_binary_connective(equivalence(LHS,RHS),equivalence,'<=>',LHS,RHS).
278
279 inc_indent(Type,CurType,I,NewI) :- (Type=CurType -> NewI=I ; NewI=s(I)).
280 print_bracket(I,I,_) :- !.
281 print_bracket(I,_NewI,Bracket) :-
282 print_indent(I), print(Bracket),nl.
283
284 print_indent(s(X)):- !,
285 print(' '),
286 print_indent(X).
287 print_indent(_).
288
289
290 /* =============================================== */
291 /* Translating expressions and values into strings */
292 /* =============================================== */
293
294 translate_params_for_dot(List,TransList) :-
295 translate_params_for_dot(List,TransList,3,-3).
296 translate_params_for_dot_nl(List,TransList) :- % newline after every entry
297 translate_params_for_dot(List,TransList,1,-1).
298
299 translate_params_for_dot([],'',_,_).
300 translate_params_for_dot([H|T],Res,Lim,Nr) :-
301 translate_property_with_limit(H,100,TH),
302 (Nr>=Lim -> N1=1 % Limit reached, add newline
303 ; N1 is Nr+1),
304 translate_params_for_dot(T,TT,Lim,N1),
305 string_concatenate(TH,TT,Res1),
306 (N1=1
307 -> string_concatenate(',\n',Res1,Res)
308 ; (Nr>(-Lim) -> string_concatenate(',',Res1,Res)
309 ; Res=Res1)).
310
311
312 translate_channel_values(X,['_'|T],T) :- var(X),!.
313 translate_channel_values([],S,S) :- !.
314 translate_channel_values([tuple([])|T],S,R) :- !,
315 translate_channel_values(T,S,R).
316 translate_channel_values([in(tuple([]))|T],S,R) :- !,
317 translate_channel_values(T,S,R).
318 translate_channel_values([H|T],['.'|S],R) :- !,
319 ((nonvar(H),H=in(X))
320 -> Y=X
321 ; Y=H
322 ),
323 pp_csp_value(Y,S,S2),
324 translate_channel_values(T,S2,R).
325 translate_channel_values(tail_in(X),S,T) :-
326 (X=[] ; X=[_|_]), !, translate_channel_values(X,S,T).
327 translate_channel_values(_X,['??'|S],S).
328
329
330
331 pp_single_csp_value(V,'_') :- var(V),!.
332 pp_single_csp_value(X,'_cyclic_') :- cyclic_term(X),!.
333 pp_single_csp_value(int(X),A) :- atomic(X),!,number_chars(X,Chars),atom_chars(A,Chars).
334
335 :- assert_must_succeed((translate_cspm_expression(listExp(rangeOpen(2)),R), R == '<2..>')).
336 :- assert_must_succeed((translate_cspm_expression(listFrom(2),R), R == '<2..>')).
337 :- assert_must_succeed((translate_cspm_expression(listFromTo(2,6),R), R == '<2..6>')).
338 :- assert_must_succeed((translate_cspm_expression(setFromTo(2,6),R), R == '{2..6}')).
339 :- assert_must_succeed((translate_cspm_expression('#'(listFromTo(2,6)),R), R == '#<2..6>')).
340 :- assert_must_succeed((translate_cspm_expression(inGuard(x,setFromTo(1,5)),R), R == '?x:{1..5}')).
341 :- assert_must_succeed((translate_cspm_expression(builtin_call(int(3)),R), R == '3')).
342 :- assert_must_succeed((translate_cspm_expression(set_to_seq(setValue([int(1),int(2)])),R), R == 'seq({1,2})')).
343 :- assert_must_succeed((translate_cspm_expression(diff(setValue([int(1)]),setValue([])),R), R == 'diff({1},{})')).
344 :- assert_must_succeed((translate_cspm_expression(inter(setValue([int(1)]),setValue([])),R), R == 'inter({1},{})')).
345 :- assert_must_succeed((translate_cspm_expression(lambda([x,y],'*'(x,y)),R), R == '\\ x,y @ (x*y)')).
346 :- assert_must_succeed((translate_cspm_expression(lambda([x,y],'/'(x,y)),R), R == '\\ x,y @ (x/y)')).
347 :- assert_must_succeed((translate_cspm_expression(lambda([x,y],'%'(x,y)),R), R == '\\ x,y @ (x%y)')).
348 :- assert_must_succeed((translate_cspm_expression(rename(x,y),R), R == 'x <- y')).
349 :- assert_must_succeed((translate_cspm_expression(link(x,y),R), R == 'x <-> y')).
350 :- assert_must_succeed((translate_cspm_expression(agent_call_curry(f,[[a,b],[c]]),R), R == 'f(a,b)(c)')).
351
352 translate_cspm_expression(Expr, Text) :-
353 (pp_csp_value(Expr,Atoms,[]) -> ajoin(Atoms,Text)
354 ; print('Pretty printing expression failed: '),print(Expr),nl).
355
356 pp_csp_value(X,[A|S],S) :- pp_single_csp_value(X,A),!.
357 pp_csp_value(setValue(L),['{'|S],T) :- !,pp_csp_value_l(L,',',S,['}'|T],inf).
358 pp_csp_value(setExp(rangeEnum(L)),['{'|S],T) :- !,pp_csp_value_l(L,',',S,['}'|T],inf).
359 pp_csp_value(setExp(rangeEnum(L),Gen),['{'|S],T) :- !,
360 copy_term((L,Gen),(L2,Gen2)), numbervars((L2,Gen2),1,_),
361 pp_csp_value_l(L2,',',S,['|'|S2],inf),
362 pp_csp_value_l(Gen2,',',S2,['}'|T],inf).
363 pp_csp_value(avl_set(A),['{'|S],T) :- !, check_is_non_empty_avl(A),
364 avl_domain(A,L),pp_csp_value_l(L,',',S,['}'|T],inf).
365 pp_csp_value(setExp(rangeClosed(L,U)),['{'|S],T) :- !, pp_csp_value(L,S,['..'|S2]),pp_csp_value(U,S2,['}'|T]).
366 pp_csp_value(setExp(rangeOpen(L)),['{'|S],T) :- !, pp_csp_value(L,S,['..}'|T]).
367 % TO DO: pretty print comprehensionGuard; see prints in coz-example.csp ; test 1846
368 pp_csp_value(comprehensionGenerator(Var,Body),S,T) :- !, pp_csp_value(Var,S,['<-'|S1]),
369 pp_csp_value(Body,S1,T).
370 pp_csp_value(listExp(rangeEnum(L)),['<'|S],T) :- !,pp_csp_value_l(L,',',S,['>'|T],inf).
371 pp_csp_value(listExp(rangeClosed(L,U)),['<'|S],T) :- !, pp_csp_value(L,S,['..'|S2]),pp_csp_value(U,S2,['>'|T]).
372 pp_csp_value(listExp(rangeOpen(L)),['<'|S],T) :- !, pp_csp_value(L,S,['..>'|T]).
373 pp_csp_value(setFromTo(L,U),['{'|S],T) :- !,
374 pp_csp_value(L,S,['..'|S2]),pp_csp_value(U,S2,['}'|T]).
375 pp_csp_value(setFrom(L),['{'|S],T) :- !,
376 pp_csp_value(L,S,['..}'|T]).
377 pp_csp_value(closure(L), ['{|'|S],T) :- !,pp_csp_value_l(L,',',S,['|}'|T],inf).
378 pp_csp_value(list(L),['<'|S],T) :- !,pp_csp_value_l(L,',',S,['>'|T],inf).
379 pp_csp_value(listFromTo(L,U),['<'|S],T) :- !,
380 pp_csp_value(L,S,['..'|S2]),pp_csp_value(U,S2,['>'|T]).
381 pp_csp_value(listFrom(L),['<'|S],T) :- !,
382 pp_csp_value(L,S,['..>'|T]).
383 pp_csp_value('#'(L),['#'|S],T) :- !,pp_csp_value(L,S,T).
384 pp_csp_value('^'(X,Y),S,T) :- !,pp_csp_value(X,S,['^'|S1]), pp_csp_value(Y,S1,T).
385 pp_csp_value(linkList(L),S,T) :- !,pp_csp_value_l(L,',',S,T,inf).
386 pp_csp_value(in(X),['?'|S],T) :- !,pp_csp_value(X,S,T).
387 pp_csp_value(inGuard(X,Set),['?'|S],T) :- !,pp_csp_value(X,S,[':'|S1]),
388 pp_csp_value(Set,S1,T).
389 pp_csp_value(out(X),['!'|S],T) :- !,pp_csp_value(X,S,T).
390 pp_csp_value(alsoPat(X,_Y),S,T) :- !,pp_csp_value(X,S,T).
391 pp_csp_value(appendPat(X,_Fun),S,T) :- !,pp_csp_value(X,S,T).
392 pp_csp_value(tuple(vclosure),S,T) :- !, S=T.
393 pp_csp_value(tuple([X]),S,T) :- !,pp_csp_value_in(X,S,T).
394 pp_csp_value(tuple([X|vclosure]),S,T) :- !,pp_csp_value_in(X,S,T).
395 pp_csp_value(tuple([H|TT]),S,T) :- !,pp_csp_value_in(H,S,['.'|S1]),pp_csp_value(tuple(TT),S1,T).
396 pp_csp_value(dotTuple([]),['unit_channel'|S],S) :- ! .
397 pp_csp_value(dotTuple([H]),S,T) :- !, pp_csp_value_in(H,S,T).
398 pp_csp_value(dotTuple([H|TT]),S,T) :- !, pp_csp_value_in(H,S,['.'|S1]),
399 pp_csp_value(dotTuple(TT),S1,T).
400 pp_csp_value(tupleExp(Args),S,T) :- !,pp_csp_args(Args,S,T,'(',')').
401 pp_csp_value(na_tuple(Args),S,T) :- !,pp_csp_args(Args,S,T,'(',')').
402 pp_csp_value(record(Name,Args),['('|S],T) :- !,pp_csp_value(tuple([Name|Args]),S,[')'|T]).
403 pp_csp_value(val_of(Name,_Span),S,T) :- !, pp_csp_value(Name,S,T).
404 pp_csp_value(builtin_call(X),S,T) :- !,pp_csp_value(X,S,T).
405 pp_csp_value(seq_to_set(X),['set('|S],T) :- !,pp_csp_value(X,S,[')'|T]).
406 pp_csp_value(set_to_seq(X),['seq('|S],T) :- !,pp_csp_value(X,S,[')'|T]).
407 %pp_csp_value('\\'(B,C,S),S1,T) :- !, pp_csp_process(ehide(B,C,S),S1,T).
408 pp_csp_value(agent_call(_Span,Agent,Parameters),['('|S],T) :- !,
409 pp_csp_value(Agent,S,S1),
410 pp_csp_args(Parameters,S1,[')'|T],'(',')').
411 pp_csp_value(agent_call_curry(Agent,Parameters),S,T) :- !,
412 pp_csp_value(Agent,S,S1),
413 pp_csp_curry_args(Parameters,S1,T).
414 pp_csp_value(lambda(Parameters,Body),['\\ '|S],T) :- !,
415 pp_csp_args(Parameters,S,[' @ '|S1],'',''),
416 pp_csp_value(Body,S1,T).
417 pp_csp_value(rename(X,Y),S,T) :- !,pp_csp_value(X,S,[' <- '|S1]),
418 pp_csp_value(Y,S1,T).
419 pp_csp_value(link(X,Y),S,T) :- !,pp_csp_value(X,S,[' <-> '|S1]),
420 pp_csp_value(Y,S1,T).
421 % binary operators:
422 pp_csp_value(Expr,['('|S],T) :- bynary_numeric_operation(Expr,E1,E2,OP),!,
423 pp_csp_value(E1,S,[OP|S2]),
424 pp_csp_value(E2,S2,[')'|T]).
425 % built-in functions for sets
426 pp_csp_value(empty(A),[empty,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
427 pp_csp_value(card(A),[card,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
428 pp_csp_value('Set'(A),['Set','('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
429 pp_csp_value('Inter'(A1),['Inter','('|S],T) :- !,pp_csp_value(A1,S,[')'|T]).
430 pp_csp_value('Union'(A1),['Union','('|S],T) :- !,pp_csp_value(A1,S,[')'|T]).
431 pp_csp_value(diff(A1,A2),[diff,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
432 pp_csp_value(inter(A1,A2),[inter,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
433 pp_csp_value(union(A1,A2),[union,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
434 pp_csp_value(member(A1,A2),[member,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
435 % built-in functions for sequences
436 pp_csp_value(null(A),[null,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
437 pp_csp_value(length(A),[length,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
438 pp_csp_value(head(A),[head,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
439 pp_csp_value(tail(A),[tail,'('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
440 pp_csp_value(elem(A1,A2),[elem,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
441 pp_csp_value(concat(A1,A2),[concat,'('|S],T) :- !,pp_csp_args([A1,A2],S,[')'|T],'','').
442 pp_csp_value('Seq'(A),['Seq','('|S],T) :- !, pp_csp_value(A,S,[')'|T]).
443 % vclosure
444 pp_csp_value(Expr,S,T) :- is_list(Expr),!,pp_csp_value(closure(Expr),S,T).
445 % Type expressions
446 pp_csp_value(dotTupleType([H]),S,T) :- !, pp_csp_value_in(H,S,T).
447 pp_csp_value(dotTupleType([H|TT]),S,T) :- !,pp_csp_value_in(H,S,['.'|S1]), pp_csp_value(dotTupleType(TT),S1,T).
448 pp_csp_value(typeTuple(Args),S,T) :- !, pp_csp_args(Args,S,T,'(',')').
449 pp_csp_value(dataType(T),[T|S],S) :- ! .
450 pp_csp_value(boolType,['Bool'|S],S) :- ! .
451 pp_csp_value(intType,['Int'|S],S) :- ! .
452 pp_csp_value(dataTypeDef([H]),S,T) :- !, pp_csp_value(H,S,T).
453 pp_csp_value(dataTypeDef([H|TT]),S,T) :- !, pp_csp_value(H,S,['|'|S1]),
454 pp_csp_value(dataTypeDef(TT),S1,T).
455 pp_csp_value(constructor(Name),[Name|S],S) :- ! .
456 pp_csp_value(constructorC(C,Type),[C,'('|S],T) :- !, pp_csp_value(Type,S,[')'|T]).
457 % Argument of function can be process
458
459 pp_csp_value(Expr,S,T) :- pp_csp_process(Expr,S,T),!. % pp_csp_process has a catch-all !!! TO DO: look at this
460 pp_csp_value(Expr,S,T) :- csp_with_bz_mode,!,pp_value(Expr,S,T).
461 pp_csp_value(X, [A|S], S) :- % ['<< ',A,' >>'|S],S) :- % the << >> pose problems when checking against FDR
462 write_to_codes(X,Codes),atom_codes_with_limit(A,Codes).
463
464 pp_csp_value_in(H,S,T) :- nonvar(H),H=in(X),!, pp_csp_value(X,S,T).
465 pp_csp_value_in(H,S,T) :- pp_csp_value(H,S,T).
466
467 print_csp_value(Val) :- pp_csp_value(Val,Atoms,[]), ajoin(Atoms,Text),
468 print(Text).
469
470 translate_csp_value(Val,Text) :- pp_csp_value(Val,Atoms,[]), ajoin(Atoms,Text).
471
472 return_csp_closure_value(closure(S),List) :- pp_csp_value_l1(S,List).
473 return_csp_closure_value(setValue(S),List) :- pp_csp_value_l1(S,List).
474
475 pp_csp_value_l1([Expr|Rest],List) :-
476 ( nonvar(Rest),Rest=[] ->
477 pp_csp_value(Expr,T,[]),ajoin(T,Value),List=[Value]
478 ; pp_csp_value_l1(Rest,R),pp_csp_value(Expr,T,[]),ajoin(T,Value),List=[Value|R]
479 ).
480
481 pp_csp_args([],T,T,_LPar,_RPar).
482 pp_csp_args([H|TT],[LPar|S],T,LPar,RPar) :- pp_csp_value(H,S,S1), pp_csp_args2(TT,S1,T,RPar).
483 pp_csp_args2([],[RPar|T],T,RPar).
484 pp_csp_args2([H|TT],[','|S],T,RPar) :- pp_csp_value(H,S,S1), pp_csp_args2(TT,S1,T,RPar).
485
486 pp_csp_curry_args([],T,T).
487 pp_csp_curry_args([H|TT],S,T) :- is_list(H), pp_csp_args(H,S,S1,'(',')'), pp_csp_curry_args(TT,S1,T).
488
489 pp_csp_value_l(V,_Sep,['...'|S],S,N) :- (var(V) ; (N \= inf -> N<1;fail)), !.
490 pp_csp_value_l([],_Sep,S,S,_).
491 pp_csp_value_l([Expr|Rest],Sep,S,T,Nr) :-
492 ( nonvar(Rest),Rest=[] ->
493 pp_csp_value(Expr,S,T)
494 ;
495 (Nr=inf -> N1 = Nr ; N1 is Nr-1),
496 pp_csp_value(Expr,S,[Sep|S1]),pp_csp_value_l(Rest,Sep,S1,T,N1)).
497
498 :- assert_must_succeed((translate:convert_set_into_sequence([(int(1),int(5))],Seq),
499 check_eqeq(Seq,[int(5)]))).
500 :- assert_must_succeed((translate:convert_set_into_sequence([(int(2),X),(int(1),int(5))],Seq),
501 check_eq(Seq,[int(5),X]))).
502
503 convert_set_into_sequence(Set,Seq) :-
504 nonvar(Set), \+ eventb_translation_mode,
505 convert_set_into_sequence1(Set,Seq).
506 convert_set_into_sequence1(avl_set(A),Seq) :- !, check_is_non_empty_avl(A),
507 avl_size(A,Sz),size_is_in_set_limit(Sz),convert_avlset_into_sequence(A,Seq).
508 convert_set_into_sequence1([],Seq) :- !, Seq=[].
509 convert_set_into_sequence1(Set,Seq) :-
510 convert_set_into_sequence2(Set,0,_,SetElems,Seq),ground(SetElems).
511 convert_set_into_sequence2([],_Max,([],[]),_,_Seq).
512 convert_set_into_sequence2([Pair|T],Max,Last,SetElems,Seq) :-
513 nonvar(Pair),nonvar(T),Pair=(Index,H),ground(Index),
514 Index=int(Nr),
515 insert_el_into_seq(Nr,H,Seq,SetElems,L),
516 (Nr>Max -> NMax=Nr,NLast=L ; NMax=Max,NLast=Last),
517 convert_set_into_sequence2(T,NMax,NLast,SetElems,Seq).
518 insert_el_into_seq(1,H,[H|L],[set|L2],(L,L2)) :- !.
519 insert_el_into_seq(N,H,[_|T],[_|T2],Last) :- N>1, N1 is N-1, insert_el_into_seq(N1,H,T,T2,Last).
520
521 convert_avlset_into_sequence(Avl,Sequence) :-
522 \+ eventb_translation_mode,
523 convert_avlset_into_sequence2(Avl,1,Sequence).
524 convert_avlset_into_sequence2(Avl,_Index,[]) :-
525 empty_avl(Avl),!.
526 convert_avlset_into_sequence2(Avl,Index,[Head|Tail]) :-
527 avl_del_min(Avl, Min, _ ,NewAvl),
528 nonvar(Min), Min=(L,Head),
529 ground(L), L=int(Index),
530 Index2 is Index + 1,
531 convert_avlset_into_sequence2(NewAvl,Index2,Tail).
532
533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
534 % translate new syntax tree -- work in progress
535 :- assert_must_succeed((translate_cspm_state(lambda([x,y],'|~|'(prefix(_,[],x,skip(_),_),prefix(_,[],y,skip(_),_),_)),R), R == 'CSP: \\ x,y @ (x->SKIP) |~| (y->SKIP)')).
536 :- assert_must_succeed((translate_cspm_state(agent_call_curry('F',[[a,b],[c]]),R), R == 'CSP: F(a,b)(c)')).
537 :- assert_must_succeed((translate_cspm_state(ifte(bool_not('<'(x,3)),';'(esharing([a],'/\\'('P1','P2',span),procRenaming([rename(r,s)],'Q',span),span),lParallel([link(b,c)],'R','S',span),span),'[>'(elinkParallel([link(h1,h2)],'G1','G2',span),exception([a],'H1','H2',span),span),span1,span2,span3),R), R == 'CSP: if not((x<3)) then ((P1) /\\ (P2) [|{|a|}|] Q[[r <- s]]) ; (R [{|b <-> c|}] S) else (G1 [{|h1 <-> h2|}] G2) [> (H1 [|{|a|}|> H2)')).
538 :- assert_must_succeed((translate_cspm_state(aParallel([a,b],'P',[b,c],'Q',span),R), R == 'CSP: P [{|a,b|} || {|b,c|}] Q')).
539 :- assert_must_succeed((translate_cspm_state(eaParallel([a,b],'P',[b,c],'Q',span),R), R == 'CSP: P [{|a,b|} || {|b,c|}] Q')).
540 :- assert_must_succeed((translate_cspm_state(eexception([a,b],'P','Q',span),R), R == 'CSP: P [|{|a,b|}|> Q')).
541
542 print_cspm_state(State) :- translate_cspm_state(State,T), print(T).
543
544 translate_cspm_state(State,Text) :-
545 ( pp_csp_process(State,Atoms,[]) -> true
546 ; print(pp_csp_process_failed(State)),nl,Atoms=State),
547 ajoin(['CSP: '|Atoms],Text).
548
549 pp_csp_process(skip(_Span),S,T) :- !, S=['SKIP'|T].
550 pp_csp_process(stop(_Span),S,T) :- !, S=['STOP'|T].
551 pp_csp_process('CHAOS'(_Span,Set),['CHAOS('|S],T) :- !,
552 pp_csp_value(Set,S,[')'|T]).
553 pp_csp_process(val_of(Agent,_Span),S,T) :- !,
554 pp_csp_value(Agent,S,T).
555 pp_csp_process(builtin_call(X),S,T) :- !,pp_csp_process(X,S,T).
556 pp_csp_process(agent(F,Body,_Span),S,T) :- !,
557 F =.. [Agent|Parameters],
558 pp_csp_value(Agent,S,S1),
559 pp_csp_args(Parameters,S1,[' = '|S2],'(',')'),
560 pp_csp_value(Body,S2,T).
561 pp_csp_process(agent_call(_Span,Agent,Parameters),S,T) :- !,
562 pp_csp_value(Agent,S,S1),
563 pp_csp_args(Parameters,S1,T,'(',')').
564 pp_csp_process(agent_call_curry(Agent,Parameters),S,T) :- !,
565 pp_csp_value(Agent,S,S1),
566 pp_csp_curry_args(Parameters,S1,T).
567 pp_csp_process(lambda(Parameters,Body),['\\ '|S],T) :- !,
568 pp_csp_args(Parameters,S,[' @ '|S1],'',''),
569 pp_csp_value(Body,S1,T).
570 pp_csp_process('\\'(B,C,S),S1,T) :- !, pp_csp_process(ehide(B,C,S),S1,T).
571 pp_csp_process(ehide(Body,ChList,_Span),['('|S],T) :- !,
572 pp_csp_process(Body,S,[')\\('|S1]),
573 pp_csp_value(ChList,S1,[')'|T]).
574 pp_csp_process(let(Decls,P),['let '| S],T) :- !,
575 maplist(translate_cspm_state,Decls,Texts),
576 ajoin_with_sep(Texts,' ',Text),
577 S=[Text,' within '|S1],
578 pp_csp_process(P,S1,T).
579 pp_csp_process(Expr,['('|S],T) :- binary_csp_op(Expr,X,Y,Op),!,
580 pp_csp_process(X,S,[') ',Op,' ('|S1]),
581 pp_csp_process(Y,S1,[')'|T]).
582 pp_csp_process(Expr,S,T) :- sharing_csp_op(Expr,X,Middle,Y,Op1,Op2),!,
583 pp_csp_process(X,S,[Op1|S1]),
584 pp_csp_value(Middle,S1,[Op2|S2]),
585 pp_csp_process(Y,S2,T).
586 pp_csp_process(Expr,S,T) :- asharing_csp_op(Expr,X,MiddleX,MiddleY,Y,Op1,MOp,Op2),!,
587 pp_csp_process(X,S,[Op1|S1]),
588 pp_csp_value(MiddleX,S1,[MOp|S2]),
589 pp_csp_value(MiddleY,S2,[Op2|S3]),
590 pp_csp_process(Y,S3,T).
591 pp_csp_process(Expr,S,T) :- renaming_csp_op(Expr,X,RList,Op1,Op2),!,
592 pp_csp_process(X,S,[Op1|S1]),
593 pp_csp_value_l(RList,',',S1,[Op2|T],10).
594 pp_csp_process(prefix(_SPAN1,Values,ChannelExpr,CSP,_SPAN2),S,T) :- !,
595 pp_csp_value_l([ChannelExpr|Values],'',S,['->'|S2],20),
596 pp_csp_process(CSP,S2,T).
597 pp_csp_process('&'(Test,Then),S,T) :- !,
598 pp_csp_bool_expr(Test,S,['&'|S2]),
599 pp_csp_process(Then,S2,T).
600 pp_csp_process(ifte(Test,Then,Else,_SPAN1,_SPAN2,_SPAN3),[' if '|S],T) :- !,
601 pp_csp_bool_expr(Test,S,[' then '|S2]),
602 pp_csp_process(Then,S2,[' else '|S3]),
603 pp_csp_process(Else,S3,T).
604 pp_csp_process(head(A),[head,'('|S],T) :- !, pp_csp_process(A,S,[')'|T]).
605 pp_csp_process(X,[X|T],T).
606
607 pp_csp_bool_expr(bool_not(BE),['not('|S],T) :- !, pp_csp_bool_expr(BE,S,[')'|T]).
608 pp_csp_bool_expr(BE,['('|S],T) :- binary_bool_op(BE,BE1,BE2,OP), !,
609 pp_csp_bool_expr(BE1,S,[OP|S2]),
610 pp_csp_bool_expr(BE2,S2,[')'|T]).
611 pp_csp_bool_expr(BE,[OP,'('|S],T) :- binary_pred(BE,BE1,BE2,OP), !,
612 pp_csp_value(BE1,S,[','|S2]),
613 pp_csp_value(BE2,S2,[')'|T]).
614 pp_csp_bool_expr(BE,S,T) :- pp_csp_value(BE,S,T).
615
616 bynary_numeric_operation('+'(X,Y),X,Y,'+').
617 bynary_numeric_operation('-'(X,Y),X,Y,'-').
618 bynary_numeric_operation('*'(X,Y),X,Y,'*').
619 bynary_numeric_operation('/'(X,Y),X,Y,'/').
620 bynary_numeric_operation('%'(X,Y),X,Y,'%').
621
622 binary_pred('member'(X,Y),X,Y,member).
623 binary_pred('<'(X,Y),X,Y,'<').
624 binary_pred('>'(X,Y),X,Y,'>').
625 binary_pred('>='(X,Y),X,Y,'>=').
626 binary_pred('<='(X,Y),X,Y,'=<').
627 binary_pred('elem'(X,Y),X,Y,is_elem_list).
628 binary_pred('=='(X,Y),X,Y,equal_element).
629 binary_pred('!='(X,Y),X,Y,not_equal_element).
630
631
632 binary_bool_op('<'(X,Y),X,Y,'<').
633 binary_bool_op('>'(X,Y),X,Y,'>').
634 binary_bool_op('>='(X,Y),X,Y,'>=').
635 binary_bool_op('<='(X,Y),X,Y,'=<').
636 binary_bool_op('=='(X,Y),X,Y,'==').
637 binary_bool_op('!='(X,Y),X,Y,'!=').
638 binary_bool_op(bool_and(X,Y),X,Y,'&&').
639 binary_bool_op(bool_or(X,Y),X,Y,'||').
640
641 binary_csp_op('|||'(X,Y,_Span),X,Y,'|||').
642 binary_csp_op('[]'(X,Y,_Span),X,Y,'[]').
643 binary_csp_op('|~|'(X,Y,_Span),X,Y,'|~|').
644 binary_csp_op(';'(X,Y,_Span),X,Y,';').
645 binary_csp_op('[>'(P,Q,_SrcSpan),P,Q,'[>').
646 binary_csp_op('/\\'(P,Q,_SrcSpan),P,Q,'/\\').
647
648 sharing_csp_op(esharing(CList,X,Y,_SrcSpan),X,CList,Y,' [|','|] ').
649 sharing_csp_op(sharing(CList,X,Y,_SrcSpan),X,CList,Y,' [|','|] ').
650 sharing_csp_op(lParallel(LinkList,X,Y,_Span),X,LinkList,Y,' [','] ').
651 sharing_csp_op(elinkParallel(LinkList,X,Y,_Span),X,LinkList,Y,' [','] ').
652 sharing_csp_op(exception(CList,X,Y,_SrcSpan),X,CList,Y,' [|','|> ').
653 sharing_csp_op(eexception(CList,X,Y,_SrcSpan),X,CList,Y,' [|','|> ').
654
655 asharing_csp_op(aParallel(CListX,X,CListY,Y,_SrcSpan),X,CListX,CListY,Y,' [',' || ','] ').
656 asharing_csp_op(eaParallel(CListX,X,CListY,Y,_SrcSpan),X,CListX,CListY,Y,' [',' || ','] ').
657
658 renaming_csp_op(procRenaming(RenameList,X,_SrcSpan),X,RenameList,'[[',']]').
659 renaming_csp_op(eprocRenaming(RenameList,X,_SrcSpan),X,RenameList,'[[',']]').
660
661 :- use_module(bmachine,[b_get_machine_operation_parameter_types/2, b_is_operation_name/1]).
662
663 translate_events([],[]).
664 translate_events([E|Erest],[Out|Orest]) :-
665 translate_event(E,Out),
666 translate_events(Erest,Orest).
667
668
669 % a version of translate_event which has access to the target state id:
670 % this allows to translate setup_constants, intialise by inserting target constants or values
671
672 translate_event_with_target_id(Term,Dst,Limit,Str) :-
673 translate_event_with_src_and_target_id(Term,unknown,Dst,Limit,Str).
674 translate_event_with_src_and_target_id(Term,Src,Dst,Str) :-
675 translate_event_with_src_and_target_id(Term,Src,Dst,5000,Str).
676
677 translate_event_with_src_and_target_id(Term,Src,Dst,Limit,Str) :-
678 get_preference(expand_avl_upto,CurLim),
679 SetLim is Limit//2,% at least two symbols per element
680 (CurLim<0 ; SetLim < CurLim),!,
681 temporary_set_preference(expand_avl_upto,SetLim,CHNG),
682 call_cleanup(translate_event_with_target_id2(Term,Src,Dst,Limit,Str),
683 reset_temporary_preference(expand_avl_upto,CHNG)).
684 translate_event_with_src_and_target_id(Term,Src,Dst,Limit,Str) :-
685 translate_event_with_target_id2(Term,Src,Dst,Limit,Str).
686
687 setup_cst_functor('$setup_constants',"SETUP_CONSTANTS").
688 setup_cst_functor('$partial_setup_constants',"PARTIAL_SETUP_CONSTANTS").
689
690 translate_event_with_target_id2(Term,_,Dst,Limit,Str) :-
691 functor(Term,Functor,_),
692 setup_cst_functor(Functor,UI_Name),
693 get_preference(show_initialisation_arguments,true),
694 state_space:visited_expression(Dst,concrete_constants(State)),
695 get_non_det_constant(State,NonDetState),
696 !,
697 translate_b_state_to_comma_list_codes(UI_Name,NonDetState,Limit,Codes),
698 atom_codes_with_limit(Str,Limit,Codes).
699 translate_event_with_target_id2(Term,_,Dst,Limit,Str) :-
700 functor(Term,'$initialise_machine',_),
701 get_preference(show_initialisation_arguments,true),
702 ? bmachine:b_get_operation_non_det_modifies('$initialise_machine',NDModVars),
703 state_space:visited_expression(Dst,State), get_variables(State,VarsState),
704 (NDModVars \= []
705 ->
706 include(non_det_modified_var(NDModVars),VarsState,ModVarsState) % first show non-det variables
707 % we could add a preference for whether to show the deterministicly assigned variables at all
708 %exclude(non_det_modified_var(NDModVars),VarsState,ModVarsState2),
709 %append(ModVarsState1,ModVarsState2,ModVarsState)
710 ; ModVarsState = VarsState),
711 !,
712 translate_b_state_to_comma_list_codes("INITIALISATION",ModVarsState,Limit,Codes),
713 atom_codes_with_limit(Str,Limit,Codes).
714 translate_event_with_target_id2(Term,Src,Dst,Limit,Str) :-
715 atomic(Term), % only applied to operations without parameters
716 ? specfile:b_mode,
717 get_non_det_modified_vars_in_target_id(Term,Dst,ModVarsState0), % only show non-det variables
718 (Src \= unknown,
719 state_space:visited_expression(Src,SrcState), get_variables(SrcState,PriorVarsState)
720 -> exclude(var_not_really_modified(PriorVarsState),ModVarsState0,ModVarsState)
721 % we could also optionally filter out vars which have the same value for all outgoing transitions of Src
722 ; ModVarsState = ModVarsState0
723 ),
724 !,
725 atom_codes(Term,TermCodes),
726 translate_b_state_to_comma_list_codes(TermCodes,ModVarsState,Limit,Codes),
727 atom_codes_with_limit(Str,Limit,Codes).
728 translate_event_with_target_id2(Term,_,_,Limit,Str) :- translate_event_with_limit(Term,Limit,Str).
729
730
731 get_non_det_modified_vars_in_target_id(OpName,DstId,ModVarsState0) :-
732 bmachine:b_get_operation_non_det_modifies(OpName,NDModVars),
733 NDModVars \= [], % a variable is non-deterministically written
734 state_space:visited_expression(DstId,State), % TO DO: unpack only NModVars
735 get_variables(State,VarsState),
736 include(non_det_modified_var(NDModVars),VarsState,ModVarsState0).
737
738 :- use_module(library(ordsets)).
739 non_det_modified_var(NDModVars,bind(Var,_)) :- ord_member(Var,NDModVars).
740
741 var_not_really_modified(PriorState,bind(Var,Val)) :-
742 ? (member(bind(Var,PVal),PriorState) -> PVal=Val).
743
744 get_variables(const_and_vars(_,VarsState),S) :- !, S=VarsState.
745 get_variables(S,S).
746
747 :- dynamic non_det_constants/2.
748
749 % compute which constants are non-deterministically assigned and which ones not
750 % TODO: maybe move to state space and invalidate info in case execute operation by predicate used
751 get_non_det_constant(Template,Result) :- non_det_constants(A,B),!, (A,B)=(Template,Result).
752 get_non_det_constant(Template,Result) :-
753 ? state_space:transition(root,_,DstID),
754 state_space:visited_expression(DstID,concrete_constants(State)), %print(get_non_det_constant(DstID)),nl,
755 !,
756 findall(D,(state_space:transition(root,_,D),D \= DstID),OtherDst),
757 compute_non_det_constants2(OtherDst,State),
758 non_det_constants(Template,Result).
759 get_non_det_constant(A,A).
760
761 compute_non_det_constants2([],State) :- adapt_state(State,Template,Result),
762 (Result = [] -> assertz(non_det_constants(A,A)) % in case all variables are deterministic: just show them
763 ; assertz(non_det_constants(Template,Result))).
764 compute_non_det_constants2([Dst|T],State) :-
765 state_space:visited_expression(Dst,concrete_constants(State2)),
766 lub_state(State,State2,NewState),
767 compute_non_det_constants2(T,NewState).
768
769 lub_state([],[],[]).
770 lub_state([bind(V,H1)|T1],[bind(V,H2)|T2],[bind(V,H3)|T3]) :-
771 (H1==H2 -> H3=H1 ; H3='$NONDET'), lub_state(T1,T2,T3).
772
773 adapt_state([],[],[]).
774 adapt_state([bind(ID,Val)|T],[bind(ID,X)|TX],[bind(ID,X)|TY]) :- Val='$NONDET',!,
775 adapt_state(T,TX,TY).
776 adapt_state([bind(ID,_)|T],[bind(ID,_)|TX],TY) :- % Value is deterministic: do not copy
777 adapt_state(T,TX,TY).
778
779
780
781 % ------------------------------------
782
783 translate_event_with_limit(Event,Limit,Out) :-
784 translate_event2(Event,Atoms,[]),!,
785 ajoin_with_limit(Atoms,Limit,Out).
786 %,print(done),debug:print_debug_stats,nl.% , print(Out),nl.
787 translate_event_with_limit(Event,_,Out) :- add_error(translate_event_with_limit,'Could not translate event: ', Event),
788 Out = '???'.
789
790 translate_event(Event,Out) :- %print(translate),print_debug_stats,nl,
791 translate_event2(Event,Atoms,[]),!,
792 ajoin(Atoms,Out).
793 %,print(done),debug:print_debug_stats,nl.% , print(Out),nl.
794 translate_event(Event,Out) :-
795 add_error(translate_event,'Could not translate event: ', Event),
796 Out = '???'.
797 /* BEGIN CSP */
798 translate_event2(start_cspm(Process),['start_cspm('|S],T) :- process_algebra_mode,!,pp_csp_value(Process,S,[')'|T]).
799 %% translate_event2(i(_Span),['i'|T],T) :- process_algebra_mode,!. /* CSP */ %% deprecated
800 translate_event2(tick(_Span),['tick'|T],T) :- process_algebra_mode,!. /* CSP */
801 translate_event2(tau(hide(Action)),['tau(hide('|S],T) :- process_algebra_mode,nonvar(Action), !,
802 translate_event2(Action,S,['))'|T]). /* CSP */
803 translate_event2(tau(link(Action1,Action2)),['tau(link('|S],T) :- /* CSP */
804 nonvar(Action1), nonvar(Action2), process_algebra_mode, !,
805 translate_event2(Action1,S,['<->'|S1]),
806 translate_event2(Action2,S1,['))'|T]).
807 translate_event2(tau(Info),['tau(',Fun,')'|T],T) :-
808 nonvar(Info), process_algebra_mode,!, /* CSP */
809 functor(Info,Fun,_). %(translate_event(Info,Fun) -> true ; functor(Info,Fun,_)),
810 translate_event2(io(V,Ch,_Span),S,T) :- process_algebra_mode,!, /* CSP */
811 (specfile:csp_with_bz_mode ->
812 S=['CSP:'|S1],
813 translate_event2(io(V,Ch),S1,T)
814 ;
815 translate_event2(io(V,Ch),S,T)
816 ).
817 translate_event2(io(X,Channel),S,T) :- process_algebra_mode,!, /* CSP */
818 (X=[] -> translate_event2(Channel,S,T)
819 ; (translate_event2(Channel,S,S1),
820 translate_channel_values(X,S1,T))
821 ).
822 /* END CSP */
823 translate_event2('$JUMP'(Name),[A|T],T) :- write_to_codes(Name,Codes),
824 atom_codes_with_limit(A,Codes).
825 translate_event2('-->'(Operation,ResultValues),S,T) :- nonvar(ResultValues),
826 ResultValues=[_|_],!,
827 translate_event2(Operation,S,['-->',ValuesStr|T]),
828 translate_bvalues(ResultValues,ValuesStr).
829 translate_event2(Op,S,T) :-
830 nonvar(Op), Op =.. [OpName|Args],
831 translate_b_operation_call(OpName,Args,S,T),!.
832 translate_event2(Op,[A|T],T) :-
833 %['<< ',A,' >>'|T],T) :- % the << >> pose problems when checking against FDR
834 write_to_codes(Op,Codes),
835 atom_codes_with_limit(A,Codes).
836
837 % translate a B operation call to list of atoms in dcg style
838 translate_b_operation_call(OpName,Args,[TOpName|S],T) :-
839 translate_operation_name(OpName,TOpName),
840 ( Args=[] -> S=T
841 ;
842 S=['(',ValuesStr,')'|T],
843 ( get_preference(show_eventb_any_arguments,false), % otherwise we have additional ANY parameters !
844 \+ is_init(OpName), % order of variables does not always correspond to Variable order used by b_get_machine_operation_parameter_types ! TO DO - Fix this in b_initialise_machine2 (see Interlocking.mch CSP||B model)
845 ? specfile:b_mode,
846 b_is_operation_name(OpName),
847 ? b_get_machine_operation_parameter_types(OpName,ParTypes),
848 ParTypes \= []
849 -> translate_bvalues_with_types(Args,ParTypes,ValuesStr)
850 %; is_init(OpName) -> b_get_machine_operation_typed_parameters(OpName,TypedParas),
851 ; translate_bvalues(Args,ValuesStr))
852 ).
853
854 % -----------------
855
856 % translate call stacks as stored in wait flag info fields
857 % (managed by push_wait_flag_call_stack_info)
858
859 translate_call_stack(Stack,Msg) :-
860 Opts = [detailed],
861 split_calls(Stack,DStack),
862 get_cs_avl_limit(ALimit),
863 temporary_set_preference(expand_avl_upto,ALimit,CHNG),
864 set_unicode_mode,
865 call_cleanup(render_call_stack(DStack,1,Opts,A,[]),
866 (unset_unicode_mode,
867 reset_temporary_preference(expand_avl_upto,CHNG))),
868 ajoin(['call stack: '|A],Msg).
869 render_call_stack([],_,_) --> [].
870 render_call_stack([H],Nr,Opts) --> !,
871 render_nr(Nr,H,_,Opts), render_call(H,Opts).
872 render_call_stack([H|T],Nr,Opts) -->
873 render_nr(Nr,H,Nr1,Opts),
874 render_call(H,Opts),
875 render_seperator(Opts),
876 render_call_stack(T,Nr1,Opts).
877
878 % render nr of call in call stack
879 render_nr(Pos,H,Pos1,Opts) --> {member(detailed,Opts)},!, ['\n '], render_pos_nr(Pos,H,Pos1).
880 render_nr(Pos,_,Pos,_) --> [].
881
882 render_pos_nr(Pos,definition_call(_,_),Pos) --> !,
883 [' ']. % definition calls are virtual and can appear multiple times for different entries in the call stack
884 % see e.g., public_examples/B/FeatureChecks/DEFINITIONS/DefCallStackDisplay2.mch
885 render_pos_nr(Pos,_,Pos1) --> [Pos] , {Pos1 is Pos+1}, [': '].
886
887 render_seperator(Opts) --> {member(detailed,Opts)},!. % we put newlines in render_nr
888 render_seperator(_Opts) -->
889 {call_stack_arrow_atom_symbol(Symbol)}, [Symbol].
890
891 render_call(definition_call(Name,Pos),Opts) --> !,
892 ['within DEFINITION call '],[Name],
893 render_span(Pos,Opts).
894 render_call(operation_call(Op,Paras,Pos),Opts) --> !,
895 translate_b_operation_call(Op,Paras), % TODO: limit size?
896 render_span(Pos,Opts).
897 render_call(using_state(Name,State),_Opts) --> !,
898 [Name], [' with state: '],
899 {get_cs_limit(Limit),translate_bstate_limited(State,Limit,Str)},
900 [Str].
901 render_call(after_event(OpTerm),_Opts) --> !,
902 ['after event: '],
903 {get_cs_limit(Limit),translate_event_with_limit(OpTerm,Limit,Str)},
904 [Str].
905 render_call(function_call(Fun,Paras,Pos),Opts) --> !,
906 render_function_call(Fun,Paras),
907 render_span(Pos,Opts).
908 render_call(b_operator_call(OP,Paras,Pos),Opts) --> !,
909 render_operator_arg(b_operator(OP,Paras)),
910 render_span(Pos,Opts).
911 render_call(id_equality_evaluation(ID,Kind,Pos),Opts) --> !,
912 ['equality for '],[Kind],[' '],[ID],
913 render_span(Pos,Opts).
914 render_call(b_operator_arg_evaluation(OP,PosNr,Args,Pos),Opts) --> !,
915 ['arg '],[PosNr],[' of '],
916 render_operator_arg(b_operator(OP,Args)),
917 render_span(Pos,Opts).
918 render_call(external_call(Name,Paras,Pos),Opts) --> !,
919 ['external call '], [Name],['('],
920 {get_cs_limit(Limit),translate_bvalues_with_limit(Paras,Limit,PS)},[PS], [')'],
921 render_span(Pos,Opts).
922 render_call(prob_command_context(Name,Pos),Opts) --> !,
923 ['checking '], render_prob_command(Name),
924 render_span(Pos,Opts).
925 render_call(quantifier_call(comprehension_set,ParaNames,ParaValues,Pos),Opts) --> % special case for lambda
926 {nth1(LPos,ParaNames,LambdaRes,RestParaNames),
927 is_lambda_result_name(LambdaRes,_),
928 nth1(LPos,ParaValues,LambdaVal,RestParaValues)},!, % we have found '_lambda_res_' amongst paras
929 render_quantifier(lambda), ['('],
930 render_paras(RestParaNames,RestParaValues),
931 ['|'], render_para_val(LambdaVal),
932 [')'],
933 render_span(Pos,Opts).
934 render_call(quantifier_call(Kind,ParaNames,ParaValues,Pos),Opts) --> !,
935 render_quantifier(Kind), ['('],
936 render_paras(ParaNames,ParaValues), [')'],
937 render_span(Pos,Opts).
938 render_call(top_level_call(SpanPred),Opts) -->
939 render_call(SpanPred,Opts).
940 render_call(b_expr_call(Context,Expr),Opts) --> !,
941 [Context],[': '],
942 render_b_expr(Expr),
943 render_span(Expr,Opts).
944 render_call(span_predicate(Pred,LS,S),Opts) --> % Pred can also be an expression like function/2
945 % infos could contain was(extended_expr(Op)); special case for: assertion_expression
946 {Pred=b(_,_,Pos),
947 b_compiler:b_compile(Pred,[],LS,S,CPred,no_wf_available) % inline actual parameters
948 },
949 !,
950 render_b_expr(CPred),
951 render_function_name(Pred), % try show function name from uncompiled Expr
952 render_span(Pos,Opts).
953 render_call(Other,_) --> [Other].
954
955 %render_operator(OP) -->
956 % {(unicode_translation(OP,Unicode) -> FOP=Unicode ; FOP=OP)}, [FOP].
957
958 % render b operator arguments/calls:
959 render_operator_arg(Var) --> {var(Var)},!,['_VARIABLE_']. % should not happen
960 render_operator_arg(b_operator(OP,[Arg1,Arg2])) -->
961 {binary_infix_in_mode(OP,Symbol,_,_)},!,
962 {(unicode_translation(OP,Unicode) -> FOP=Unicode ; FOP=Symbol)}, %TODO: add parentheses if necessary
963 render_operator_arg(Arg1),
964 [' '],[FOP], [' '],
965 render_operator_arg(Arg2).
966 render_operator_arg(b_operator(OP,Args)) --> !,
967 {(unicode_translation(OP,Unicode) -> FOP=Unicode ; function_like(OP,FOP) -> true ; FOP=OP)},
968 [FOP], ['('],
969 render_operator_args(Args),
970 [')'].
971 render_operator_arg(bind(Name,Value)) --> !,
972 [Name], ['='],
973 render_operator_arg(Value).
974 render_operator_arg(identifier(ID)) --> !, [ID].
975 render_operator_arg(Val) --> render_para_val(Val).
976
977 render_operator_args([]) --> !, [].
978 render_operator_args([H]) --> !, render_operator_arg(H).
979 render_operator_args([H|T]) --> !, render_operator_arg(H), [','], render_operator_args(T).
980 render_operator_args(A) --> {add_internal_error('Not a list: ',A)}, ['???'].
981
982 render_prob_command(check_pred_command(PredKind,Arg)) --> !, ['predicate '], render_pred_nr(Arg), ['of '],[PredKind].
983 render_prob_command(eval_expr_command(Kind,Arg)) --> !, ['expression '], render_pred_nr(Arg), ['of '],[Kind].
984 render_prob_command(trace_replay(OpName,FromId)) --> !, ['Trace replay predicate for '],[OpName], [' from '],[FromId].
985 render_prob_command(Cmd) --> [Cmd].
986
987 render_pred_nr(0) --> !. % 0 is special value to indicate we have no number/id within outer kind
988 render_pred_nr(Nr) --> {number(Nr)},!,['# '],[Nr],[' '].
989 render_pred_nr('') --> !.
990 render_pred_nr(AtomId) --> ['for '], [AtomId],[' '].
991
992 render_function_name(b(function(Fun,_),_,_)) --> {try_get_identifier(Fun,FID)},!,
993 % TODO: other means of extracting name; maybe we should render anything that is not a value?
994 ['\n (Function applied: '], [FID], [')'].
995 render_function_name(b(_,_,Infos)) --> {member(was(extended_expr(OpID)),Infos)},!,
996 ['\n (Theory operator applied: '], [OpID], [')'].
997 render_function_name(_) --> [].
998
999 try_get_identifier(Expr,Id) :- (get_texpr_id(Expr,Id) -> true ; get_was_identifier(Expr,Id)).
1000
1001 render_span(Span,Opts) --> {member(detailed,Opts),translate_span(Span,Atom), Atom \= ''},!,
1002 ['\n '], [Atom],
1003 ({member(additional_descr,Opts),translate_additional_description(Span,Descr)}
1004 -> [' within ',Descr]
1005 ; []).
1006 render_span(_,_) --> [].
1007
1008 render_function_call(Fun,Paras) -->
1009 {(atomic(Fun) -> FS=Fun ; translate_bexpr_for_call_stack(Fun,FS))}, % memoization will only register atomic name
1010 [FS],['('], render_para_val(Paras), [')'].
1011
1012 render_b_expr(b(function(Fun,Paras),_,_)) --> !, % ensure we print both function and paras at least partially
1013 {translate_bexpr_for_call_stack(Fun,FS)}, [FS],['('],
1014 {translate_bexpr_for_call_stack(Paras,PS)},[PS], [')'].
1015 render_b_expr(b(assertion_expression(Pred,Msg,b(value(_),string,_)),_,_)) --> !,
1016 % Body is not source of error; probably better to use special call stack entry for assertion_expression
1017 ['ASSERT '],[Msg],['\n '],
1018 {translate_bexpr_for_call_stack(Pred,PS)}, [PS].
1019 render_b_expr(CPred) --> {translate_bexpr_for_call_stack(CPred,PS)}, [PS].
1020
1021 translate_bexpr_for_call_stack(Expr,TS) :-
1022 get_cs_limit(Limit),
1023 translate_bexpression_with_limit(Expr,Limit,TS).
1024
1025 get_cs_limit(2000) :- !.
1026 get_cs_limit(Limit) :- debug_mode(on),!, debug_level(Level), % 19 regular, 5 very verbose
1027 Limit is 1000 - Level*20.
1028 get_cs_limit(200) :- get_preference(provide_trace_information,true),!.
1029 get_cs_limit(100).
1030
1031 get_cs_avl_limit(40) :- debug_mode(on),!.
1032 get_cs_avl_limit(6) :- get_preference(provide_trace_information,true),!.
1033 get_cs_avl_limit(4).
1034
1035 get_call_stack_span(operation_call(_,_,Pos),Pos).
1036 %get_call_stack_span(after_event(_),unknown).
1037 get_call_stack_span(function_call(_,_,Pos),Pos).
1038 get_call_stack_span(id_equality_evaluation(_ID,_Kind,Pos),Pos).
1039 get_call_stack_span(quantifier_call(_,_,_,Pos),Pos).
1040 get_call_stack_span(definition_call(_,Pos),Pos).
1041 get_call_stack_span(external_call(_,_,Pos),Pos).
1042 get_call_stack_span(prob_command_context(_,Pos),Pos).
1043 get_call_stack_span(top_level_call(Pos),Pos).
1044 get_call_stack_span(b_operator_call(_,_,Pos),Pos).
1045 get_call_stack_span(b_operator_arg_evaluation(_,_,_,Pos),Pos).
1046 get_call_stack_span(b_expr_call(_,Expr),Expr).
1047 get_call_stack_span(span_predicate(A,B,C),span_predicate(A,B,C)).
1048
1049 nop_call(top_level_call(X)) :- \+ is_top_level_function_call(X).
1050 % just there to insert virtual DEFINITION calls at top-level of call-stack
1051 is_top_level_function_call(span_predicate(b(Expr,_,_),_,_)) :-
1052 Expr = function(_,_),
1053 get_preference(provide_trace_information,false).
1054 % otherwise we push function_calls onto the stack; see opt_push_wait_flag_call_stack_info
1055
1056 % expand the call stack by creating entries for the definition calls
1057 split_calls([],[]).
1058 split_calls([Call|T],NewCalls) :- nop_call(Call),!, %print(nop(Call)),nl,
1059 split_calls(T,NewCalls).
1060 split_calls([Call|T],NewCalls) :-
1061 get_call_stack_span(Call,Span),!,
1062 NewCalls = [Call|New2],
1063 extract_def_calls(Span,New2,ST),
1064 split_calls(T,ST).
1065 split_calls([Call|T],[Call|ST]) :-
1066 split_calls(T,ST).
1067
1068 extract_def_calls(Span) -->
1069 {extract_pos_context(Span,MainPos,Context,CtxtPos)},
1070 {Context = definition_call(Name)},
1071 !,
1072 extract_def_calls(MainPos),
1073 [definition_call(Name,CtxtPos)],
1074 extract_def_calls(CtxtPos). % do we need this??
1075 extract_def_calls(_) --> [].
1076
1077 % a shorter version of extract_additional_description only accepting definition_calls
1078 translate_additional_description(Span,Desc) :-
1079 extract_pos_context(Span,MainPos,Context,CtxtPos),
1080 translate_span(CtxtPos,CtxtAtom),
1081 extract_def_context_msg(Context,OuterCMsg),
1082 (translate_additional_description(MainPos,InnerCMsg)
1083 -> ajoin([InnerCMsg,' within ',OuterCMsg, ' ', CtxtAtom],Desc)
1084 ; ajoin([OuterCMsg, ' ', CtxtAtom],Desc)
1085 ).
1086
1087 % try and get an immediate definition call context for a position
1088 get_definition_context_from_span(Span,DefCtxtMsg) :-
1089 extract_pos_context(Span,_MainPos,Context,_CtxtPos),
1090 extract_def_context_msg(Context,DefCtxtMsg).
1091
1092 extract_def_context_msg(definition_call(Name),Msg) :- !, % static Definition macro expansion call stack
1093 ajoin(['DEFINITION call of ',Name],Msg).
1094
1095 render_paras([],[]) --> !, [].
1096 render_paras([],_Vals) --> ['...?...']. % should not happen
1097 render_paras([Name],[Val]) --> !, render_para_name(Name), ['='], render_para_val(Val).
1098 render_paras([Name|TN],[Val|TV]) --> !,
1099 render_para_name(Name), ['='], render_para_val(Val), [','],
1100 render_paras(TN,TV).
1101 render_paras([N|Names],[]) --> !, render_para_name(N), render_paras(Names,[]). % value list can be empty
1102
1103 render_para_val(Val) --> {get_cs_limit(Limit),translate_bvalue_with_limit(Val,Limit,VS)}, [VS].
1104
1105 % accept typed and atomic ids
1106 render_para_name(b(identifier(ID),_,_)) --> !, {translated_identifier(ID,TID)},[TID].
1107 render_para_name(ID) --> {translated_identifier(ID,TID)},[TID].
1108
1109 render_quantifier(lambda) --> !, {unicode_translation(lambda,Symbol)},[Symbol]. % ['{|}'].
1110 render_quantifier(comprehension_set) --> !, ['{|}'].
1111 render_quantifier(comprehension_set(NegationContext)) --> !,
1112 render_negation_context(NegationContext), [' {|}'].
1113 render_quantifier(exists) --> !, {unicode_translation(exists,Symbol)},[Symbol].
1114 render_quantifier(let_quantifier) --> !, ['LET'].
1115 render_quantifier(optimize) --> !, ['#optimize'].
1116 render_quantifier(forall) --> !, {unicode_translation(forall,Symbol)},[Symbol].
1117 render_quantifier(not(Q)) --> !, {unicode_translation(negation,Symbol)}, % not(exists)
1118 [Symbol, '('], render_quantifier(Q), [')'].
1119 render_quantifier(Q) --> !, [Q].
1120
1121 render_negation_context(positive) --> !, ['one solution'].
1122 render_negation_context(negative) --> !, ['no solution'].
1123 render_negation_context(all_solutions) --> !,['all solutions'].
1124 render_negation_context(C) --> [C].
1125
1126 call_stack_arrow_atom_symbol(' \x2192\ '). % see total function
1127 %call_stack_arrow_atom_symbol('\x27FF\ '). % long rightwards squiggle arrow
1128
1129 % -----------------
1130
1131
1132 is_init('$initialise_machine').
1133 is_init('$setup_constants').
1134
1135 translate_bvalues_with_types(Values,Types,Output) :-
1136 %set_up_limit_reached(Codes,1000,LimitReached),
1137 pp_value_l_with_types(Values,',',Types,_LimitReached,Codes,[]),!,
1138 atom_codes_with_limit(Output,Codes).
1139 translate_bvalues_with_types(Values,T,Output) :-
1140 add_internal_error('Call failed: ',translate_bvalues_with_types(Values,T,Output)),
1141 translate_bvalues(Values,Output).
1142
1143 pp_value_l_with_types([],_Sep,[],_) --> !.
1144 pp_value_l_with_types([Expr|Rest],Sep,[TE|TT],LimitReached) -->
1145 ( {nonvar(Rest),Rest=[]} ->
1146 pp_value_with_type(Expr,TE,LimitReached)
1147 ;
1148 pp_value_with_type(Expr,TE,LimitReached),ppatom(Sep),
1149 pp_value_l_with_types(Rest,Sep,TT,LimitReached)).
1150
1151
1152 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1153
1154 % pretty-print properties
1155 translate_properties_with_limit([],[]).
1156 translate_properties_with_limit([P|Prest],[Out|Orest]) :-
1157 translate_property_with_limit(P,320,Out), % reduced limit as we now have evaluation view + possibility to inspect all of value
1158 translate_properties_with_limit(Prest,Orest).
1159
1160 translate_property_with_limit(Prop,Limit,Output) :-
1161 (pp_property(Prop,Limit,Output) -> true ; (add_error(translate_property,'Could not translate property: ',Prop),Output='???')).
1162 pp_property(Prop,Limit,Output) :-
1163 pp_property_without_plugin(Prop,Limit,Output).
1164 pp_property_without_plugin(=(Key,Value),_,A) :-
1165 !,ajoin([Key,' = ',Value],A).
1166 pp_property_without_plugin(':'(Key,Value),_,A) :-
1167 !,ajoin([Key,' : ',Value],A).
1168 pp_property_without_plugin(info(I),_,I) :- !.
1169 pp_property_without_plugin(Prop,Limit,A) :-
1170 write_to_codes(Prop,Codes),
1171 atom_codes_with_limit(A,Limit,Codes).
1172
1173
1174 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1175 :- use_module(tools_meta,[translate_term_into_atom_with_max_depth/3]).
1176
1177 % pretty-print errors belonging to a certain state
1178 translate_error_term(Term,S) :- translate_error_term(Term,unknown,S).
1179 translate_error_term(Var,_,S) :- var(Var),!,
1180 translate_term_into_atom_with_max_depth(Var,5,S).
1181 translate_error_term('@fun'(X,F),Span,S) :-
1182 translate_bvalue(X,TX),
1183 (get_function_from_span(Span,Fun,LocState,State),
1184 translate_bexpression_with_limit(Fun,200,TSF)
1185 -> % we managed to extract the function from the span_predicate
1186 (is_compiled_value(Fun)
1187 -> (get_was_identifier(Fun,WasFunId) -> Rest = [', function: ',WasFunId | Rest1]
1188 ; Rest = Rest1
1189 ),
1190 TVal=TSF % use as value
1191 ; Rest = [', function: ',TSF | Rest1],
1192 % try and extract value from span_predicate (often F=[] after traversing avl)
1193 (get_texpr_id(Fun,FID),
1194 (member(bind(FID,FVal),LocState) ; member(bind(FID,FVal),State))
1195 -> translate_bvalue(FVal,TVal)
1196 ; translate_bvalue(F,TVal)
1197 )
1198 )
1199 ; Rest=[], translate_bvalue(F,TVal)
1200 ),!,
1201 % translate_term_into_atom_with_max_depth('@fun'(TX,TVal),5,S).
1202 (get_error_span_for_value(F,NewSpanTxt) % triggers in test 953
1203 -> Rest1 = [' defined at ',NewSpanTxt]
1204 ; Rest1 = []
1205 ),
1206 ajoin(['Function argument: ',TX, ', function value: ',TVal | Rest],S).
1207 translate_error_term('@rel'(Arg,Res1,Res2),_,S) :-
1208 translate_bvalue(Arg,TA), translate_bvalue(Res1,R1),
1209 translate_bvalue(Res2,R2),!,
1210 ajoin(['Function argument: ',TA, ', two possible values: ',R1,', ',R2],S).
1211 translate_error_term([operation(Name,Env)],_,S) :-
1212 translate_any_state(Env,TEnv), !,
1213 translate_term_into_atom_with_max_depth(operation(Name,TEnv),10,S).
1214 translate_error_term(error(E1,E2),_,S) :- !, translate_prolog_error(E1,E2,S).
1215 translate_error_term(b(B,T,I),_,S) :-
1216 translate_subst_or_bexpr_with_limit(b(B,T,I),1000,do_not_report_errors,S),!. % do not report errors, otherwise we end in an infinite loop of adding errors while adding errors
1217 translate_error_term([H|T],_,S) :- nonvar(H), H=b(_,_,_), % typically a list of typed ids
1218 E=b(sequence_extension([H|T]),any,[]),
1219 translate_subst_or_bexpr_with_limit(E,1000,do_not_report_errors,S),!.
1220 translate_error_term([H|T],_,S) :- nonvar(H), H=bind(_,_), % a store
1221 translate_bstate_limited([H|T],1000,S),!.
1222 translate_error_term(Term,_,S) :-
1223 is_bvalue(Term),
1224 translate_bvalue_with_limit(Term,1000,S),!.
1225 translate_error_term(T,_,S) :-
1226 (debug_mode(on) -> Depth = 20 ; Depth = 5),
1227 translate_term_into_atom_with_max_depth(T,Depth,S).
1228
1229 get_function_from_span(Var,Fun,_,_) :- var(Var), !,
1230 add_internal_error('Variable span:',get_function_from_span(Var,Fun)),fail.
1231 get_function_from_span(pos_context(Span,_,_),Fun,LS,S) :- get_function_from_span(Span,Fun,LS,S).
1232 get_function_from_span(span_predicate(b(function(Function,_Arg),_T,_I),LocalState,State),Function,LocalState,State).
1233
1234 is_compiled_value(b(value(_),_,_)).
1235
1236 get_was_identifier(b(_,_,Info),Id) :- member(was_identifier(Id),Info). % added e.g. by b_compiler
1237
1238 % TODO: complete this
1239 % for recognising B values as error terms and automatically translating them
1240 is_bvalue(V) :- var(V),!,fail.
1241 is_bvalue([]).
1242 is_bvalue(closure(_,_,_)).
1243 is_bvalue(fd(_,_)).
1244 is_bvalue(freetype(_)).
1245 is_bvalue(freeval(_,_,_)).
1246 is_bvalue(avl_set(_)).
1247 is_bvalue(int(_)).
1248 is_bvalue(global_set(_)).
1249 is_bvalue(pred_true).
1250 is_bvalue(pred_false).
1251 is_bvalue(string(_)).
1252 is_bvalue(term(_)). % typically term(floating(_))
1253 is_bvalue(rec(Fields)) :- nonvar(Fields), Fields=[F1|_], nonvar(F1),
1254 F1=field(_,V1), is_bvalue(V1).
1255 is_bvalue((A,B)) :-
1256 (nonvar(A) -> is_bvalue(A) ; true),
1257 (nonvar(B) -> is_bvalue(B) ; true).
1258
1259 % try and get error location for span:
1260 get_error_span_for_value(Var,_) :- var(Var),!,fail.
1261 get_error_span_for_value(closure(_,_,Body),Span) :- translate_span_with_filename(Body,Span), Span \= ''.
1262
1263
1264 % translate something that was caught with catch/3
1265 translate_prolog_exception(user_interrupt_signal,R) :- !, R='User-Interrupt (CTRL-C)'.
1266 translate_prolog_exception(enumeration_warning(_,_,_,_,_),R) :- !, R='Enumeration Warning'.
1267 translate_prolog_exception(error(E1,E2),S) :- !, translate_prolog_error(E1,E2,S).
1268 translate_prolog_exception(E1,S) :- translate_term_into_atom_with_max_depth(E1,8,S).
1269
1270 % translate a Prolog error(E1,E2) exception
1271 translate_prolog_error(existence_error(procedure,Pred),_,S) :- !,
1272 translate_term_into_atom_with_max_depth('Unknown Prolog predicate:'(Pred),8,S).
1273 translate_prolog_error(existence_error(source_sink,File),_,S) :- !,
1274 translate_term_into_atom_with_max_depth('File does not exist:'(File),8,S).
1275 translate_prolog_error(permission_error(Action,source_sink,File),_,S) :- !, % Action = open, ...
1276 ajoin(['Permission denied to ',Action,' the file: ',File],S).
1277 translate_prolog_error(permission_error(Action,past_end_of_stream,File),_,S) :- !, % Action = open, ...
1278 ajoin(['Permission denied to ',Action,' past end of file: ',File],S).
1279 translate_prolog_error(system_error,system_error('SPIO_E_NET_CONNRESET'),S) :- !,
1280 S = 'System error: connection to process lost (SPIO_E_NET_CONNRESET)'.
1281 translate_prolog_error(system_error,system_error('SPIO_E_ENCODING_UNMAPPABLE'),S) :- !,
1282 S = 'System error: illegal character or encoding encountered (SPIO_E_ENCODING_UNMAPPABLE)'.
1283 translate_prolog_error(system_error,system_error('SPIO_E_NET_HOST_NOT_FOUND'),S) :- !,
1284 S = 'System error: could not find host (SPIO_E_NET_HOST_NOT_FOUND)'.
1285 translate_prolog_error(system_error,system_error('SPIO_E_CHARSET_NOT_FOUND'),S) :- !,
1286 S = 'System error: could not find character set encoding'.
1287 translate_prolog_error(system_error,system_error('SPIO_E_OS_ERROR'),S) :- !,
1288 S = 'System error due to some OS/system call (SPIO_E_OS_ERROR)'.
1289 translate_prolog_error(system_error,system_error('SPIO_E_END_OF_FILE'),S) :- !,
1290 S = 'System error: end of file (SPIO_E_END_OF_FILE)'.
1291 translate_prolog_error(system_error,system_error('SPIO_E_TOO_MANY_OPEN_FILES'),S) :- !,
1292 S = 'System error: too many open files (SPIO_E_TOO_MANY_OPEN_FILES)'.
1293 translate_prolog_error(system_error,system_error(dlopen(Msg)),S) :- !,
1294 translate_term_into_atom_with_max_depth(Msg,4,MS),
1295 ajoin(['System error: could not load dynamic library (you may have to right-click on the library and open it in the macOS Finder): ', MS],S).
1296 translate_prolog_error(system_error,system_error(Err),S) :- !,
1297 % or Err is an atom dlopen( mach-o file, but is an incompatible architecture ...)
1298 % E.g., SPIO_E_NOT_SUPPORTED when doing open('/usr',r,S)
1299 translate_term_into_atom_with_max_depth('System error:'(Err),8,S).
1300 translate_prolog_error(existence_error(procedure,Module:Pred/Arity),_,S) :- !,
1301 ajoin(['Prolog predicate does not exist: ',Module,':', Pred, '/',Arity],S).
1302 translate_prolog_error(instantiation_error,instantiation_error(Call,_ArgNo),S) :- !,
1303 translate_term_into_atom_with_max_depth('Prolog instantiation error:'(Call),8,S).
1304 translate_prolog_error(uninstantiation_error(_),uninstantiation_error(Call,_ArgNo,_Culprit),S) :- !,
1305 translate_term_into_atom_with_max_depth('Prolog uninstantiation error:'(Call),8,S).
1306 translate_prolog_error(evaluation_error(zero_divisor),evaluation_error(Call,_,_,_),S) :- !,
1307 translate_term_into_atom_with_max_depth('Division by zero error:'(Call),8,S).
1308 translate_prolog_error(evaluation_error(float_overflow),evaluation_error(Call,_,_,_),S) :- !,
1309 translate_term_into_atom_with_max_depth('Float overflow:'(Call),8,S).
1310 translate_prolog_error(representation_error(Err),representation_error(Call,_,_),S) :-
1311 memberchk(Err, ['CLPFD integer overflow','max_clpfd_integer','min_clpfd_integer']),!,
1312 translate_term_into_atom_with_max_depth('Prolog CLP(FD) overflow:'(Call),8,S).
1313 % TODO: domain_error(list_to_fdset(FDLIST,_989819),_,_,_L)
1314 translate_prolog_error(syntax_error(Err),_,S) :- !,
1315 translate_term_into_atom_with_max_depth('Prolog syntax error:'(Err),8,S).
1316 translate_prolog_error(_,resource_error(open(File,Mode,_),Kind),S) :- !, % Kind e.g. file_handle
1317 ajoin(['Resource error (',Kind,
1318 '), could not open file ',File,' in mode ',Mode],S).
1319 :- if(predicate_property(message_to_string(_, _), _)).
1320 translate_prolog_error(E1,E2,S) :-
1321 % SWI-Prolog way to translate an arbitrary message term (such as an exception) to a string,
1322 % the same way that the built-in message handling system would print it.
1323 message_to_string(error(E1,E2), String),
1324 !,
1325 atom_string(S, String).
1326 :- endif.
1327 translate_prolog_error(E1,_,S) :- translate_term_into_atom_with_max_depth(E1,8,S).
1328 % we also have permission_error, context_error, domain_error
1329
1330 translate_state_errors([],[]).
1331 translate_state_errors([E|ERest],[Out|ORest]) :-
1332 ( E = eventerror(Event,EError,_) ->
1333 translate_event_error(EError,Msg),
1334 ajoin([Event,': ',Msg],Out)
1335 ; translate_state_error(E,Out) -> true
1336 ; functor(E,Out,_) ),
1337 translate_state_errors(ERest,ORest).
1338
1339 translate_error_context(E,TE) :- translate_error_context2(E,Codes,[]),
1340 atom_codes_with_limit(TE,Codes).
1341 translate_error_context2(span_context(Span,Context)) --> !,
1342 translate_error_context2(Context),
1343 translate_span(Span,only_subsidiary).
1344 translate_error_context2([H]) --> !,translate_error_context2(H).
1345 translate_error_context2(checking_invariant) --> !,
1346 {get_specification_description_codes(invariant,A)}, A. %"INVARIANT".
1347 translate_error_context2(checking_assertions) --> !,
1348 {get_specification_description_codes(assertions,A)}, A. %"ASSERTIONS".
1349 translate_error_context2(checking_negation_of_invariant(_State)) --> !,
1350 "not(INVARIANT)".
1351 translate_error_context2(operation(OpName,_State)) --> !,
1352 {translate_operation_name(OpName,TOp)},
1353 ppterm(TOp).
1354 translate_error_context2(checking_context(Check,Name)) --> !,
1355 ppterm(Check),ppterm(Name).
1356 translate_error_context2(loading_context(_Name)) --> !.
1357 translate_error_context2(visb_error_context(Class,SvgId,OpNameOrAttr,Span)) --> !,
1358 "VisB ", ppterm(Class), " for SVG ID ",
1359 ppterm(SvgId), " and attribute/event ",
1360 {translate_operation_name(OpNameOrAttr,TOp)},
1361 ppterm(TOp),
1362 translate_span(Span,only_subsidiary).
1363 translate_error_context2(X) --> "???:", ppterm(X).
1364
1365 print_span(Span) :- translate_span(Span,Atom), !, print(Atom).
1366 print_span(S) :- print(span(S)).
1367
1368 print_span_nl(Span) :- translate_span(Span,Atom), !,(Atom='' -> true ; print(Atom)),nl.
1369 print_span_nl(S) :- print(span(S)),nl.
1370
1371
1372 translate_span(Span,Atom) :- translate_span(Span,only_subsidiary,Codes,[]),
1373 atom_codes_with_limit(Atom,Codes).
1374 translate_span_with_filename(Span,Atom) :-
1375 translate_span(Span,always_print_filename,Codes,[]),
1376 atom_codes_with_limit(Atom,Codes).
1377
1378 translate_span(Span,_) --> {var(Span)},!, {add_internal_error('Variable span:',translate_span(Span,_))}, "_".
1379 translate_span(Span,PrintFileNames) --> {extract_line_col(Span,Srow,Scol,_Erow,_Ecol)},!,
1380 "(Line:",ppterm(Srow)," Col:",ppterm(Scol),
1381 %"-",ppterm(Erow),":",ppterm(Ecol),
1382 translate_span_file_opt(Span,PrintFileNames),
1383 % TO DO: print short version of extract_additional_description ?
1384 ")".
1385 translate_span(Span,_PrintFileNames) --> {extract_symbolic_label(Span,Label)},!, "(label @",ppterm(Label),")".
1386 translate_span(Span,PrintFileNames) -->
1387 % for Event-B, e.g., line-col fails but we can get a section/file name
1388 "(File:",translate_span_file(Span,PrintFileNames),!,")".
1389 translate_span(_,_PrintFileNames) --> "".
1390
1391 translate_span_file(Span,always_print_filename) -->
1392 {extract_tail_file_name(Span,Filename)},!,
1393 %{bmachine:b_get_main_filenumber(MainFN), Nr \= MainFN},!,
1394 " File:", ppterm(Filename).
1395 translate_span_file(Span,_) -->
1396 {extract_subsidiary_tail_file_name(Span,Filename)},
1397 %{bmachine:b_get_main_filenumber(MainFN), Nr \= MainFN},!,
1398 !,
1399 " File:", ppterm(Filename).
1400 translate_span_file_opt(Span,Print) --> translate_span_file(Span,Print),!.
1401 translate_span_file_opt(_,_) --> "".
1402
1403
1404 explain_span_file(Span) -->
1405 {extract_subsidiary_tail_file_name(Span,Filename)},
1406 %{bmachine:b_get_main_filenumber(MainFN), Nr \= MainFN},!,
1407 "\n### File: ", ppterm(Filename).
1408 explain_span_file(_) --> "".
1409
1410 explain_span(V) --> {var(V)},!, "Internal error: Illegal variable span".
1411 explain_span(span_predicate(Pred,LS,S)) --> !, explain_span2(span_predicate(Pred,LS,S)),
1412 explain_local_state(LS). %, explain_global_state(S).
1413 explain_span(Span) --> explain_span2(Span).
1414 explain_span2(Span) --> {extract_line_col(Span,Srow,Scol,Erow,Ecol)},!,
1415 "\n### Line: ", ppterm(Srow), ", Column: ", ppterm(Scol),
1416 " until Line: ", ppterm(Erow), ", Column: ", ppterm(Ecol),
1417 explain_span_file(Span),
1418 explain_span_context(Span).
1419 explain_span2(Span) --> {extract_symbolic_label_pos(Span,Msg)},!,
1420 "\n @label: ", ppterm(Msg),
1421 explain_span_context(Span).
1422 explain_span2(Span) --> explain_span_context(Span).
1423
1424 explain_span_context(Span) --> {extract_additional_description(Span,Msg),!},
1425 "\n### within ", ppterm(Msg). % context of span, such as definition call hierarchy
1426 explain_span_context(_) --> "".
1427
1428 explain_local_state([]) --> !, "".
1429 explain_local_state(LS) --> "\n Local State: ", pp_b_state(LS,1000).
1430 %explain_global_state([]) --> !, "".
1431 %explain_global_state(LS) --> "\n Global State: ", pp_b_state(LS).
1432
1433 translate_event_error(Error,Out) :-
1434 ( translate_event_error2(Error,Out) -> true
1435 ;
1436 functor(Error,F,_),
1437 ajoin(['** Unable to translate event error: ',F,' **'],Out)).
1438 translate_event_error2(no_witness_found(Type,Var,_Predicate),Out) :-
1439 def_get_texpr_id(Var,Id),
1440 ajoin(['no witness was found for ',Type,' ',Id],Out).
1441 translate_event_error2(simulation_error(_Events),Out) :-
1442 Out = 'no matching abstract event was found'.
1443 translate_event_error2(action_not_executable(_Action,WDErr),Out) :-
1444 (WDErr=wd_error_possible -> Out = 'action was not executable (maybe with WD error)'
1445 ; Out = 'action was not executable').
1446 translate_event_error2(invalid_modification(Var,_Pre,_Post),Out) :-
1447 def_get_texpr_id(Var,Id),
1448 ajoin(['modification of variable ', Id, ' not allowed'],Out).
1449 translate_event_error2(variant_negative(_CType,_Variant,_Value),Out) :-
1450 Out = 'enabled for negative variant'.
1451 translate_event_error2(invalid_variant(anticipated,_Expr,_Pre,_Post),Out) :-
1452 Out = 'variant increased'.
1453 translate_event_error2(invalid_variant(convergent,_Expr,_Pre,_Post),Out) :-
1454 Out = 'variant not decreased'.
1455 translate_event_error2(invalid_theorem_in_guard(_Theorem),Out) :-
1456 Out = 'theorem in guard evaluates to false'.
1457 translate_event_error2(event_wd_error(_TExpr,Source),Out) :-
1458 ajoin(['WD error for ',Source],Out).
1459 translate_event_error2(event_other_error(Msg),Out) :- Out=Msg.
1460
1461 translate_state_error(abort_error(_TYPE,Msg,ErrTerm,ErrorContext),Out) :- !,
1462 translate_error_term(ErrTerm,ES),
1463 translate_error_context(ErrorContext,EC),
1464 ajoin([EC,': ',Msg,': ',ES],Out).
1465 translate_state_error(clpfd_overflow_error(Context),Out) :- !, % 'CLPFD_integer_overflow'
1466 ajoin(['CLPFD integer overflow while ', Context],Out).
1467 translate_state_error(max_state_errors_reached(Nr),Out) :- !,
1468 ajoin(['Max. number of state errors reached: ', Nr],Out).
1469 translate_state_error(Unknown,Out) :-
1470 add_error(translate_state_error,'Unknown state error: ',Unknown),
1471 Out = '*** Unknown State Error ***'.
1472
1473
1474 get_span_from_context([H],Span) :- !, get_span_from_context(H,Span).
1475 get_span_from_context(span_context(Span,_),Res) :- !, Res=Span.
1476 get_span_from_context(_,unknown).
1477
1478 explain_error_context1([H]) --> !,explain_error_context1(H).
1479 explain_error_context1(span_context(Span,Context)) --> !,
1480 explain_span(Span),"\n",
1481 explain_error_context2(Context).
1482 explain_error_context1(Ctxt) --> explain_error_context2(Ctxt).
1483
1484 explain_error_context2([H]) --> !,explain_error_context2(H).
1485 explain_error_context2(span_context(Span,Context)) --> !,
1486 explain_span(Span),"\n",
1487 explain_error_context2(Context).
1488 explain_error_context2(checking_invariant) --> !,
1489 {get_specification_description_codes(invariant,I)}, I, ":\n ", %"INVARIANT:\n ",
1490 pp_current_state. % assumes explain is called in the right state ! ; otherwise we need to store the state id
1491 explain_error_context2(checking_assertions) --> !,
1492 {get_specification_description_codes(assertions,A)}, A, ":\n ", %"ASSERTIONS:\n ",
1493 pp_current_state. % assumes explain is called in the right state ! ; otherwise we need to store the state id
1494 explain_error_context2(checking_negation_of_invariant(State)) --> !,
1495 "not(INVARIANT):\n State: ",
1496 pp_b_state(State,1000).
1497 explain_error_context2(operation('$setup_constants',StateID)) --> !,
1498 {get_specification_description_codes(properties,P)}, P, ":\n State: ",
1499 pp_context_state(StateID).
1500 explain_error_context2(operation(OpName,StateID)) --> !,
1501 {get_specification_description_codes(operation,OP)}, OP, ": ", %"EVENT/OPERATION: ",
1502 {translate_operation_name(OpName,TOp)},
1503 ppterm(TOp), "\n ",
1504 pp_context_state(StateID).
1505 explain_error_context2(checking_context(Check,Name)) --> !,
1506 ppterm(Check),ppterm(Name), "\n ".
1507 explain_error_context2(loading_context(Name)) --> !,
1508 "Loading: ",ppterm(Name), "\n ".
1509 explain_error_context2(visb_error_context(Class,SvgId,OpNameOrAttr,Span)) --> !,
1510 translate_error_context2(visb_error_context(Class,SvgId,OpNameOrAttr,Span)).
1511 explain_error_context2(X) --> "UNKNOWN ERROR CONTEXT:\n ", ppterm(X).
1512
1513 :- use_module(specfile,[get_specification_description/2]).
1514 get_specification_description_codes(Tag,Codes) :- get_specification_description(Tag,Atom), atom_codes(Atom,Codes).
1515
1516 explain_state_error(Error,Span,Out) :-
1517 explain_state_error2(Error,Span,Out,[]),!.
1518 explain_state_error(_Error,unknown,"Sorry, the detailed output failed.\n").
1519
1520 explain_abort_error_type(well_definedness_error) --> !, "An expression was not well-defined.\n".
1521 explain_abort_error_type(card_overflow_error) --> !, "The cardinality of a finite set was too large to be represented.\n".
1522 explain_abort_error_type(while_variant_error) --> !, "A while-loop VARIANT error occurred.\n".
1523 explain_abort_error_type(while_invariant_violation) --> !, "A while-loop INVARIANT error occurred.\n".
1524 explain_abort_error_type(precondition_error) --> !, "A precondition (PRE) error occurred.\n".
1525 explain_abort_error_type(assert_error) --> !, "An ASSERT error occurred.\n".
1526 explain_abort_error_type(Type) --> "Error occurred: ", ppterm(Type), "\n".
1527
1528 explain_state_error2(abort_error(TYPE,Msg,ErrTerm,ErrContext),Span) -->
1529 explain_abort_error_type(TYPE),
1530 "Reason: ", ppterm(Msg), "\n",
1531 {get_span_from_context(ErrContext,Span)},
1532 ({ErrTerm=''} -> ""
1533 ; "Details: ", {translate_error_term(ErrTerm,Span,ErrS)},ppterm(ErrS), "\n"
1534 ),
1535 "Context: ", explain_error_context1(ErrContext).
1536 explain_state_error2(max_state_errors_reached(Nr),unknown) -->
1537 "Too many error occurred for this state.\n",
1538 "Not all errors are shown.\n",
1539 "Number of errors is at least: ", ppterm(Nr).
1540 explain_state_error2(eventerror(_Event,Error,Trace),Span) --> % TO DO: also extract loc info ?
1541 {translate_event_error(Error,Msg)},
1542 ppatom(Msg),
1543 "\nA detailed trace containing the error:\n",
1544 "--------------------------------------\n",
1545 explain_event_trace(Trace,Span).
1546 explain_state_error2(clpfd_overflow_error(Context),unknown) --> % CLPFD_integer_overflow
1547 "An overflow occurred inside the CLP(FD) library.\n",
1548 "Context: ", ppterm(Context), "\n",
1549 "You may try and set the CLPFD preference to FALSE.\n".
1550
1551 % try and get span from state error:
1552 get_state_error_span(abort_error(_,_,_,Context),Span) :- get_span_context_span(Context,Span).
1553
1554 get_span_context_span(span_context(Span,_),Span).
1555 get_span_context_span([H],Span) :- get_span_context_span(H,Span).
1556
1557
1558
1559 show_parameter_values([],[]) --> !.
1560 show_parameter_values([P|Prest],[V|Vrest]) -->
1561 show_parameter_value(P,V),
1562 show_parameter_values(Prest,Vrest).
1563 show_parameter_value(P,V) -->
1564 " ",pp_expr(P,_,_LR)," = ",pp_value(V),"\n".
1565
1566 % translate an Event-B error trace (error occurred during multi-level animation)
1567 % into a textual description (Codes) and a span_predicate term which can be visualised
1568 explain_event_trace(Trace,Codes,Span) :-
1569 explain_event_trace(Trace,Span,Codes,[]).
1570
1571 explain_event_trace(Trace,span_predicate(SpanPred,[],[])) -->
1572 % evaluating the span predicate will require access to current state, which needs to be added later
1573 explain_event_trace4(Trace,'?','?',SpanPred).
1574
1575 explain_event_trace4([],_,_,b(truth,pred,[])) --> !.
1576 explain_event_trace4([event(Name,Section)|Trest],_,_,SpanPred) --> !,
1577 "\n",
1578 "Event ",ppterm(Name)," in model ",ppterm(Section),
1579 ":\n",
1580 % pass new current event name and section for processing tail:
1581 explain_event_trace4(Trest,Name,Section,SpanPred).
1582 explain_event_trace4([Step|Trest],Name,Section,SpanPred) -->
1583 "\n",
1584 ( explain_event_step4(Step,StepPred) -> ""
1585 ; {functor(Step,F,_)} ->
1586 " (no rule to explain event step ",ppatom(F),")\n"),
1587 explain_event_trace4(Trest,Name,Section,RestSpanPred),
1588 {combine_span_pred(StepPred,RestSpanPred,Name,Section,SpanPred)}.
1589
1590 % create a span predicate from the event error trace to display relevant values and predicates
1591 combine_span_pred(unknown,S,_,_,Res) :- !, Res=S.
1592 combine_span_pred(new_scope(Kind,Paras,Vals,P1),P2,Name,Section,Res) :- !,
1593 maplist(create_tvalue,Paras,Vals,TVals),
1594 add_span_label(Kind,Name,Section,P1,P1L),
1595 conjunct_predicates([P1L,P2],Body),
1596 (Paras=[] -> Res=Body ; Res = b(let_predicate(Paras,TVals,Body),pred,[])). % translate:print_bexpr(Res),nl.
1597 % we could also do: add_texpr_description
1598 combine_span_pred(P1,P2,_,_,Res) :-
1599 conjunct_predicates([P1,P2],Res).
1600
1601 add_span_label(Kind,Name,Section,Pred,NewPred) :-
1602 (Kind=[Label] -> true % already has position info
1603 ; create_label(Kind,Name,Section,Label)),
1604 add_labels_to_texpr(Pred,[Label],NewPred).
1605 create_label(Kind,Name,Section,Label) :- ajoin([Kind,' in ',Section,':',Name],Label).
1606
1607 create_tvalue(b(_,Type,_),Value,b(value(Value),Type,[])).
1608
1609 explain_event_step4(true_guard(Parameters,Values,Guard),new_scope('guard true',Parameters,Values,Guard)) --> !,
1610 ( {Parameters==[]} -> ""
1611 ; " for the parameters:\n",
1612 show_parameter_values(Parameters,Values)),
1613 " the guard is true:",
1614 explain_predicate(Guard,4),"\n".
1615 explain_event_step4(eval_witness(Type,Id,Value,Predicate),new_scope('witness',[Id],[Value],Predicate)) -->
1616 witness_intro(Id,Predicate,Type),
1617 " found witness:\n",
1618 " ", pp_expr(Id,_,_LR), " = ", pp_value(Value), "\n".
1619 explain_event_step4(simulation_error(Errors),SpanPred) -->
1620 " no guard of a refined event was satisfiable:\n",
1621 explain_simulation_errors(Errors,Guards),
1622 {disjunct_predicates(Guards,SpanPred)}.
1623 explain_event_step4(invalid_theorem_in_guard(Theorem),new_scope('false theorem',[],[],Theorem)) -->
1624 " the following theorem evaluates to false:",
1625 explain_predicate(Theorem,4),"\n".
1626 explain_event_step4(invalid_modification(Var,Pre,Post),
1627 new_scope('invalid modification',[Var],[Post],b(falsity,pred,[]))) -->
1628 " the variable ", pp_expr(Var,_,_LR), " has been modified.\n",
1629 " The event is not allowed to modify the variable because its abstract event does not modify it.\n",
1630 " Old value: ", pp_value(Pre), "\n",
1631 " New value: ", pp_value(Post), "\n".
1632 explain_event_step4(action_not_executable(TAction,WDErr),new_scope('action not executable',[],[],Equalities)) -->
1633 {exctract_span_pred_from_subst(TAction,Equalities)},
1634 explain_action_not_executable(TAction,WDErr).
1635 explain_event_step4(Step,unknown) -->
1636 explain_event_step(Step).
1637 % TODO: add span predicates for the errors below:
1638
1639 extract_equality(Infos,TID,NewExpr,b(equal(TID,NewExpr),pred,Infos)). % TODO: introduce TID' primed?
1640 exctract_span_pred_from_subst(b(assign(TIDs,Exprs),subst,Infos),SpanPred) :-
1641 maplist(extract_equality(Infos),TIDs,Exprs,List),
1642 conjunct_predicates(List,SpanPred).
1643 % todo: becomes_such, ...
1644
1645 explain_event_step(variant_checked_pre(CType,Variant,Value)) -->
1646 " ",ppatom(CType)," event: checking if the variant is non-negative:\n",
1647 " variant: ",pp_expr(Variant,_,_LR),"\n",
1648 " its value: ",pp_value(Value),"\n".
1649 explain_event_step(variant_negative(CType,Variant,Value)) -->
1650 explain_event_step(variant_checked_pre(CType,Variant,Value)),
1651 " ERROR: variant is negative\n".
1652 explain_event_step(variant_checked_post(CType,Variant,EntryValue,ExitValue)) -->
1653 " ",ppatom(CType)," event: checking if the variant is ",
1654 ( {CType==convergent} -> "decreased:\n" ; "not increased:\n"),
1655 " variant: ", pp_expr(Variant,_,_LR), "\n",
1656 " its value before: ", pp_value(EntryValue),"\n",
1657 " its value after: ", pp_value(ExitValue),"\n".
1658 explain_event_step(invalid_variant(CType,Variant,EntryValue,ExitValue)) -->
1659 explain_event_step(variant_checked_post(CType,Variant,EntryValue,ExitValue)),
1660 " ERROR: variant has ",
1661 ({CType==convergent} -> "not been decreased\n"; "has been increased\n").
1662 explain_event_step(no_witness_found(Type,Id,Predicate)) -->
1663 witness_intro(Id,Predicate,Type),
1664 " ERROR: no solution for witness predicate found!\n".
1665 explain_event_step(action(Lhs,_Rhs,Values)) -->
1666 " executing an action:\n",
1667 show_assignments(Lhs,Values).
1668 explain_event_step(action_set(Lhs,_Rhs,ValueSet,Values)) -->
1669 " executing an action:\n ",
1670 pp_expr_l(Lhs,_LR)," :: ",pp_value(ValueSet),"\n choosing\n",
1671 show_assignments(Lhs,Values).
1672 explain_event_step(action_pred(Ids,Pred,Values)) -->
1673 " executing an action:\n ",
1674 pp_expr_l(Ids,_LR1)," :| ",pp_expr(Pred,_,_LR2),"\n choosing\n",
1675 show_assignments(Ids,Values).
1676 explain_event_step(error(Error,_Id)) -->
1677 % the error marker serves to link to a stored state-error by its ID
1678 explain_event_step(Error).
1679 explain_event_step(event_wd_error(TExpr,Source)) -->
1680 " Well-Definedness ERROR for ", ppatom(Source), "\n",
1681 " ", pp_expr(TExpr,_,_LR), "\n".
1682 explain_event_step(event_other_error(Msg)) --> ppatom(Msg).
1683
1684 explain_action_not_executable(TAction,no_wd_error) --> {is_assignment_to(TAction,IDs)},!,
1685 " ERROR: the following assignment to ", ppatoms(IDs),"was not executable\n",
1686 " (probably in conflict with another assignment, check SIM or EQL PO):", % or WD error
1687 translate_subst_with_indention_and_label(TAction,4).
1688 explain_action_not_executable(TAction,wd_error_possible) --> !,
1689 " ERROR: the following action was not executable\n",
1690 " (possibly due to a WD error):",
1691 translate_subst_with_indention_and_label(TAction,4).
1692 explain_action_not_executable(TAction,_WDErr) -->
1693 " ERROR: the following action was not executable:",
1694 translate_subst_with_indention_and_label(TAction,4).
1695
1696 is_assignment_to(b(assign(LHS,_),_,_),IDs) :- get_texpr_ids(LHS,IDs).
1697
1698 witness_intro(Id,Predicate,Type) -->
1699 " evaluating witness for abstract ", ppatom(Type), " ", pp_expr(Id,_,_LR1), "\n",
1700 " witness predicate: ", pp_expr(Predicate,_,_LR2), "\n".
1701
1702 show_assignments([],[]) --> !.
1703 show_assignments([Lhs|Lrest],[Val|Vrest]) -->
1704 " ",pp_expr(Lhs,_,_LimitReached), " := ", pp_value(Val), "\n",
1705 show_assignments(Lrest,Vrest).
1706
1707 /* unused at the moment:
1708 explain_state([]) --> !.
1709 explain_state([bind(Varname,Value)|Rest]) --> !,
1710 " ",ppterm(Varname)," = ",pp_value(Value),"\n",
1711 explain_state(Rest).
1712 explain_guards([]) --> "".
1713 explain_guards([Event|Rest]) -->
1714 {get_texpr_expr(Event,rlevent(Name,_Section,_Status,_Params,Guard,_Theorems,_Act,_VWit,_PWit,_Unmod,_Evt))},
1715 "\n",ppatom(Name),":",
1716 explain_predicate(Guard),
1717 explain_guards(Rest).
1718 explain_predicate(Guard,I,O) :-
1719 explain_predicate(Guard,2,I,O).
1720 */
1721 explain_predicate(Guard,Indention,I,O) :-
1722 pred_over_lines(0,'@grd',Guard,(Indention,I),(_,O)).
1723
1724 explain_simulation_errors([],[]) --> !.
1725 explain_simulation_errors([Error|Rest],[Grd|Gs]) -->
1726 explain_simulation_error(Error,Grd),
1727 explain_simulation_errors(Rest,Gs).
1728 explain_simulation_error(event(Name,Section,Guard),SpanPred) -->
1729 {add_span_label('guard false',Name,Section,Guard,SpanPred)},
1730 " guard for event ", ppatom(Name),
1731 " in ", ppatom(Section), ":",
1732 explain_predicate(Guard,6),"\n".
1733
1734 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1735 % pretty-print a state
1736
1737
1738 print_state(State) :- b_state(State), !,print_bstate(State).
1739 print_state(csp_and_b_root) :- csp_with_bz_mode, !,
1740 print('(MAIN || B)').
1741 print_state(csp_and_b(CSPState,BState)) :- csp_with_bz_mode, !,
1742 print_bstate(BState), translate_cspm_state(CSPState,Text), print(Text).
1743 print_state(CSPState) :- csp_mode,!,translate_cspm_state(CSPState,Text), print(Text).
1744 print_state(State) :- animation_mode(xtl),!,print(State).
1745 print_state(State) :- print('*** Unknown state: '),print(State).
1746
1747 b_state(root).
1748 b_state(concrete_constants(_)).
1749 b_state(const_and_vars(_,_)).
1750 b_state(expanded_const_and_vars(_,_,_,_)).
1751 b_state(expanded_vars(_,_)).
1752 b_state([bind(_,_)|_]).
1753 b_state([]).
1754
1755 print_bstate(State) :- print_bstate_limited(State,1000,-1).
1756 print_bstate_limited(State,VarLimit,OverallLimit) :-
1757 translate_bstate_limited(State,VarLimit,OverallLimit,Output), print(' '),print(Output).
1758
1759 translate_any_state(State,Output) :-
1760 get_pp_state_limit(Limit),
1761 pp_any_state(State,Limit,Codes,[]),
1762 atom_codes_with_limit(Output,Codes).
1763 translate_bstate(State,Output) :-
1764 get_pp_state_limit(Limit),
1765 pp_b_state(State,Limit,Codes,[]),
1766 atom_codes_with_limit(Output,Codes).
1767
1768 get_pp_state_limit(Limit) :-
1769 (get_preference(expand_avl_upto,-1) -> Limit = -1 ; Limit = 1000).
1770
1771 % a version which tries to generate smaller strings
1772 translate_bstate_limited(State,Output) :-
1773 temporary_set_preference(expand_avl_upto,2,CHNG),
1774 call_cleanup(translate_bstate_limited(State,200,Output),
1775 reset_temporary_preference(expand_avl_upto,CHNG)).
1776
1777 translate_bstate_limited(State,Limit,Output) :-
1778 translate_bstate_limited(State,Limit,Limit,Output).
1779 translate_bstate_limited(State,VarLimit,Limit,Output) :-
1780 pp_b_state(State,VarLimit,Codes,[]), % this limit VarLimit applies to every variable
1781 atom_codes_with_limit(Output,Limit,Codes). % Limit applies to the full translation
1782
1783 pp_b_state(X,Limit) --> try_pp_b_state(X,Limit),!.
1784 pp_b_state(X,_Limit) --> {add_error(pp_b_state,'Could not translate state: ',X)}.
1785
1786 % Limit is pretty-print limit for every value printed
1787 try_pp_b_state(VAR,_) --> {var(VAR)},!, "_?VAR?_", {add_error(pp_b_state,'Variable state: ',VAR)}.
1788 try_pp_b_state(root,_) --> !, "root".
1789 try_pp_b_state(concrete_constants(Constants),Limit) --> !,"Constants: ",
1790 pp_b_state(Constants,Limit).
1791 try_pp_b_state(const_and_vars(ID,Vars),Limit) --> !,
1792 "Constants:",ppterm(ID),", Vars:",
1793 {set_translation_constants(ID)}, /* extract constants which stand for deferred set elements */
1794 pp_b_state(Vars,Limit),
1795 {clear_translation_constants}.
1796 try_pp_b_state(expanded_const_and_vars(ID,Vars,_,_Infos),Limit) --> !, "EXPANDED ",
1797 try_pp_b_state(const_and_vars(ID,Vars),Limit).
1798 try_pp_b_state(expanded_vars(Vars,_Infos),Limit) --> !, "EXPANDED ",
1799 try_pp_b_state(Vars,Limit).
1800 try_pp_b_state([],_) --> !, "/* empty state */".
1801 try_pp_b_state([bind(Varname,Value)|Rest],Limit) --> !,
1802 "( ",ppterm(Varname),"=",
1803 dcg_set_up_limit_reached(Limit,LimitReached),
1804 pp_value(Value,LimitReached),
1805 ({Rest = []} -> []; " ",and_symbol,"\n "),
1806 pp_b_state_list(Rest,Limit).
1807
1808
1809 pp_b_state_list([],_) --> !, " )".
1810 pp_b_state_list([bind(Varname,Value)|Rest],Limit) --> !,
1811 ppterm(Varname),"=",
1812 dcg_set_up_limit_reached(Limit,LimitReached),
1813 pp_value(Value,LimitReached),
1814 ({Rest = []} -> [] ; " ",and_symbol,"\n "),
1815 pp_b_state_list(Rest,Limit).
1816 pp_b_state_list(X,_) --> {add_error(pp_b_state_list,'Could not translate: ',X)}.
1817
1818 % a version of pp which generates no newline; can be used for printing SETUP_CONSTANTS, INITIALISATION
1819 pp_b_state_comma_list([],_,_) --> !, ")".
1820 pp_b_state_comma_list(_,Cur,Limit) --> {Cur >= Limit}, !, "...".
1821 pp_b_state_comma_list([bind(Varname,Value)|Rest],Cur,Limit) --> !,
1822 %{print(c(Varname,Cur,Limit)),nl},
1823 start_size(Ref),
1824 ppterm(Varname),"=",
1825 pp_value(Value),
1826 ({Rest = []}
1827 -> ")"
1828 ; ",",
1829 end_size(Ref,Size), % compute size increase wrt Ref point
1830 {Cur1 is Cur+Size},
1831 pp_b_state_comma_list(Rest,Cur1,Limit)
1832 ).
1833 pp_b_state_comma_list(X,_,_) --> {add_error(pp_b_state_comma_list,'Could not translate: ',X)}.
1834
1835 start_size(X,X,X).
1836 end_size(RefVar,Len,X,X) :- % compute how many chars the dcg has added wrt start_size
1837 len(RefVar,X,Len).
1838 len(Var,X,Len) :- (var(Var) ; Var==X),!, Len=0.
1839 len([],_,0).
1840 len([_|T],X,Len) :- len(T,X,L1), Len is L1+1.
1841
1842 % can be used e.g. for setup_constants, initialise
1843 translate_b_state_to_comma_list_codes(FUNCTORCODES,State,Limit,ResCodes) :-
1844 pp_b_state_comma_list(State,0,Limit,Codes,[]),
1845 append("(",Codes,C0),
1846 append(FUNCTORCODES,C0,ResCodes).
1847
1848 % translate to a single line without newlines
1849 translate_b_state_to_comma_list(State,Limit,ResAtom) :-
1850 pp_b_state_comma_list(State,0,Limit,Codes,[]),
1851 append("(",Codes,C0),
1852 atom_codes(ResAtom,C0).
1853
1854 % ----------------
1855
1856 % printing and translating error contexts
1857 print_context(State) :- translate_context(State,Output), print(Output).
1858
1859 translate_context(Context,Output) :-
1860 pp_b_context(Context,Codes,[]),
1861 atom_codes_with_limit(Output,250,Codes).
1862
1863 pp_b_context([]) --> !.
1864 pp_b_context([C|Rest]) --> !,
1865 pp_b_context(C),
1866 pp_b_context(Rest).
1867 pp_b_context(translate_context) --> !, " ERROR CONTEXT: translate_context". % error occurred within translate_context
1868 pp_b_context(span_context(Span,Context)) --> !,
1869 pp_b_context(Context), " ", translate_span(Span,only_subsidiary).
1870 pp_b_context(operation(Name,StateID)) --> !,
1871 " ERROR CONTEXT: ",
1872 {get_specification_description_codes(operation,OP)}, OP, ":", % "OPERATION:"
1873 ({var(Name)} -> ppterm('ALL') ; {translate_operation_name(Name,TName)},ppterm(TName)),
1874 ",",pp_context_state(StateID).
1875 pp_b_context(checking_invariant) --> !,
1876 " ERROR CONTEXT: INVARIANT CHECKING,", pp_cur_context_state.
1877 pp_b_context(checking_negation_of_invariant(State)) --> !,
1878 " ERROR CONTEXT: NEGATION_OF_INVARIANT CHECKING, State:", pp_b_state(State,1000).
1879 pp_b_context(checking_assertions) --> !,
1880 " ERROR CONTEXT: ASSERTION CHECKING,", pp_cur_context_state.
1881 pp_b_context(checking_context(Check,Name)) --> !,
1882 " ERROR CONTEXT: ", ppterm(Check),ppterm(Name).
1883 pp_b_context(loading_context(_FName)) --> !.
1884 pp_b_context(unit_test_context(Module,TotNr,Line,Call)) --> !,
1885 " ERROR CONTEXT: Unit Test ", ppterm(TotNr), " in module ", ppterm(Module),
1886 " at line ", ppterm(Line), " calling ", pp_functor(Call).
1887 pp_b_context(visb_error_context(Class,ID,OpNameOrAttr,Span)) --> !,
1888 " ERROR CONTEXT: VisB ", ppterm(Class), " with ID ", ppterm(ID),
1889 ({OpNameOrAttr='all_attributes'} -> ""
1890 ; " and attribute/event ", ppterm(OpNameOrAttr)
1891 ),
1892 " ", translate_span(Span,only_subsidiary).
1893 pp_b_context(C) --> ppterm(C),pp_cur_context_state.
1894
1895 pp_functor(V) --> {var(V)},!, ppterm(V).
1896 pp_functor(T) --> {functor(T,F,N)}, ppterm(F),"/",ppterm(N).
1897
1898 pp_cur_context_state --> {state_space:get_current_context_state(ID)}, !,pp_context_state(ID).
1899 pp_cur_context_state --> ", unknown context state.".
1900
1901 % assumes we are in the right state:
1902 pp_current_state --> {state_space:current_expression(ID,_)}, !,pp_context_state(ID).
1903 pp_current_state --> ", unknown current context state.".
1904
1905 % TO DO: limit length/size of generated error description
1906 pp_context_state(ID) --> {state_space:visited_expression(ID,State)},!, % we have a state ID
1907 " State ID:", ppterm(ID),
1908 pp_context_state2(State).
1909 pp_context_state(State) --> pp_context_state3(State).
1910
1911 pp_context_state2(_) --> {debug:debug_mode(off)},!.
1912 pp_context_state2(State) --> ",", pp_context_state3(State).
1913
1914 pp_context_state3(State) --> " State: ",pp_any_state_with_limit(State,10).
1915
1916 pp_any_state_with_limit(State,Limit) -->
1917 { get_preference(expand_avl_upto,CurLim),
1918 (CurLim<0 ; Limit < CurLim),
1919 !,
1920 temporary_set_preference(expand_avl_upto,Limit,CHNG),
1921 VarLimit is Limit*10
1922 },
1923 pp_any_state(State,VarLimit),
1924 {reset_temporary_preference(expand_avl_upto,CHNG)}.
1925 pp_any_state_with_limit(State,_Limit) -->
1926 {get_preference(expand_avl_upto,CurLim), VarLimit is CurLim*10},
1927 pp_any_state(State,VarLimit).
1928
1929 pp_any_state(X,VarLimit) --> try_pp_b_state(X,VarLimit),!.
1930 pp_any_state(csp_and_b(P,B),VarLimit) --> "CSP: ",{pp_csp_process(P,Atoms,[])},!,atoms_to_codelist(Atoms),
1931 " || B: ", try_pp_b_state(B,VarLimit).
1932 pp_any_state(X,_) --> {animation_mode(xtl)}, !, "XTL: ",ppterm(X). % CSP state
1933 pp_any_state(P,_) --> "CSP: ",{pp_csp_process(P,Atoms,[])},!,atoms_to_codelist(Atoms).
1934 pp_any_state(X,_) --> "Other formalism: ",ppterm(X). % CSP state
1935
1936 atoms_to_codelist([]) --> [].
1937 atoms_to_codelist([Atom|T]) --> ppterm(Atom), atoms_to_codelist(T).
1938
1939 % ----------------
1940
1941 :- dynamic deferred_set_constant/3.
1942
1943 set_translation_context(const_and_vars(ConstID,_)) :- !,
1944 %% print_message(setting_translation_constants(ConstID)),
1945 set_translation_constants(ConstID).
1946 set_translation_context(expanded_const_and_vars(ConstID,_,_,_)) :- !,
1947 set_translation_constants(ConstID).
1948 set_translation_context(_).
1949
1950 set_translation_constants(_) :- clear_translation_constants,
1951 get_preference(dot_print_use_constants,false),!.
1952 set_translation_constants(ConstID) :- var(ConstID),!,
1953 add_error(set_translation_constants,'Variable used as ConstID: ',ConstID).
1954 set_translation_constants(ConstID) :-
1955 state_space:visited_expression(ConstID,concrete_constants(ConstantsStore)),!,
1956 %% print_message(setting_constants(ConstID)),%%
1957 (treat_constants(ConstantsStore) -> true ; print_message(fail)).
1958 set_translation_constants(ConstID) :-
1959 add_error(set_translation_constants,'Unknown ConstID: ',ConstID).
1960
1961 clear_translation_constants :- %print_message(clearing),%%
1962 retractall(deferred_set_constant(_,_,_)).
1963
1964 treat_constants([]).
1965 treat_constants([bind(CstName,Val)|T]) :-
1966 ((Val=fd(X,GSet),b_global_deferred_set(GSet))
1967 -> (deferred_set_constant(GSet,X,_)
1968 -> true /* duplicate def of value */
1969 ; assertz(deferred_set_constant(GSet,X,CstName))
1970 )
1971 ; true
1972 ),
1973 treat_constants(T).
1974
1975
1976
1977 translate_bvalue_with_tlatype(Value,Type,Output) :-
1978 ( pp_tla_value(Type,Value,Codes,[]) ->
1979 atom_codes_with_limit(Output,Codes)
1980 ; add_error(translate_bvalue,'Could not translate TLA value: ',Value),
1981 Output='???').
1982
1983 pp_tla_value(function(_Type1,_Type2),[]) --> !,
1984 ppcodes("<<>>").
1985 pp_tla_value(function(integer,T2),avl_set(Set)) -->
1986 {convert_avlset_into_sequence(Set,Seq)}, !,
1987 pp_tla_with_sep("<< "," >>",",",T2,Seq).
1988 pp_tla_value(function(T1,T2),Set) -->
1989 {is_printable_set(Set,Values)},!,
1990 pp_tla_with_sep("(",")"," @@ ",function_value(T1,T2),Values).
1991 pp_tla_value(function_value(T1,T2),(L,R)) -->
1992 !,pp_tla_value(T1,L),":>",pp_tla_value(T2,R).
1993 pp_tla_value(set(Type),Set) -->
1994 {is_printable_set(Set,Values)},!,
1995 pp_tla_with_sep("{","}",",",Type,Values).
1996 pp_tla_value(tuple(Types),Value) -->
1997 {pairs_to_list(Types,Value,Values,[]),!},
1998 pp_tla_with_sep("<< "," >>",",",Types,Values).
1999 pp_tla_value(record(Fields),rec(FieldValues)) -->
2000 % TODO: Check if we can safely assume that Fields and FieldValues have the
2001 % same order
2002 !, {sort_tla_fields(Fields,FieldValues,RFields,RFieldValues)},
2003 pp_tla_with_sep("[","]",", ",RFields,RFieldValues).
2004 pp_tla_value(field(Name,Type),field(_,Value)) -->
2005 !, ppatom_opt_scramble(Name)," |-> ",pp_tla_value(Type,Value).
2006 pp_tla_value(_Type,Value) -->
2007 % fallback: use B's pretty printer
2008 pp_value(Value).
2009
2010 is_printable_set(avl_set(A),List) :- avl_domain(A,List).
2011 is_printable_set([],[]).
2012 is_printable_set([H|T],[H|T]).
2013
2014 pairs_to_list([_],Value) --> !,[Value].
2015 pairs_to_list([_|Rest],(L,R)) -->
2016 pairs_to_list(Rest,L),[R].
2017
2018
2019 sort_tla_fields([],_,[],[]).
2020 sort_tla_fields([Field|RFields],ValueFields,RFieldTypes,ResultValueFields) :-
2021 ( Field=field(Name,Type) -> true
2022 ; Field= opt(Name,Type) -> true),
2023 ( selectchk(field(Name,Value),ValueFields,RestValueFields),
2024 field_value_present(Field,Value,Result) ->
2025 % Found the field in the record value
2026 RFieldTypes = [field(Name,Type) |RestFields],
2027 ResultValueFields = [field(Name,Result)|RestValues],
2028 sort_tla_fields(RFields,RestValueFields,RestFields,RestValues)
2029 ;
2030 % didn't found the field in the value -> igore
2031 sort_tla_fields(RFields,ValueFields,RFieldTypes,ResultValueFields)
2032 ).
2033 field_value_present(field(_,_),RecValue,RecValue). % Obligatory fields are always present
2034 field_value_present(opt(_,_),OptValue,Value) :-
2035 % Optional fields are present if the field is of the form TRUE |-> Value.
2036 ( is_printable_set(OptValue,Values) -> Values=[(_TRUE,Value)]
2037 ;
2038 add_error(translate,'exptected set for TLA optional record field'),
2039 fail
2040 ).
2041
2042 pp_tla_with_sep(Start,End,Sep,Type,Values) -->
2043 ppcodes(Start),pp_tla_with_sep_aux(Values,End,Sep,Type).
2044 pp_tla_with_sep_aux([],End,_Sep,_Type) -->
2045 ppcodes(End).
2046 pp_tla_with_sep_aux([Value|Rest],End,Sep,Type) -->
2047 % If a single type is given, we interpret it as the type
2048 % for each element of the list, if it is a list, we interpret
2049 % it one different type for every value in the list.
2050 { (Type=[CurrentType|RestTypes] -> true ; CurrentType = Type, RestTypes=Type) },
2051 pp_tla_value(CurrentType,Value),
2052 ( {Rest=[_|_]} -> ppcodes(Sep); {true} ),
2053 pp_tla_with_sep_aux(Rest,End,Sep,RestTypes).
2054
2055
2056 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2057 % pretty-print a value
2058
2059 translate_bvalue_for_dot(string(S),Translation) :- !,
2060 % normal quotes confuse dot
2061 %ajoin(['''''',S,''''''],Translation).
2062 string_escape(S,ES),
2063 ajoin(['\\"',ES,'\\"'],Translation).
2064 translate_bvalue_for_dot(Val,ETranslation) :-
2065 translate_bvalue(Val,Translation),
2066 string_escape(Translation,ETranslation).
2067
2068 translate_bvalue_to_codes(V,Output) :-
2069 ( pp_value(V,_LimitReached,Codes,[]) ->
2070 Output=Codes
2071 ; add_error(translate_bvalue_to_codes,'Could not translate bvalue: ',V),
2072 Output="???").
2073 translate_bvalue_to_codes_with_limit(V,Limit,Output) :-
2074 set_up_limit_reached(Codes,Limit,LimitReached), % TODO: also limit expand_avl_upto
2075 ( pp_value(V,LimitReached,Codes,[]) ->
2076 Output=Codes
2077 ; add_error(translate_bvalue_to_codes,'Could not translate bvalue: ',V),
2078 Output="???").
2079
2080 translate_bvalue(V,Output) :-
2081 %set_up_limit_reached(Codes,1000000,LimitReached), % we could set a very high-limit, like max_atom_length
2082 ( pp_value(V,_LimitReached,Codes,[]) ->
2083 atom_codes_with_limit(Output,Codes) % just catches representation error
2084 ; add_error(translate_bvalue,'Could not translate bvalue: ',V),
2085 Output='???').
2086 :- use_module(preferences).
2087 translate_bvalue_with_limit(V,Limit,Output) :-
2088 get_preference(expand_avl_upto,Max),
2089 ((Max > Limit % no sense in printing larger AVL trees
2090 ; (Max < 0, Limit >= 0)) % or setting limit to -1 for full value
2091 -> temporary_set_preference(expand_avl_upto,Limit,CHNG)
2092 ; CHNG=false),
2093 call_cleanup(translate_bvalue_with_limit_aux(V,Limit,Output),
2094 reset_temporary_preference(expand_avl_upto,CHNG)).
2095 translate_bvalue_with_limit_aux(V,Limit,OutputAtom) :-
2096 set_up_limit_reached(Codes,Limit,LimitReached),
2097 ( pp_value(V,LimitReached,Codes,[]) ->
2098 atom_codes_with_limit(OutputAtom,Limit,Codes)
2099 % ,length(Codes,Len), (Len>Limit -> format('pp(~w) codes:~w, limit:~w, String=~s~n~n',[LimitReached,Len,Limit,Codes]) ; true)
2100 ; add_error(translate_bvalue_with_limit,'Could not translate bvalue: ',V),
2101 OutputAtom='???').
2102
2103 translate_bvalues(Values,Output) :-
2104 translate_bvalues_with_limit(Values,no_limit,Output). % we could set a very high-limit, like max_atom_length
2105
2106 translate_bvalues_with_limit(Values,Limit,Output) :-
2107 (Limit==no_limit -> true %
2108 ; set_up_limit_reached(Codes,Limit,LimitReached)
2109 ),
2110 pp_value_l(Values,',',LimitReached,Codes,[]),!,
2111 atom_codes_with_limit(Output,Codes).
2112 translate_bvalues_with_limit(Values,Limit,O) :-
2113 add_internal_error('Call failed: ',translate_bvalues(Values,Limit,O)), O='??'.
2114
2115 translate_bvalue_for_expression(Value,TExpr,Output) :-
2116 animation_minor_mode(tla),
2117 expression_has_tla_type(TExpr,TlaType),!,
2118 translate_bvalue_with_tlatype(Value,TlaType,Output).
2119 translate_bvalue_for_expression(Value,TExpr,Output) :-
2120 get_texpr_type(TExpr,Type),
2121 translate_bvalue_with_type(Value,Type,Output).
2122
2123 translate_bvalue_for_expression_with_limit(Value,TExpr,_Limit,Output) :-
2124 animation_minor_mode(tla),
2125 expression_has_tla_type(TExpr,TlaType),!,
2126 translate_bvalue_with_tlatype(Value,TlaType,Output). % TO DO: treat Limit
2127 translate_bvalue_for_expression_with_limit(Value,TExpr,Limit,Output) :-
2128 get_texpr_type(TExpr,Type),
2129 translate_bvalue_with_type_and_limit(Value,Type,Limit,Output).
2130
2131 expression_has_tla_type(TExpr,Type) :-
2132 get_texpr_info(TExpr,Infos),
2133 memberchk(tla_type(Type),Infos).
2134
2135
2136 translate_bvalue_to_parseable_classicalb(Val,Str) :-
2137 % corresponds to set_print_type_infos(needed)
2138 temporary_set_preference(translate_force_all_typing_infos,false,CHNG),
2139 temporary_set_preference(translate_print_typing_infos,true,CHNG2),
2140 (animation_minor_mode(X)
2141 -> remove_animation_minor_mode,
2142 call_cleanup(translate_bvalue_to_parseable_aux(Val,Str),
2143 (reset_temporary_preference(translate_force_all_typing_infos,CHNG),
2144 reset_temporary_preference(translate_print_typing_infos,CHNG2),
2145 set_animation_minor_mode(X)))
2146 ; call_cleanup(translate_bvalue_to_parseable_aux(Val,Str),
2147 (reset_temporary_preference(translate_force_all_typing_infos,CHNG),
2148 reset_temporary_preference(translate_print_typing_infos,CHNG2)))
2149 ).
2150 translate_bvalue_to_parseable_aux(Val,Str) :-
2151 call_pp_with_no_limit_and_parseable(translate_bvalue(Val,Str)).
2152
2153
2154 translate_bexpr_to_parseable(Expr,Str) :-
2155 call_pp_with_no_limit_and_parseable(translate_bexpression(Expr,Str)).
2156
2157 % a more refined pretty printing: takes Type information into account; useful for detecting sequences
2158 translate_bvalue_with_type(Value,_,Output) :- var(Value),!,
2159 translate_bvalue(Value,Output).
2160 translate_bvalue_with_type(Value,Type,Output) :-
2161 adapt_value_according_to_type(Type,Value,NewValue),
2162 translate_bvalue(NewValue,Output).
2163
2164 translate_bvalue_with_type_and_limit(Value,Type,Limit,Output) :-
2165 (Limit < 0 -> SetLim = -1 ; SetLim is Limit//2), % at least two symbols per element
2166 get_preference(expand_avl_upto,CurLim),
2167 ((CurLim < 0, SetLim >= 0) ; SetLim < CurLim),!,
2168 temporary_set_preference(expand_avl_upto,SetLim,CHNG),
2169 translate_bvalue_with_type_and_limit2(Value,Type,Limit,Output),
2170 reset_temporary_preference(expand_avl_upto,CHNG).
2171 translate_bvalue_with_type_and_limit(Value,Type,Limit,Output) :-
2172 translate_bvalue_with_type_and_limit2(Value,Type,Limit,Output).
2173 translate_bvalue_with_type_and_limit2(Value,_,Limit,Output) :- var(Value),!,
2174 translate_bvalue_with_limit(Value,Limit,Output).
2175 translate_bvalue_with_type_and_limit2(Value,Type,Limit,Output) :-
2176 adapt_value_according_to_type(Type,Value,NewValue),
2177 translate:translate_bvalue_with_limit(NewValue,Limit,Output).
2178 %debug:watch(translate:translate_bvalue_with_limit(NewValue,Limit,Output)).
2179
2180 :- use_module(avl_tools,[quick_avl_approximate_size/2]).
2181 adapt_value_according_to_type(_,Var,R) :- var(Var),!,R=Var.
2182 adapt_value_according_to_type(T,V,R) :- var(T),!,
2183 add_internal_error('Variable type: ',adapt_value_according_to_type(T,V,R)),
2184 R=V.
2185 adapt_value_according_to_type(integer,V,R) :- !,R=V.
2186 adapt_value_according_to_type(string,V,R) :- !,R=V.
2187 adapt_value_according_to_type(boolean,V,R) :- !,R=V.
2188 adapt_value_according_to_type(global(_),V,R) :- !,R=V.
2189 adapt_value_according_to_type(couple(TA,TB),(VA,VB),R) :- !, R=(RA,RB),
2190 adapt_value_according_to_type(TA,VA,RA),
2191 adapt_value_according_to_type(TB,VB,RB).
2192 adapt_value_according_to_type(set(Type),avl_set(A),Res) :- check_is_non_empty_avl(A),
2193 quick_avl_approximate_size(A,S),S<20,
2194 custom_explicit_sets:expand_custom_set_to_list(avl_set(A),List),!,
2195 maplist(adapt_value_according_to_type(Type),List,Res).
2196 adapt_value_according_to_type(set(_Type),V,R) :- !,R=V.
2197 adapt_value_according_to_type(seq(Type),V,R) :- !, % the type tells us it is a sequence
2198 (convert_set_into_sequence(V,VS)
2199 -> l_adapt_value_according_to_type(VS,Type,AVS),
2200 R=sequence(AVS)
2201 ; R=V).
2202 adapt_value_according_to_type(record(Fields),rec(Values),R) :- !,
2203 R=rec(AdaptedValues),
2204 % fields and values should be in the same (alphabetical) order
2205 maplist(adapt_record_field_according_to_type,Fields,Values,AdaptedValues).
2206 adapt_value_according_to_type(freetype(_),Value,R) :-
2207 Value = freeval(ID,_,Term),
2208 nonvar(Term), Term=term(ID), % not a constructor, just a value
2209 !,
2210 R = Value.
2211 adapt_value_according_to_type(freetype(_),freeval(ID,Case,SubValue),R) :- nonvar(Case),
2212 !,
2213 R = freeval(ID,Case,AdaptedSubValue),
2214 kernel_freetypes:get_freeval_type(ID,Case,SubType),
2215 adapt_value_according_to_type(SubType,SubValue,AdaptedSubValue).
2216 adapt_value_according_to_type(freetype(_),Value,R) :- !, R=Value.
2217 adapt_value_according_to_type(any,Value,R) :- !, R=Value.
2218 adapt_value_according_to_type(pred,Value,R) :- !, R=Value.
2219 adapt_value_according_to_type(_,term(V),R) :- !, R=term(V). % appears for unknown values (no_value_for) when ALLOW_INCOMPLETE_SETUP_CONSTANTS is true
2220 adapt_value_according_to_type(Type,Value,R) :- print(adapt_value_according_to_type_unknown(Type,Value)),nl,
2221 R=Value.
2222
2223 l_adapt_value_according_to_type([],_Type,R) :- !,R=[].
2224 l_adapt_value_according_to_type([H|T],Type,[AH|AT]) :-
2225 adapt_value_according_to_type(Type,H,AH),
2226 l_adapt_value_according_to_type(T,Type,AT).
2227
2228 adapt_record_field_according_to_type(field(Name,HTy),field(Name,H),field(Name,R)) :-
2229 adapt_value_according_to_type(HTy,H,R).
2230
2231
2232 pp_value_with_type(E,T,LimitReached) --> {adapt_value_according_to_type(T,E,AdaptedE)},
2233 pp_value(AdaptedE,LimitReached).
2234
2235 pp_value(V,In,Out) :-
2236 set_up_limit_reached(In,1000,LimitReached),
2237 pp_value(V,LimitReached,In,Out).
2238
2239 % LimitReached is a flag: when it is grounded to limit_reached this instructs pp_value to stop generating output
2240 pp_value(_,LimitReached) --> {LimitReached==limit_reached},!, "...".
2241 pp_value(V,_) --> {var(V)},!, pp_variable(V).
2242 pp_value('$VAR'(N),_) --> !,pp_numberedvar(N).
2243 pp_value(X,_) --> {cyclic_term(X)},!,underscore_symbol,"cyclic",underscore_symbol.
2244 pp_value(fd(X,GSet),_) --> {var(X)},!,
2245 ppatom(GSet),":", ppnumber(X). %":??".
2246 pp_value(fd(X,GSet),_) -->
2247 {b_global_sets:is_b_global_constant_hash(GSet,X,Res)},!,
2248 pp_identifier(Res).
2249 pp_value(fd(X,GSet),_) --> {deferred_set_constant(GSet,X,Cst)},!,
2250 pp_identifier(Cst).
2251 pp_value(fd(X,M),_) --> !,ppatom_opt_scramble(M),ppnumber(X).
2252 pp_value(int(X),_) --> !,ppnumber(X).
2253 pp_value(term(floating(X)),_) --> !,ppnumber(X).
2254 pp_value(string(X),_) --> !,string_start_symbol,ppstring_opt_scramble(X),string_end_symbol.
2255 pp_value(global_set(X),_) --> {atomic(X),integer_set_mapping(X,Kind,Y)},!,
2256 ({Kind=integer_set} -> ppatom(Y) ; ppatom_opt_scramble(X)).
2257 pp_value(term(X),_) --> {var(X)},!,"term(",pp_variable(X),")".
2258 pp_value(freetype(X),_) --> {pretty_freetype(X,P)},!,ppatom_opt_scramble(P).
2259 pp_value(pred_true /* bool_true */,_) --> %!,"TRUE". % TO DO: in latex_mode: surround by mathit
2260 {constants_in_mode(pred_true,Symbol)},!,ppatom(Symbol).
2261 pp_value(pred_false /* bool_false */,_) --> %!,"FALSE".
2262 {constants_in_mode(pred_false,Symbol)},!,ppatom(Symbol).
2263 %pp_value(bool_true) --> !,"TRUE". % old version; still in some test traces which are printed
2264 %pp_value(bool_false) --> !,"FALSE".
2265 pp_value([],_) --> !,empty_set_symbol.
2266 pp_value(sequence(List),LimitReached) --> !,
2267 ({List=[]} -> pp_empty_sequence ; pp_sequence_with_limit(List,LimitReached)).
2268 pp_value([Head|Tail],LimitReached) --> {get_preference(translate_print_all_sequences,true),
2269 convert_set_into_sequence([Head|Tail],Elements)},
2270 !,
2271 pp_sequence(Elements,LimitReached).
2272 pp_value([Head|Tail],LimitReached) --> !, {set_brackets(L,R)},
2273 ppatom(L),
2274 pp_value_l_with_limit([Head|Tail],',',LimitReached),
2275 ppatom(R).
2276 %pp_value([Head|Tail]) --> !,
2277 % {( convert_set_into_sequence([Head|Tail],Elements) ->
2278 % (Start,End) = ('[',']')
2279 % ;
2280 % Elements = [Head|Tail],
2281 % (Start,End) = ('{','}'))},
2282 % ppatom(Start),pp_value_l(Elements,','),ppatom(End).
2283 pp_value( (A,B) ,LimitReached) --> !,
2284 "(",pp_inner_value(A,LimitReached),
2285 maplet_symbol,
2286 pp_value(B,LimitReached),")".
2287 pp_value(avl_set(A),LimitReached) --> !,
2288 {check_is_non_empty_avl(A),avl_size(A,Sz)},
2289 {set_brackets(LBrace,RBrace)},
2290 ( {size_is_in_set_limit(Sz),
2291 %(Sz>2 ; get_preference(translate_print_all_sequences,true)),
2292 get_preference(translate_print_all_sequences,true), % no longer try and convert any sequence longer than 2 to sequence notation
2293 avl_max(A,(int(Sz),_)), % a sequence has minimum int(1) and maximum int(Sz)
2294 convert_avlset_into_sequence(A,Seq)} ->
2295 pp_sequence(Seq,LimitReached)
2296 ;
2297 ( {Sz=0} -> left_set_bracket," /* empty avl_set */ ",right_set_bracket
2298 ; {(size_is_in_set_limit(Sz) ; Sz < 3)} -> % if Sz 3 we will print at least two elements anyway
2299 {avl_domain(A,List)},
2300 ppatom(LBrace),pp_value_l(List,',',LimitReached),ppatom(RBrace)
2301 ; {(Sz<5 ; \+ size_is_in_set_limit(4))} ->
2302 {avl_min(A,Min),avl_max(A,Max)},
2303 hash_card_symbol, % "#"
2304 ppnumber(Sz),":", left_set_bracket,
2305 pp_value(Min,LimitReached),",",ldots,",",pp_value(Max,LimitReached),right_set_bracket
2306 ;
2307 {avl_min(A,Min),avl_next(Min,A,Nxt),avl_max(A,Max),avl_prev(Max,A,Prev)},
2308 hash_card_symbol, % "#",
2309 ppnumber(Sz),":", left_set_bracket,
2310 pp_value(Min,LimitReached),",",pp_value(Nxt,LimitReached),",",ldots,",",
2311 pp_value(Prev,LimitReached),",",pp_value(Max,LimitReached),right_set_bracket )).
2312
2313 pp_value(field(Name,Value),LimitReached) --> !,
2314 pp_identifier(Name),":",pp_value(Value,LimitReached). % : for fields has priority 120 in French manual
2315 pp_value(rec(Rec),LimitReached) --> !,
2316 {function_like_in_mode(rec,Symbol)},
2317 ppatom(Symbol), "(",pp_value_l(Rec,',',LimitReached),")".
2318 pp_value(struct(Rec),LimitReached) --> !,
2319 {function_like_in_mode(struct,Symbol)},
2320 ppatom(Symbol), "(", pp_value_l(Rec,',',LimitReached),")".
2321 pp_value(term(no_value_for(Id)),_) --> !,
2322 "undefined ",ppatom(Id).
2323 pp_value(closure(Variables,Types,Predicate),LimitReached) --> !,
2324 pp_closure_value(Variables,Types,Predicate,LimitReached).
2325 pp_value(freeval(Freetype,Case,Value),LimitReached) --> !,
2326 ({ground(Case),ground(Value),Value=term(Case)} -> ppatom_opt_scramble(Case)
2327 ; {ground(Case)} -> ppatom_opt_scramble(Case),"(",pp_value(Value,LimitReached),")"
2328 ; {pretty_freetype(Freetype,P)},
2329 "FREEVALUE[",ppatom_opt_scramble(P),
2330 ",",write_to_codes(Case),
2331 "](",pp_value(Value,LimitReached),")"
2332 ).
2333 pp_value(X,_) --> {animation_mode(xtl)},!,
2334 write_to_codes(X).
2335 pp_value(X,_) --> % the << >> pose problems when checking against FDR
2336 "<< ",write_to_codes(X)," >>".
2337
2338 pp_variable(V) --> write_to_codes(V). %underscore_symbol.
2339
2340 :- use_module(closures,[is_recursive_closure/3]).
2341
2342 pp_closure_value(Ids,Type,B,_LimitReached) -->
2343 {var(Ids) ; var(Type) ; var(B)},!,
2344 add_internal_error('Illegal value: ',pp_value_illegal_closure(Ids,Type,B)),
2345 "<< ILLEGAL ",write_to_codes(closure(Ids,Type,B))," >>".
2346 pp_closure_value(Variables,Types,Predicate,LimitReached) --> {\+ size_is_in_set_limit(1)},
2347 !, % do not print body; just print hash value
2348 {make_closure_ids(Variables,Types,Ids), term_hash(Predicate,PH)},
2349 left_set_bracket, % { Ids | #PREDICATE#(HASH) }
2350 pp_expr_l_pair_in_mode(Ids,LimitReached),
2351 pp_such_that_bar,
2352 " ",hash_card_symbol,"PREDICATE",hash_card_symbol,"(",ppnumber(PH),") ", right_set_bracket.
2353 pp_closure_value(Variables,Types,Predicate,LimitReached) -->
2354 {get_preference(translate_ids_to_parseable_format,true),
2355 is_recursive_closure(Variables,Types,Predicate),
2356 get_texpr_info(Predicate,Infos),
2357 member(prob_annotation(recursive(TID)),Infos),
2358 def_get_texpr_id(TID,ID)}, !,
2359 % write recursive let for f as : CHOOSE(.) or MU({f|f= SET /*@desc letrec */ })
2360 % an alternate syntax could be RECLET f BE f = SET IN f END
2361 "MU({", pp_identifier(ID), "|",
2362 pp_identifier(ID)," = ",
2363 pp_closure_value2(Variables,Types,Predicate,LimitReached),
2364 "/*@desc letrec */ }) ".
2365 pp_closure_value([Id],[Type],Membership,LimitReached) -->
2366 { get_texpr_expr(Membership,member(Elem,Set)),
2367 get_texpr_id(Elem,Id),
2368 \+ occurs_in_expr(Id,Set), % detect things like {s|s : 1 .. card(s) --> T} (test 1030)
2369 get_texpr_type(Elem,Type),
2370 !},
2371 pp_expr_m(Set,299,LimitReached).
2372 pp_closure_value(Variables,Types,Predicate,LimitReached) --> pp_closure_value2(Variables,Types,Predicate,LimitReached).
2373
2374 pp_closure_value2(Variables,Types,Predicate,LimitReached) --> !,
2375 {make_closure_ids(Variables,Types,Ids)},
2376 pp_comprehension_set(Ids,Predicate,[],LimitReached). % TODO: propagate LimitReached
2377
2378 % avoid printing parentheses:
2379 % (x,y,z) = ((x,y),z)
2380 pp_inner_value( AB , LimitReached) --> {nonvar(AB),AB=(A,B)}, !, % do not print parentheses in this context
2381 pp_inner_value(A,LimitReached),maplet_symbol,
2382 pp_value(B,LimitReached).
2383 pp_inner_value( Value , LimitReached) --> pp_value( Value , LimitReached).
2384
2385 size_is_in_set_limit(Size) :- get_preference(expand_avl_upto,Max),
2386 (Max<0 -> true /* no limit */
2387 ; Size =< Max).
2388
2389 dcg_set_up_limit_reached(Limit,LimitReached,InList,InList) :- set_up_limit_reached(InList,Limit,LimitReached).
2390
2391 % instantiate LimitReached argument as soon as a list exceeds a certain limit
2392 set_up_limit_reached(_,Neg,_) :- Neg<0,!. % negative number means unlimited
2393 set_up_limit_reached(_,0,LimitReached) :- !, LimitReached = limit_reached.
2394 set_up_limit_reached(List,Limit,LimitReached) :-
2395 block_set_up_limit_reached(List,Limit,LimitReached).
2396 :- block block_set_up_limit_reached(-,?,?).
2397 block_set_up_limit_reached([],_,_).
2398 block_set_up_limit_reached([_|T],Limit,LimitReached) :-
2399 (Limit<1 -> LimitReached=limit_reached
2400 ; L1 is Limit-1, block_set_up_limit_reached(T,L1,LimitReached)).
2401
2402 % pretty print LimitReached, requires %:- block block_set_up_limit_reached(-,?,-).
2403 /*
2404 pp_lr(LR) --> {LR==limit_reached},!, " *LR* ".
2405 pp_lr(LR) --> {frozen(LR,translate:block_set_up_limit_reached(_,Lim,_))},!, " ok(", ppnumber(Lim),") ".
2406 pp_lr(LR) --> {frozen(LR,G)},!, " ok(", ppterm(G),") ".
2407 pp_lr(_) --> " ok ".
2408 */
2409
2410
2411 pp_value_l_with_limit(V,Sep,LimitReached) --> {get_preference(expand_avl_upto,Max)},
2412 pp_value_l(V,Sep,Max,LimitReached).
2413 pp_value_l(V,Sep,LimitReached) --> pp_value_l(V,Sep,-1,LimitReached).
2414
2415 pp_value_l(V,_Sep,_,_) --> {var(V)},!,"...".
2416 pp_value_l(_,_,_,LimitReached) --> {LimitReached==limit_reached},!,"...".
2417 pp_value_l('$VAR'(N),_Sep,_,_) --> !,"}\\/{",pp_numberedvar(N),"}".
2418 pp_value_l([],_Sep,_,_) --> !.
2419 pp_value_l([Expr|Rest],Sep,Limit,LimitReached) -->
2420 ( {nonvar(Rest),Rest=[]} ->
2421 pp_value(Expr,LimitReached)
2422 ; {Limit=0} -> "..."
2423 ;
2424 pp_value(Expr,LimitReached),
2425 % no separator for closure special case
2426 ({nonvar(Rest) , Rest = closure(_,_,_)} -> {true} ; ppatom(Sep)) ,
2427 {L1 is Limit-1} ,
2428 % convert avl_set(_) in a list's tail to a Prolog list
2429 {nonvar(Rest) , Rest = avl_set(_) -> custom_explicit_sets:expand_custom_set_to_list(Rest,LRest) ; LRest = Rest} ,
2430 pp_value_l(LRest,Sep,L1,LimitReached)).
2431 pp_value_l(avl_set(A),_Sep,_,LimitReached) --> pp_value(avl_set(A),LimitReached).
2432 pp_value_l(closure(A,B,C),_Sep,_,LimitReached) --> "}\\/", pp_value(closure(A,B,C),LimitReached).
2433
2434 make_closure_ids([],[],[]).
2435 make_closure_ids([V|Vrest],[T|Trest],[TExpr|TErest]) :-
2436 (var(V) -> V2='_', format('Illegal variable identifier in make_closure_ids: ~w~n',[V])
2437 ; V2=V),
2438 create_texpr(identifier(V2),T,[],TExpr),
2439 make_closure_ids(Vrest,Trest,TErest).
2440
2441 % symbol for starting and ending a sequence:
2442 pp_begin_sequence --> {animation_minor_mode(tla)},!,"<<".
2443 pp_begin_sequence --> {get_preference(translate_print_cs_style_sequences,true)},!,"".
2444 pp_begin_sequence --> "[".
2445 pp_end_sequence --> {animation_minor_mode(tla)},!,">>".
2446 pp_end_sequence --> {get_preference(translate_print_cs_style_sequences,true)},!,"".
2447 pp_end_sequence --> "]".
2448
2449 pp_separator_sequence('') :- get_preference(translate_print_cs_style_sequences,true),!.
2450 pp_separator_sequence(',').
2451
2452 % string for empty sequence
2453 pp_empty_sequence --> {animation_minor_mode(tla)},!, "<< >>".
2454 pp_empty_sequence --> {get_preference(translate_print_cs_style_sequences,true)},!,
2455 ( {latex_mode} -> "\\lambda" ; [955]). % 955 is lambda symbol in Unicode
2456 pp_empty_sequence --> {atelierb_mode(prover(_))},!, "{}".
2457 pp_empty_sequence --> "[]".
2458
2459 % symbols for function application:
2460 pp_function_left_bracket --> {animation_minor_mode(tla)},!, "[".
2461 pp_function_left_bracket --> "(".
2462
2463 pp_function_right_bracket --> {animation_minor_mode(tla)},!, "]".
2464 pp_function_right_bracket --> ")".
2465
2466 pp_sequence(Elements,LimitReached) --> {pp_separator_sequence(Sep)},
2467 pp_begin_sequence,
2468 pp_value_l(Elements,Sep,LimitReached),
2469 pp_end_sequence.
2470 pp_sequence_with_limit(Elements,LimitReached) --> {pp_separator_sequence(Sep)},
2471 pp_begin_sequence,
2472 pp_value_l_with_limit(Elements,Sep,LimitReached),
2473 pp_end_sequence.
2474
2475 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2476 % machines
2477
2478 :- use_module(eventhandling,[register_event_listener/3]).
2479 :- register_event_listener(clear_specification,reset_translate,
2480 'Reset Translation Caches.').
2481 reset_translate :- retractall(bugly_scramble_id_cache(_,_)), retractall(non_det_constants(_,_)).
2482 %reset_translate :- set_print_type_infos(none),
2483 % set_preference(translate_suppress_rodin_positions_flag,false).
2484
2485 suppress_rodin_positions(CHNG) :- set_suppress_rodin_positions(true,CHNG).
2486 set_suppress_rodin_positions(Value,CHNG) :-
2487 temporary_set_preference(translate_suppress_rodin_positions_flag,Value,CHNG).
2488 reset_suppress_rodin_positions(CHNG) :-
2489 reset_temporary_preference(translate_suppress_rodin_positions_flag,CHNG).
2490
2491 set_print_type_infos(none) :- !,
2492 set_preference(translate_force_all_typing_infos,false),
2493 set_preference(translate_print_typing_infos,false).
2494 set_print_type_infos(needed) :- !,
2495 set_preference(translate_force_all_typing_infos,false),
2496 set_preference(translate_print_typing_infos,true).
2497 set_print_type_infos(all) :- !,
2498 set_preference(translate_force_all_typing_infos,true),
2499 set_preference(translate_print_typing_infos,true).
2500 set_print_type_infos(Err) :-
2501 add_internal_error('Illegal typing setting: ',set_print_type_infos(Err)).
2502
2503 type_info_setting(none,false,false).
2504 type_info_setting(needed,false,true).
2505 type_info_setting(all,true,true).
2506
2507 set_print_type_infos(Setting,[CHNG1,CHNG2]) :-
2508 type_info_setting(Setting,Value1,Value2),!,
2509 temporary_set_preference(translate_force_all_typing_infos,Value1,CHNG1),
2510 temporary_set_preference(translate_print_typing_infos,Value2,CHNG2).
2511 set_print_type_infos(Err,_) :-
2512 add_internal_error('Illegal typing setting: ',set_print_type_infos(Err,_)),fail.
2513 reset_print_type_infos([CHNG1,CHNG2]) :-
2514 reset_temporary_preference(translate_force_all_typing_infos,CHNG1),
2515 reset_temporary_preference(translate_print_typing_infos,CHNG2).
2516
2517 :- use_module(tools_files,[put_codes/2]).
2518 print_machine(M) :-
2519 nl, translate_machine(M,Msg,true), put_codes(Msg,user_output), nl,
2520 flush_output(user_output),!.
2521 print_machine(M) :- add_internal_error('Printing failed: ',print_machine(M)).
2522
2523 %
2524 translate_machine(M,Codes,AdditionalInfo) :-
2525 retractall(print_additional_machine_info),
2526 (AdditionalInfo=true -> assertz(print_additional_machine_info) ; true),
2527 call_pp_with_no_limit_and_parseable(translate_machine1(M,(0,Codes),(_,[]))).
2528
2529 % perform a call by forcing parseable output and removing limit to set
2530 call_pp_with_no_limit_and_parseable(PP_Call) :-
2531 temporary_set_preference(translate_ids_to_parseable_format,true,CHNG),
2532 temporary_set_preference(expand_avl_upto,-1,CHNG2),
2533 call_cleanup(call(PP_Call),
2534 (reset_temporary_preference(translate_ids_to_parseable_format,CHNG),
2535 reset_temporary_preference(expand_avl_upto,CHNG2))).
2536
2537
2538 % useful if we wish to translate just a selection of sections without MACHINE/END
2539 translate_section_list(SL,Codes) :- init_machine_translation,
2540 translate_machine2(SL,SL,no_end,(0,Codes),(_,[])).
2541
2542 translate_machine1(machine(Name,Sections)) -->
2543 indent('MACHINE '), {adapt_machine_name(Name,AName)}, insertstr(AName),
2544 {init_machine_translation},
2545 translate_machine2(Sections,Sections,end).
2546 translate_machine2([],_,end) --> !, insertstr('\nEND\n').
2547 translate_machine2([],_,_) --> !, insertstr('\n').
2548 translate_machine2([P|Rest],All,End) -->
2549 translate_mpart(P,All),
2550 translate_machine2(Rest,All,End).
2551
2552 adapt_machine_name('dummy(uses)',R) :- !,R='MAIN'.
2553 adapt_machine_name(X,X).
2554
2555 :- dynamic section_header_generated/1.
2556 :- dynamic print_additional_machine_info/0.
2557 print_additional_machine_info.
2558
2559 init_machine_translation :- retractall(section_header_generated(_)).
2560
2561 % start a part of a section
2562 mpstart(Title,I) -->
2563 insertstr('\n'),insertstr(Title),
2564 indention_level(I,I2), {I2 is I+2}.
2565 % end a part of a section
2566 mpend(I) -->
2567 indention_level(_,I).
2568
2569 mpstart_section(Section,Title,AltTitle,I,In,Out) :-
2570 (\+ section_header_generated(Section)
2571 -> mpstart(Title,I,In,Out), assertz(section_header_generated(Section))
2572 ; mpstart(AltTitle,I,In,Out) /* use alternative title; section header already generated */
2573 ).
2574
2575 translate_mpart(Section/I,All) --> %{print(Section),nl},
2576 ( {I=[]} -> {true}
2577 ; translate_mpart2(Section,I,All) -> {true}
2578 ;
2579 insertstr('\nSection '),insertstr(Section),insertstr(': '),
2580 insertstr('<< pretty-print failed >>')
2581 ).
2582 translate_mpart2(deferred_sets,I,_) -->
2583 mpstart_section(sets,'SETS /* deferred */',' ; /* deferred */',P),
2584 indent_expr_l_sep(I,';'),mpend(P).
2585 translate_mpart2(enumerated_sets,_I,_) --> []. % these are now pretty printed below
2586 %mpstart('ENUMERATED SETS',P),indent_expr_l_sep(I,';'),mpend(P).
2587 translate_mpart2(enumerated_elements,I,_) --> %{print(enum_els(I)),nl},
2588 {translate_enums(I,[],Res)},
2589 mpstart_section(sets,'SETS /* enumerated */',' ; /* enumerated */',P),
2590 indent_expr_l_sep(Res,';'),mpend(P).
2591 translate_mpart2(parameters,I,_) --> mpstart('PARAMETERS',P),indent_expr_l_sep(I,','),mpend(P).
2592 translate_mpart2(internal_parameters,I,_) --> {print_additional_machine_info},!,
2593 mpstart('/* INTERNAL_PARAMETERS',P),indent_expr_l_sep(I,','),insertstr(' */'),mpend(P).
2594 translate_mpart2(internal_parameters,_I,_) --> [].
2595 translate_mpart2(abstract_variables,I,_) --> mpstart('ABSTRACT_VARIABLES',P),indent_exprs(I),mpend(P).
2596 translate_mpart2(concrete_variables,I,_) --> mpstart('CONCRETE_VARIABLES',P),indent_exprs(I),mpend(P).
2597 translate_mpart2(abstract_constants,I,_) --> mpstart('ABSTRACT_CONSTANTS',P),indent_exprs(I),mpend(P).
2598 translate_mpart2(concrete_constants,I,_) --> mpstart('CONCRETE_CONSTANTS',P),indent_exprs(I),mpend(P).
2599 translate_mpart2(promoted,I,_) --> {print_additional_machine_info},!,
2600 mpstart('/* PROMOTED OPERATIONS',P),indent_expr_l_sep(I,','),insertstr(' */'),mpend(P).
2601 translate_mpart2(promoted,_I,_) --> [].
2602 translate_mpart2(unpromoted,I,_) --> {print_additional_machine_info},!,
2603 mpstart('/* NOT PROMOTED OPERATIONS',P),indent_expr_l_sep(I,','),insertstr(' */'),mpend(P).
2604 translate_mpart2(unpromoted,_I,_) --> [].
2605 translate_mpart2(constraints,I,All) --> mpart_typing(constraints,[parameters],All,I).
2606 translate_mpart2(invariant,I,All) --> mpart_typing(invariant, [abstract_variables,concrete_variables],All,I).
2607 translate_mpart2(linking_invariant,_I,_) --> [].
2608 translate_mpart2(properties,I,All) --> mpart_typing(properties,[abstract_constants,concrete_constants],All,I).
2609 translate_mpart2(assertions,I,_) -->
2610 mpstart_spec_desc(assertions,P),
2611 %indent_expr_l_sep(I,';'),
2612 preds_over_lines(1,'@thm','; ',I),
2613 mpend(P). % TO DO:
2614 translate_mpart2(initialisation,S,_) --> mpstart_spec_desc(initialisation,P),translate_inits(S),mpend(P).
2615 translate_mpart2(definitions,Defs,_) --> {(standard_library_required(Defs,_) ; set_pref_used(Defs))},!,
2616 mpstart('DEFINITIONS',P),
2617 insertstr('\n'),
2618 {findall(Lib,standard_library_required(Defs,Lib),Libs)},
2619 insert_library_usages(Libs),
2620 translate_set_pref_defs(Defs),
2621 mpend(P),
2622 translate_other_defpart(Defs).
2623 translate_mpart2(definitions,Defs,_) --> !, translate_other_defpart(Defs).
2624 translate_mpart2(operation_bodies,Ops,_) --> mpstart_spec_desc(operations,P),translate_ops(Ops),mpend(P).
2625 translate_mpart2(used,Used,_) --> {print_additional_machine_info},!,
2626 mpstart('/* USED',P),translate_used(Used),insertstr(' */'),mpend(P).
2627 translate_mpart2(used,_Used,_) --> [].
2628 translate_mpart2(freetypes,Freetypes,_) -->
2629 mpstart('FREETYPES',P),translate_freetypes(Freetypes),mpend(P).
2630 translate_mpart2(meta,_Infos,_) --> [].
2631 translate_mpart2(operators,Operators,_) -->
2632 insertstr('\n/* Event-B operators:'), % */
2633 indention_level(I,I2), {I2 is I+2},
2634 translate_eventb_operators(Operators),
2635 indention_level(I2,I),
2636 insertstr('\n*/').
2637 translate_mpart2(values,Values,_) -->
2638 mpstart('VALUES',P),indent_expr_l_sep(Values,';'),mpend(P).
2639
2640 indent_exprs(I) --> {force_eventb_rodin_mode},!, indent_expr_l_sep(I,' '). % Event-B Camille style
2641 indent_exprs(I) --> indent_expr_l_sep(I,',').
2642
2643
2644 % Add typing predicates to a predicate
2645 mpart_typing(Title,Section,Sections,PredI) -->
2646 {mpart_typing2(Section,Sections,PredI,PredO)},
2647 ( {is_truth(PredO)} -> [] % TO DO: in animation_minor_mode(z) for INVARIANT: force adding typing predicates (translate_print_typing_infos)
2648 ;
2649 mpstart_spec_desc(Title,P),
2650 section_pred_over_lines(0,Title,PredO),
2651 mpend(P)).
2652
2653 mpstart_spec_desc(Title,P) --> {get_specification_description(Title,Atom)},!, mpstart(Atom,P).
2654 mpstart_spec_desc(Title,P) --> mpstart(Title,P).
2655
2656 mpart_typing2(Sections,AllSections,PredI,PredO) :-
2657 get_preference(translate_print_typing_infos,true),!,
2658 get_all_ids(Sections,AllSections,Ids),
2659 add_typing_predicates(Ids,PredI,PredO).
2660 mpart_typing2(_Section,_Sections,Pred,Pred).
2661
2662 get_all_ids([],_Sections,[]).
2663 get_all_ids([Section|Srest],Sections,Ids) :-
2664 memberchk(Section/Ids1,Sections),
2665 append(Ids1,Ids2,Ids),
2666 get_all_ids(Srest,Sections,Ids2).
2667
2668 add_optional_typing_predicates(Ids,In,Out) :-
2669 ( get_preference(translate_print_typing_infos,true) -> add_typing_predicates(Ids,In,Out)
2670 ; is_truth(In) -> add_typing_predicates(Ids,In,Out)
2671 ; In=Out).
2672
2673 add_normal_typing_predicates(Ids,In,Out) :- % used to call add_typing_predicates directly
2674 (add_optional_typing_predicates(Ids,In,Out) -> true
2675 ; add_internal_error('Failed: ',add_normal_typing_predicates(Ids)), In=Out).
2676
2677 add_typing_predicates([],P,P) :- !.
2678 add_typing_predicates(Ids,Pin,Pout) :-
2679 remove_already_typed_ids(Pin,Ids,UntypedIds),
2680 KeepSeq=false,
2681 generate_typing_predicates(UntypedIds,KeepSeq,Typing),
2682 conjunction_to_list(Pin,Pins),
2683 remove_duplicate_predicates(Typing,Pins,Typing2),
2684 append(Typing2,[Pin],Preds),
2685 conjunct_predicates(Preds,Pout).
2686
2687 remove_already_typed_ids(_TExpr,Ids,Ids) :-
2688 get_preference(translate_force_all_typing_infos,true),!.
2689 remove_already_typed_ids(TExpr,Ids,UntypedIds) :-
2690 get_texpr_expr(TExpr,Expr),!,
2691 remove_already_typed_ids2(Expr,Ids,UntypedIds).
2692 remove_already_typed_ids(TExpr,Ids,Res) :-
2693 add_internal_error('Not a typed expression: ',remove_already_typed_ids(TExpr,Ids,_)),
2694 Res=Ids.
2695 remove_already_typed_ids2(conjunct(A,B),Ids,UntypedIds) :- !,
2696 remove_already_typed_ids(A,Ids,I1),
2697 remove_already_typed_ids(B,I1,UntypedIds).
2698 remove_already_typed_ids2(lazy_let_pred(_,_,A),Ids,UntypedIds) :- !,
2699 remove_already_typed_ids(A,Ids,UntypedIds). % TO DO: check for variable clases with lazy_let ids ???
2700 remove_already_typed_ids2(Expr,Ids,UntypedIds) :-
2701 is_typing_predicate(Expr,Id),
2702 create_texpr(identifier(Id),_,_,TId),
2703 select(TId,Ids,UntypedIds),!.
2704 remove_already_typed_ids2(_,Ids,Ids).
2705 is_typing_predicate(member(A,_),Id) :- get_texpr_id(A,Id).
2706 is_typing_predicate(subset(A,_),Id) :- get_texpr_id(A,Id).
2707 is_typing_predicate(subset_strict(A,_),Id) :- get_texpr_id(A,Id).
2708
2709 remove_duplicate_predicates([],_Old,[]).
2710 remove_duplicate_predicates([Pred|Prest],Old,Result) :-
2711 (is_duplicate_predicate(Pred,Old) -> Result = Rest ; Result = [Pred|Rest]),
2712 remove_duplicate_predicates(Prest,Old,Rest).
2713 is_duplicate_predicate(Pred,List) :-
2714 remove_all_infos(Pred,Pattern),
2715 memberchk(Pattern,List).
2716
2717 :- use_module(typing_tools,[create_type_set/3]).
2718 generate_typing_predicates(TIds,Preds) :-
2719 generate_typing_predicates(TIds,true,Preds).
2720 generate_typing_predicates(TIds,KeepSeq,Preds) :-
2721 maplist(generate_typing_predicate(KeepSeq), TIds, Preds).
2722 generate_typing_predicate(KeepSeq,TId,Pred) :-
2723 get_texpr_type(TId,Type),
2724 remove_all_infos_and_ground(TId,TId2), % clear all infos
2725 (create_type_set(Type,KeepSeq,TSet) -> create_texpr(member(TId2,TSet),pred,[],Pred)
2726 ; TId = b(_,any,[raw]) -> is_truth(Pred) % this comes from transform_raw
2727 ; add_error(generate_typing_predicate,'Illegal type in identifier: ',Type,TId),
2728 is_truth(Pred)
2729 ).
2730
2731
2732
2733
2734 % translate enumerated constant list into enumerate set definition
2735 translate_enums([],Acc,Acc).
2736 translate_enums([EnumCst|T],Acc,Res) :- %get_texpr_id(EnumCst,Id),
2737 get_texpr_type(EnumCst,global(GlobalSet)),
2738 insert_enum_cst(Acc,EnumCst,GlobalSet,Acc2),
2739 translate_enums(T,Acc2,Res).
2740
2741 insert_enum_cst([],ID,Type,[enumerated_set_def(Type,[ID])]).
2742 insert_enum_cst([enumerated_set_def(Type,Lst)|T],ID,Type2,[enumerated_set_def(Type,Lst2)|TT]) :-
2743 (Type=Type2
2744 -> Lst2 = [ID|Lst], TT=T
2745 ; Lst2 = Lst, insert_enum_cst(T,ID,Type2,TT)
2746 ).
2747
2748 % pretty-print the initialisation section of a machine
2749 translate_inits(Inits) -->
2750 ( {is_list_simple(Inits)} ->
2751 translate_inits2(Inits)
2752 ;
2753 indention_level(I,I2),{I2 is I+2},
2754 translate_subst_begin_end(Inits),
2755 indention_level(_,I)).
2756 translate_inits2([]) --> !.
2757 translate_inits2([init(Name,Subst)|Rest]) -->
2758 indent('/* '),insertstr(Name),insertstr(': */ '),
2759 translate_subst_begin_end(Subst),
2760 translate_inits2(Rest).
2761
2762 translate_other_defpart(Defs) --> {print_additional_machine_info},!,
2763 mpstart('/* DEFINITIONS',P),translate_defs(Defs),insertstr(' */'),mpend(P).
2764 translate_other_defpart(_) --> [].
2765
2766 % pretty-print the definitions of a machine
2767 translate_defs([]) --> !.
2768 translate_defs([Def|Rest]) --> translate_def(Def),translate_defs(Rest).
2769 translate_def(definition_decl(Name,_DefType,_Pos,_Args,Expr,_Deps)) -->
2770 {dummy_def_body(Name,Expr)},!.
2771 % this is a DEFINITION from a standard library; do not show it
2772 translate_def(definition_decl(Name,DefType,_Pos,Args,Expr,_Deps)) -->
2773 {def_description(DefType,Desc)}, indent(Desc),insertstr(Name),
2774 {transform_raw_list(Args,TArgs)},
2775 translate_op_params(TArgs),
2776 ( {show_def_body(Expr)}
2777 -> insertstr(' '),{translate_in_mode(eqeq,'==',EqEqStr)}, insertstr(EqEqStr), insertstr(' '),
2778 {transform_raw(Expr,TExpr)},
2779 (translate_def_body(DefType,TExpr) -> [] ; insertstr('CANNOT PRETTY PRINT'))
2780 ; {true}
2781 ),
2782 insertstr(';').
2783 def_description(substitution,'SUBSTITUTION ').
2784 def_description(expression,'EXPRESSION ').
2785 def_description(predicate,'PREDICATE ').
2786 translate_def_body(substitution,B) --> translate_subst_begin_end(B).
2787 translate_def_body(expression,B) --> indent_expr(B).
2788 translate_def_body(predicate,B) --> indent_expr(B).
2789
2790 show_def_body(integer(_,_)).
2791 show_def_body(boolean_true(_)).
2792 show_def_body(boolean_false(_)).
2793 % show_def_body(_) % comment in to pretty print all defs
2794
2795 % check if we have a dummy definition body from a ProB Library file for external functions:
2796 dummy_def_body(Name,Expr) :-
2797 functor(Expr,F,_), (F=external_function_call ; F=external_pred_call),
2798 arg(2,Expr,Name).
2799 %external_function_declarations:external_function_library(Name,NrArgs,DefType,_),length(Args,NrArgs)
2800
2801 % utility to print definitions in JSON format for use in a VisB file:
2802 % useful when converting a B DEFINITIONS file for use in Event-B, TLA+,...
2803 :- public print_defs_as_json/0.
2804 print_defs_as_json :-
2805 findall(json([name=string(Name), value=string(BS)]), (
2806 bmachine:b_get_definition_with_pos(Name,expression,_DefPos,_Args,RawExpr,_Deps),
2807 \+ dummy_def_body(Name,RawExpr),
2808 transform_raw(RawExpr,Body),
2809 translate_subst_or_bexpr(Body,BS)
2810 ), Defs),
2811 Json = json([svg=string(''), definitions=array(Defs)]),
2812 json_write_stream(Json).
2813
2814 ?set_pref_used(Defs) :- member(definition_decl(Name,_,_,[],_,_),Defs),
2815 (is_set_pref_def_name(Name,_,_) -> true).
2816
2817 is_set_pref_def_name(Name,Pref,CurValAtom) :-
2818 atom_codes(Name,Codes),append("SET_PREF_",RestCodes,Codes),
2819 atom_codes(Pref,RestCodes),
2820 (eclipse_preference(Pref,P) -> get_preference(P,CurVal), translate_pref_val(CurVal,CurValAtom)
2821 ; deprecated_eclipse_preference(Pref,_,NewP,Mapping) -> get_preference(NewP,V), member(CurVal/V,Mapping)
2822 ; get_preference(Pref,CurVal), translate_pref_val(CurVal,CurValAtom)),
2823 translate_pref_val(CurVal,CurValAtom).
2824 translate_pref_val(true,'TRUE').
2825 translate_pref_val(false,'FALSE').
2826 translate_pref_val(Nr,NrAtom) :- number(Nr),!, number_codes(Nr,C), atom_codes(NrAtom,C).
2827 translate_pref_val(Atom,Atom) :- atom(Atom).
2828
2829 is_set_pref(definition_decl(Name,_,_Pos,[],_Expr,_Deps)) :-
2830 is_set_pref_def_name(Name,_,_).
2831 translate_set_pref_defs(Defs) -->
2832 {include(is_set_pref,Defs,SPDefs),
2833 sort(SPDefs,SortedDefs)},
2834 translate_set_pref_defs1(SortedDefs).
2835 translate_set_pref_defs1([]) --> !.
2836 translate_set_pref_defs1([Def|Rest]) -->
2837 translate_set_pref_def(Def),translate_set_pref_defs1(Rest).
2838 translate_set_pref_def(definition_decl(Name,_,_Pos,[],_Expr,_Deps)) -->
2839 {is_set_pref_def_name(Name,_Pref,CurValAtom)},!,
2840 insertstr(' '),insertstr(Name),
2841 insertstr(' '),
2842 {translate_in_mode(eqeq,'==',EqEqStr)}, insertstr(EqEqStr), insertstr(' '),
2843 insertstr(CurValAtom), % pretty print current value; Expr could be a more complicated non-atomic expression
2844 insertstr(';\n').
2845 translate_set_pref_def(_) --> [].
2846
2847 standard_library_required(Defs,Library) :-
2848 ? member(Decl,Defs),
2849 definition_decl_from_library(Decl,Library).
2850
2851 % TODO: we could also look in the list of loaded files and search for standard libraries
2852 definition_decl_from_library(definition_decl(printf,predicate,_,[_,_],_,_Deps),'LibraryIO.def').
2853 definition_decl_from_library(definition_decl('STRING_IS_DECIMAL',predicate,_,[_],_,_Deps),'LibraryStrings.def').
2854 definition_decl_from_library(definition_decl('SHA_HASH',expression,_,[_],_,_Deps),'LibraryHash.def').
2855 definition_decl_from_library(definition_decl('CHOOSE',expression,_,[_],_,_Deps),'CHOOSE.def').
2856 definition_decl_from_library(definition_decl('SCCS',expression,_,[_],_,_Deps),'SCCS.def').
2857 definition_decl_from_library(definition_decl('SORT',expression,_,[_],_,_Deps),'SORT.def').
2858 definition_decl_from_library(definition_decl('random_element',expression,_,[_],_,_Deps),'LibraryRandom.def').
2859 definition_decl_from_library(definition_decl('SIN',expression,_,[_],_,_Deps),'LibraryMath.def').
2860 definition_decl_from_library(definition_decl('RMUL',expression,_,[_,_],_,_Deps),'LibraryReals.def').
2861 definition_decl_from_library(definition_decl('REGEX_MATCH',predicate,_,[_,_],_,_Deps),'LibraryRegex.def').
2862 definition_decl_from_library(definition_decl('ASSERT_EXPR',expression,_,[_,_,_],_,_Deps),'LibraryProB.def').
2863 definition_decl_from_library(definition_decl('svg_points',expression,_,[_],_,_Deps),'LibrarySVG.def').
2864 definition_decl_from_library(definition_decl('FULL_FILES',expression,_,[_],_,_Deps),'LibraryFiles.def').
2865 definition_decl_from_library(definition_decl('READ_XML_FROM_STRING',expression,_,[_],_,_Deps),'LibraryXML.def').
2866 definition_decl_from_library(definition_decl('READ_CSV',expression,_,[_],_,_Deps),'LibraryCSV.def').
2867
2868 insert_library_usages([]) --> [].
2869 insert_library_usages([Library|T]) -->
2870 insertstr(' "'),insertstr(Library),insertstr('";\n'), % insert inclusion of ProB standard library
2871 insert_library_usages(T).
2872
2873 % ------------- RAW EXPRESSIONS
2874
2875 % try and print raw machine term or parts thereof (e.g. sections)
2876 print_raw_machine_terms(Var) :- var(Var), !,print('VAR !!'),nl.
2877 print_raw_machine_terms([]) :- !.
2878 print_raw_machine_terms([H|T]) :- !,
2879 print_raw_machine_terms(H), print(' '),
2880 print_raw_machine_terms(T).
2881 print_raw_machine_terms(Term) :- raw_machine_term(Term,String,Sub),!,
2882 format('~n~w ',[String]),
2883 print_raw_machine_terms(Sub),nl.
2884 print_raw_machine_terms(expression_definition(A,B,C,D)) :- !,
2885 print_raw_machine_terms(predicate_definition(A,B,C,D)).
2886 print_raw_machine_terms(substitution_definition(A,B,C,D)) :- !,
2887 print_raw_machine_terms(predicate_definition(A,B,C,D)).
2888 print_raw_machine_terms(predicate_definition(_,Name,Paras,RHS)) :-
2889 Paras==[],!,
2890 format('~n ~w == ',[Name]),
2891 print_raw_machine_terms(RHS),nl.
2892 print_raw_machine_terms(predicate_definition(_,Name,Paras,RHS)) :- !,
2893 format('~n ~w(',[Name]),
2894 print_raw_machine_terms_sep(Paras,','),
2895 format(') == ',[]),
2896 print_raw_machine_terms(RHS),nl.
2897 print_raw_machine_terms(operation(_,Name,Return,Paras,RHS)) :- !,
2898 format('~n ',[]),
2899 (Return=[] -> true
2900 ; print_raw_machine_terms_sep(Return,','),
2901 format(' <-- ',[])
2902 ),
2903 print_raw_machine_terms(Name),
2904 (Paras=[] -> true
2905 ; format(' (',[]),
2906 print_raw_machine_terms_sep(Paras,','),
2907 format(')',[])
2908 ),
2909 format(' = ',[]),
2910 print_raw_machine_terms(RHS),nl.
2911 print_raw_machine_terms(Term) :- print_raw_bexpr(Term).
2912
2913
2914 print_raw_machine_terms_sep([],_) :- !.
2915 print_raw_machine_terms_sep([H],_) :- !,
2916 print_raw_machine_terms(H).
2917 print_raw_machine_terms_sep([H|T],Sep) :- !,
2918 print_raw_machine_terms(H),print(Sep),print_raw_machine_terms_sep(T,Sep).
2919
2920 raw_machine_term(machine(M),'',M).
2921 raw_machine_term(generated(_,M),'',M).
2922 raw_machine_term(machine_header(_,Name,_Params),Name,[]). % TO DO: treat Params
2923 raw_machine_term(abstract_machine(_,_,Header,M),'MACHINE',[Header,M]).
2924 raw_machine_term(properties(_,P),'PROPERTIES',P).
2925 raw_machine_term(operations(_,P),'OPERATIONS',P).
2926 raw_machine_term(definitions(_,P),'DEFINITIONS',P).
2927 raw_machine_term(constants(_,P),'CONSTANTS',P).
2928 raw_machine_term(variables(_,P),'VARIABLES',P).
2929 raw_machine_term(invariant(_,P),'INVARIANT',P).
2930 raw_machine_term(assertions(_,P),'ASSERTIONS',P).
2931 raw_machine_term(constraints(_,P),'CONSTRAINTS',P).
2932 raw_machine_term(sets(_,P),'SETS',P).
2933 raw_machine_term(deferred_set(_,P),P,[]). % TO DO: enumerated_set ...
2934 %raw_machine_term(identifier(_,P),P,[]).
2935
2936 l_print_raw_bexpr([]).
2937 l_print_raw_bexpr([Raw|T]) :- write(' '),
2938 print_raw_bexpr(Raw),nl, l_print_raw_bexpr(T).
2939
2940 print_raw_bexpr(Raw) :- % a tool (not perfect) to print raw ASTs
2941 transform_raw(Raw,TExpr),!,
2942 print_bexpr_or_subst(TExpr).
2943
2944 translate_raw_bexpr_with_limit(Raw,Limit,TS) :- transform_raw(Raw,TExpr),
2945 translate_subst_or_bexpr_with_limit(TExpr,Limit,TS).
2946
2947 transform_raw_list(Var,Res) :- var(Var),!,
2948 add_internal_error('Var raw expression list:',transform_raw_list(Var,Res)),
2949 Res= [b(identifier('$$VARIABLE_LIST$$'),any,[raw])].
2950 transform_raw_list(Args,TArgs) :- maplist(transform_raw,Args,TArgs).
2951
2952
2953 transform_raw(Var,Res) :- %print(raw(Var)),nl,
2954 var(Var), !, add_internal_error('Var raw expression:',transform_raw(Var,Res)),
2955 Res= b(identifier('$$VARIABLE$$'),any,[raw]).
2956 transform_raw(precondition(_,Pre,Body),Res) :- !, Res= b(precondition(TP,TB),subst,[raw]),
2957 transform_raw(Pre,TP),
2958 transform_raw(Body,TB).
2959 transform_raw(typeof(_,E,_Type),Res) :- !, transform_raw(E,Res). % remove typeof operator; TODO: transform
2960 transform_raw(identifier(_,M),Res) :- !, Res= b(identifier(M),any,[raw]).
2961 transform_raw(integer(_,M),Res) :- !, Res= b(integer(M),integer,[raw]).
2962 % rules from btype_rewrite2:
2963 transform_raw(integer_set(_),Res) :- !, generate_typed_int_set('INTEGER',Res).
2964 transform_raw(natural_set(_),Res) :- !, generate_typed_int_set('NATURAL',Res).
2965 transform_raw(natural1_set(_),Res) :- !, generate_typed_int_set('NATURAL1',Res).
2966 transform_raw(nat_set(_),Res) :- !, generate_typed_int_set('NAT',Res).
2967 transform_raw(nat1_set(_),Res) :- !, generate_typed_int_set('NAT1',Res).
2968 transform_raw(int_set(_),Res) :- !, generate_typed_int_set('INT',Res).
2969 transform_raw(let_expression(_,_Ids,Eq,Body),Res) :- !,
2970 transform_raw(conjunct(_,Eq,Body),Res). % TO DO: fix and generate let_expression(Ids,ListofExprs,Body)
2971 transform_raw(let_predicate(_,_Ids,Eq,Body),Res) :- !,
2972 transform_raw(conjunct(_,Eq,Body),Res). % ditto
2973 transform_raw(forall(_,Ids,Body),Res) :- !,
2974 (Body=implication(_,LHS,RHS) -> true ; LHS=truth,RHS=Body),
2975 transform_raw(forall(_,Ids,LHS,RHS),Res).
2976 transform_raw(record_field(_,Rec,identifier(_,Field)),Res) :- !, Res = b(record_field(TRec,Field),any,[]),
2977 transform_raw(Rec,TRec).
2978 transform_raw(rec_entry(_,identifier(_,Field),Rec),Res) :- !, Res = field(Field,TRec),
2979 transform_raw(Rec,TRec).
2980 transform_raw(conjunct(_,List),Res) :- !,
2981 transform_raw_list_to_conjunct(List,Res). % sometimes conjunct/1 with list is used (e.g., .eventb files)
2982 transform_raw(couple(_,L),Res) :- !, transform_raw_list_to_couple(L,Res). % couples are represented by lists
2983 transform_raw(extended_expr(Pos,Op,L,_TypeParas),Res) :- !,
2984 (L=[] -> transform_raw(identifier(none,Op),Res) % no arguments
2985 ; transform_raw(function(Pos,identifier(none,Op),L),Res)).
2986 transform_raw(extended_pred(Pos,Op,L,_TypeParas),Res) :- !,
2987 transform_raw(function(Pos,identifier(none,Op),L),Res). % not of correct type pred, but seems to work
2988 transform_raw(external_function_call_auto(Pos,Name,Para),Res) :- !,
2989 transform_raw(external_function_call(Pos,Name,Para),Res). % we assume expr rather than pred and hope for the best
2990 transform_raw(function(_,F,L),Res) :- !, transform_raw(F,TF),
2991 Res = b(function(TF,Args),any,[]),
2992 transform_raw_list_to_couple(L,Args). % args are represented by lists
2993 transform_raw(Atom,Res) :- atomic(Atom),!,Res=Atom.
2994 transform_raw([H|T],Res) :- !, maplist(transform_raw,[H|T],Res).
2995 transform_raw(Symbolic,Res) :- symbolic_raw(Symbolic,Body),!,
2996 transform_raw(Body,Res).
2997 transform_raw(OtherOp,b(Res,Type,[])) :- OtherOp =..[F,_Pos|Rest],
2998 maplist(transform_raw,Rest,TRest),
2999 (get_type(F,FT) -> Type=FT ; Type=any),
3000 Res =.. [F|TRest].
3001 transform_raw_list_to_couple([R],Res) :- !, transform_raw(R,Res).
3002 transform_raw_list_to_couple([R1|T],Res) :- !, Res=b(couple(TR1,TT),any,[]),
3003 transform_raw(R1,TR1),transform_raw_list_to_couple(T,TT).
3004 transform_raw_list_to_conjunct([R],Res) :- !, transform_raw(R,Res).
3005 transform_raw_list_to_conjunct([R1|T],Res) :- !, Res=b(conjunct(TR1,TT),pred,[]),
3006 transform_raw(R1,TR1),transform_raw_list_to_conjunct(T,TT).
3007 generate_typed_int_set(Name,b(integer_set(Name),set(integer),[])).
3008 get_type(conjunct,pred).
3009 get_type(disjunct,pred).
3010 get_type(implication,pred).
3011 get_type(equivalence,pred).
3012 get_type(member,pred).
3013 get_type(equal,pred).
3014 get_type(not_equal,pred).
3015 get_type(not_member,pred).
3016 get_type(subset,pred).
3017 get_type(not_subset,pred).
3018
3019 symbolic_raw(symbolic_composition(A,B,C),composition(A,B,C)).
3020 symbolic_raw(symbolic_comprehension_set(A,B,C),comprehension_set(A,B,C)).
3021 symbolic_raw(symbolic_event_b_comprehension_set(A,B,C,D),eventb_comprehension_set(A,B,C,D)).
3022 symbolic_raw(symbolic_lambda(A,B,C,D),lambda(A,B,C,D)).
3023 symbolic_raw(symbolic_quantified_union(A,B,C,D),quantified_union(A,B,C,D)).
3024
3025 % -------------
3026
3027
3028 % pretty-print the operations of a machine
3029 translate_ops([]) --> !.
3030 translate_ops([Op|Rest]) -->
3031 translate_op(Op),
3032 ({Rest=[]} -> {true}; insertstr(';'),indent),
3033 translate_ops(Rest).
3034 translate_op(Op) -->
3035 { get_texpr_expr(Op,operation(Id,Res,Params,Body)) },
3036 translate_operation(Id,Res,Params,Body).
3037 translate_operation(Id,Res,Params,Body) -->
3038 indent,translate_op_results(Res),
3039 pp_expr_indent(Id),
3040 translate_op_params(Params),
3041 insertstr(' = '),
3042 indention_level(I1,I2),{I2 is I1+2,type_infos_in_subst(Params,Body,Body2)},
3043 translate_subst_begin_end(Body2),
3044 pp_description_pragma_of(Body2),
3045 indention_level(_,I1).
3046 translate_op_results([]) --> !.
3047 translate_op_results(Ids) --> pp_expr_indent_l(Ids), insertstr(' <-- ').
3048 translate_op_params([]) --> !.
3049 translate_op_params(Ids) --> insertstr('('),pp_expr_indent_l(Ids), insertstr(')').
3050
3051 translate_subst_begin_end(TSubst) -->
3052 {get_texpr_expr(TSubst,Subst),subst_needs_begin_end(Subst),
3053 create_texpr(block(TSubst),subst,[],Block)},!,
3054 translate_subst(Block).
3055 translate_subst_begin_end(Subst) -->
3056 translate_subst(Subst).
3057
3058 subst_needs_begin_end(assign(_,_)).
3059 subst_needs_begin_end(assign_single_id(_,_)).
3060 subst_needs_begin_end(parallel(_)).
3061 subst_needs_begin_end(sequence(_)).
3062 subst_needs_begin_end(operation_call(_,_,_)).
3063
3064 type_infos_in_subst([],Subst,Subst) :- !.
3065 type_infos_in_subst(Ids,SubstIn,SubstOut) :-
3066 get_preference(translate_print_typing_infos,true),!,
3067 type_infos_in_subst2(Ids,SubstIn,SubstOut).
3068 type_infos_in_subst(_Ids,Subst,Subst).
3069 type_infos_in_subst2(Ids,SubstIn,SubstOut) :-
3070 get_texpr_expr(SubstIn,precondition(P1,S)),!,
3071 get_texpr_info(SubstIn,Info),
3072 create_texpr(precondition(P2,S),pred,Info,SubstOut),
3073 add_typing_predicates(Ids,P1,P2).
3074 type_infos_in_subst2(Ids,SubstIn,SubstOut) :-
3075 create_texpr(precondition(P,SubstIn),pred,[],SubstOut),
3076 generate_typing_predicates(Ids,Typing),
3077 conjunct_predicates(Typing,P).
3078
3079
3080
3081
3082
3083 % pretty-print the internal section about included and used machines
3084 translate_used([]) --> !.
3085 translate_used([Used|Rest]) -->
3086 translate_used2(Used),
3087 translate_used(Rest).
3088 translate_used2(includeduse(Name,Id,NewTExpr)) -->
3089 indent,pp_expr_indent(NewTExpr),
3090 insertstr(' --> '), insertstr(Name), insertstr(':'), insertstr(Id).
3091
3092 % pretty-print the internal information about freetypes
3093 translate_freetypes([]) --> !.
3094 translate_freetypes([Freetype|Frest]) -->
3095 translate_freetype(Freetype),
3096 translate_freetypes(Frest).
3097 translate_freetype(freetype(Name,Cases)) -->
3098 {pretty_freetype(Name,PName)},
3099 indent(PName),insertstr('= '),
3100 indention_level(I1,I2),{I2 is I1+2},
3101 translate_freetype_cases(Cases),
3102 indention_level(_,I1).
3103 translate_freetype_cases([]) --> !.
3104 translate_freetype_cases([case(Name,Type)|Rest]) --> {nonvar(Type),Type=constant(_)},
3105 !,indent(Name),insert_comma(Rest),
3106 translate_freetype_cases(Rest).
3107 translate_freetype_cases([case(Name,Type)|Rest]) -->
3108 {pretty_type(Type,PT)},
3109 indent(Name),
3110 insertstr('('),insertstr(PT),insertstr(')'),
3111 insert_comma(Rest),
3112 translate_freetype_cases(Rest).
3113
3114 insert_comma([]) --> [].
3115 insert_comma([_|_]) --> insertstr(',').
3116
3117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3118 % substitutions
3119
3120 translate_subst_or_bexpr(Stmt,String) :- get_texpr_type(Stmt,subst),!,
3121 translate_substitution(Stmt,String).
3122 translate_subst_or_bexpr(ExprOrPred,String) :-
3123 translate_bexpression(ExprOrPred,String).
3124
3125 translate_subst_or_bexpr_with_limit(Stmt,Limit,String) :-
3126 translate_subst_or_bexpr_with_limit(Stmt,Limit,report_errors,String).
3127 translate_subst_or_bexpr_with_limit(Stmt,_Limit,ReportErrors,String) :- get_texpr_type(Stmt,subst),!,
3128 translate_substitution(Stmt,String,ReportErrors). % TO DO: use limit
3129 translate_subst_or_bexpr_with_limit(ExprOrPred,Limit,ReportErrors,String) :-
3130 translate_bexpression_with_limit(ExprOrPred,Limit,ReportErrors,String).
3131
3132 print_subst(Stmt) :- translate_substitution(Stmt,T), print(T).
3133 translate_substitution(Stmt,String) :- translate_substitution(Stmt,String,report_errors).
3134 translate_substitution(Stmt,String,_) :-
3135 translate_subst_with_indention(Stmt,0,Codes,[]),
3136 (Codes = [10|C] -> true ; Codes=[13|C] -> true ; Codes=C), % peel off leading newline
3137 atom_codes_with_limit(String, C),!.
3138 translate_substitution(Stmt,String,report_errors) :-
3139 add_error(translate_substitution,'Could not translate substitution: ',Stmt),
3140 String='???'.
3141
3142 translate_subst_with_indention(TS,Indention,I,O) :-
3143 translate_subst(TS,(Indention,I),(_,O)).
3144 translate_subst_with_indention_and_label(TS,Indention,I,O) :-
3145 translate_subst_with_label(TS,(Indention,I),(_,O)).
3146
3147 translate_subst(TS) -->
3148 ( {get_texpr_expr(TS,S)} ->
3149 translate_subst2(S)
3150 ; translate_subst2(TS)).
3151
3152 translate_subst_with_label(TS) -->
3153 ( {get_texpr_expr(TS,S)} ->
3154 indent_rodin_label(TS), % pretty print substitution labels
3155 translate_subst2(S)
3156 ; translate_subst2(TS)).
3157
3158 % will print (first) rodin or pragma label indendent
3159 :- public indent_rodin_label/3.
3160 indent_rodin_label(_TExpr) --> {get_preference(translate_suppress_rodin_positions_flag,true),!}.
3161 indent_rodin_label(_TExpr) --> {get_preference(bugly_pp_scrambling,true),!}.
3162 indent_rodin_label(TExpr) --> {get_texpr_labels(TExpr,Names)},!, % note: this will only get the first label
3163 indent('/* @'),pp_ids_indent(Names),insertstr('*/ '). % this Camille syntax cannot be read back in by B parser
3164 indent_rodin_label(_TExpr) --> [].
3165
3166 pp_ids_indent([]) --> !, [].
3167 pp_ids_indent([ID]) --> !,pp_expr_indent(identifier(ID)).
3168 pp_ids_indent([ID|T]) --> !,pp_expr_indent(identifier(ID)), insertstr(' '),pp_ids_indent(T).
3169 pp_ids_indent(X) --> {add_error(pp_ids_indent,'Not a list of atoms: ',pp_ids_indent(X))}.
3170
3171 translate_subst2(Var) --> {var(Var)}, !, "_", {add_warning(translate_subst,'Variable subst:',Var)}.
3172 translate_subst2(skip) -->
3173 indent(skip).
3174 translate_subst2(operation(Id,Res,Params,Body)) --> translate_operation(Id,Res,Params,Body). % not really a substition that can appear normally
3175 translate_subst2(precondition(P,S)) -->
3176 indent('PRE '), pred_over_lines(2,'@grd',P), indent('THEN'), insert_subst(S), indent('END').
3177 translate_subst2(assertion(P,S)) -->
3178 indent('ASSERT '), pp_expr_indent(P), indent('THEN'), insert_subst(S), indent('END').
3179 translate_subst2(witness_then(P,S)) -->
3180 indent('WITNESS '), pp_expr_indent(P), indent('THEN'), insert_subst(S), indent('END').
3181 translate_subst2(block(S)) -->
3182 indent('BEGIN'), insert_subst(S), indent('END').
3183 translate_subst2(assign([L],[R])) --> !,
3184 indent,pp_expr_indent(L),insertstr(' := '),pp_expr_indent(R).
3185 translate_subst2(assign(L,R)) -->
3186 ? {(member(b(E,_,_),R), can_indent_expr(E)
3187 -> maplist(create_assign,L,R,ParAssigns))},!, % split into parallel assignments so that we can indent
3188 translate_subst2(parallel(ParAssigns)).
3189 translate_subst2(assign(L,R)) -->
3190 indent,pp_expr_indent_l(L),insertstr(' := '),pp_expr_indent_l(R).
3191 translate_subst2(assign_single_id(L,R)) -->
3192 translate_subst2(assign([L],[R])).
3193 translate_subst2(becomes_element_of(L,R)) -->
3194 indent,pp_expr_indent_l(L),insertstr(' :: '),pp_expr_indent(R).
3195 translate_subst2(becomes_such(L,R)) -->
3196 indent,pp_expr_indent_l(L),insertstr(' : '), insertstr('('),
3197 { add_optional_typing_predicates(L,R,R1) },
3198 pp_expr_indent(R1), insertstr(')').
3199 translate_subst2(evb2_becomes_such(L,R)) --> translate_subst2(becomes_such(L,R)).
3200 translate_subst2(if([Elsif|Rest])) -->
3201 { get_if_elsif(Elsif,P,S) },
3202 indent('IF '), pp_expr_indent(P), insertstr(' THEN'),
3203 insert_subst(S),
3204 translate_ifs(Rest).
3205 translate_subst2(if_elsif(P,S)) --> % not a legal top-level construct; but can be called in b_portray_hook
3206 indent('IF '), pp_expr_indent(P), insertstr(' THEN'),
3207 insert_subst(S),
3208 indent('END').
3209 translate_subst2(choice(Ss)) --> indent(' CHOICE'),
3210 split_over_lines(Ss,'OR'),
3211 indent('END'). % indentation seems too far
3212 translate_subst2(parallel(Ss)) -->
3213 split_over_lines(Ss,'||').
3214 translate_subst2(init_statement(S)) --> insert_subst(S).
3215 translate_subst2(sequence(Ss)) -->
3216 split_over_lines(Ss,';').
3217 translate_subst2(operation_call(Id,Rs,As)) -->
3218 indent,translate_op_results(Rs),
3219 pp_expr_indent(Id),
3220 translate_op_params(As).
3221 translate_subst2(identifier(op(Id))) --> % shouldn't normally appear
3222 indent,pp_expr_indent(identifier(Id)).
3223 translate_subst2(external_subst_call(Symbol,Args)) -->
3224 indent,
3225 pp_expr_indent(identifier(Symbol)),
3226 translate_op_params(Args).
3227 translate_subst2(any(Ids,Pred,Subst)) -->
3228 indent('ANY '), pp_expr_indent_l(Ids),
3229 indent('WHERE '),
3230 {add_optional_typing_predicates(Ids,Pred,Pred2)},
3231 pred_over_lines(2,'@grd',Pred2), indent('THEN'),
3232 insert_subst(Subst),
3233 indent('END').
3234 translate_subst2(select(Whens)) -->
3235 translate_whens(Whens,'SELECT '),
3236 indent('END').
3237 translate_subst2(select_when(Cond,Then)) --> % not a legal top-level construct; but can be called in b_portray_hook
3238 indent('WHEN'),
3239 pp_expr_indent(Cond),
3240 indent('THEN'),
3241 insert_subst(Then),
3242 indent('END').
3243 translate_subst2(select(Whens,Else)) -->
3244 translate_whens(Whens,'SELECT '),
3245 indent('ELSE'), insert_subst(Else),
3246 indent('END').
3247 translate_subst2(var(Ids,S)) -->
3248 indent('VAR '),
3249 pp_expr_indent_l(Ids),
3250 indent('IN'),insert_subst(S),
3251 indent('END').
3252 translate_subst2(let(Ids,P,S)) -->
3253 indent('LET '),
3254 pp_expr_indent_l(Ids),
3255 insertstr(' BE '), pp_expr_indent(P),
3256 indent('IN'), insert_subst(S),
3257 indent('END').
3258 translate_subst2(lazy_let_subst(TID,P,S)) -->
3259 indent('LET '),
3260 pp_expr_indent_l([TID]),
3261 insertstr(' BE '), pp_expr_indent(P), % could be expr or pred
3262 indent('IN'), insert_subst(S),
3263 indent('END').
3264 translate_subst2(case(Expression,Cases,ELSE)) -->
3265 % CASE E OF EITHER m THEN G OR n THEN H ... ELSE I END END
3266 indent('CASE '),
3267 pp_expr_indent(Expression), insertstr(' OF'),
3268 indent('EITHER '), translate_cases(Cases),
3269 indent('ELSE '), insert_subst(ELSE), % we could drop this if ELSE is skip ?
3270 indent('END END').
3271 translate_subst2(while(Pred,Subst,Inv,Var)) -->
3272 indent('WHILE '), pp_expr_indent(Pred),
3273 indent('DO'),insert_subst(Subst),
3274 indent('INVARIANT '),pp_expr_indent(Inv),
3275 indent('VARIANT '),pp_expr_indent(Var),
3276 indent('END').
3277 translate_subst2(while1(Pred,Subst,Inv,Var)) -->
3278 indent('WHILE /* 1 */ '), pp_expr_indent(Pred),
3279 indent('DO'),insert_subst(Subst),
3280 indent('INVARIANT '),pp_expr_indent(Inv),
3281 indent('VARIANT '),pp_expr_indent(Var),
3282 indent('END').
3283 translate_subst2(rlevent(Id,Section,Status,Parameters,Guard,Theorems,Actions,VWitnesses,PWitnesses,_Unmod,Refines)) -->
3284 indent,
3285 insert_status(Status),
3286 insertstr('EVENT '),
3287 ({Id = 'INITIALISATION'}
3288 -> [] % avoid BLexer error in ProB2-UI, BLexerException: Invalid combination of symbols: 'INITIALISATION' and '='.
3289 ; insertstr(Id), insertstr(' = ')),
3290 insertstr('/'), insertstr('* of machine '),
3291 insertstr(Section),insertstr(' */'),
3292 insert_variant(Status),
3293 ( {Parameters=[], get_texpr_expr(Guard,truth)} ->
3294 {NoGuard=true} % indent('BEGIN ')
3295 ; {Parameters=[]} ->
3296 indent('WHEN '),
3297 pred_over_lines(2,'@grd',Guard)
3298 ;
3299 indent('ANY '),pp_expr_indent_l(Parameters),
3300 indent('WHERE '),
3301 pred_over_lines(2,'@grd',Guard)
3302 ),
3303 ( {VWitnesses=[],PWitnesses=[]} ->
3304 []
3305 ;
3306 {append(VWitnesses,PWitnesses,Witnesses)},
3307 indent('WITH '),pp_witness_l(Witnesses)
3308 ),
3309 {( Actions=[] ->
3310 create_texpr(skip,subst,[],Subst)
3311 ;
3312 create_texpr(parallel(Actions),subst,[],Subst)
3313 )},
3314 ( {Theorems=[]} -> {true}
3315 ;
3316 indent('THEOREMS '),
3317 preds_over_lines(2,'@thm',Theorems)
3318 ),
3319 ({NoGuard==true}
3320 -> indent('BEGIN ') % avoid BLexer errors in ProB2-UI Syntax highlighting
3321 ; indent('THEN ')
3322 ),
3323 insert_subst(Subst),
3324 pp_refines_l(Refines,Id),
3325 indent('END').
3326
3327 % translate cases of a CASE statement
3328 translate_cases([]) --> !,[].
3329 translate_cases([CaseOr|T]) -->
3330 {get_texpr_expr(CaseOr,case_or(Exprs,Subst))},!,
3331 pp_expr_indent_l(Exprs),
3332 insertstr(' THEN '),
3333 insert_subst(Subst),
3334 ({T==[]} -> {true}
3335 ; indent('OR '), translate_cases(T)).
3336 translate_cases(L) -->
3337 {add_internal_error('Cannot translate CASE list: ',translate_cases(L,_,_))}.
3338
3339 insert_status(TStatus) -->
3340 {get_texpr_expr(TStatus,Status),
3341 status_string(Status,String)},
3342 insertstr(String).
3343 status_string(ordinary,'').
3344 status_string(anticipated(_),'ANTICIPATED ').
3345 status_string(convergent(_),'CONVERGENT ').
3346
3347 insert_variant(TStatus) -->
3348 {get_texpr_expr(TStatus,Status)},
3349 insert_variant2(Status).
3350 insert_variant2(ordinary) --> !.
3351 insert_variant2(anticipated(Variant)) --> insert_variant3(Variant).
3352 insert_variant2(convergent(Variant)) --> insert_variant3(Variant).
3353 insert_variant3(Variant) -->
3354 indent('USING VARIANT '),pp_expr_indent(Variant).
3355
3356 pp_refines_l([],_) --> [].
3357 pp_refines_l([Ref|Rest],Id) -->
3358 pp_refines(Ref,Id),pp_refines_l(Rest,Id).
3359 pp_refines(Refined,_Id) -->
3360 % indent(Id), insertstr(' REFINES '),
3361 indent('REFINES '),
3362 insert_subst(Refined).
3363
3364 pp_witness_l([]) --> [].
3365 pp_witness_l([Witness|WRest]) -->
3366 pp_witness(Witness),pp_witness_l(WRest).
3367 pp_witness(Expr) -->
3368 indention_level(I1,I2),
3369 {get_texpr_expr(Expr,witness(Id,Pred)),
3370 I2 is I1+2},
3371 indent, pp_expr_indent(Id), insertstr(': '),
3372 pp_expr_indent(Pred),
3373 pp_description_pragma_of(Pred),
3374 indention_level(_,I1).
3375
3376
3377 translate_whens([],_) --> !.
3378 translate_whens([When|Rest],T) -->
3379 {get_texpr_expr(When,select_when(P,S))},!,
3380 indent(T), pred_over_lines(2,'@grd',P),
3381 indent('THEN '),
3382 insert_subst(S),
3383 translate_whens(Rest,'WHEN ').
3384 translate_whens(L,_) -->
3385 {add_internal_error('Cannot translate WHEN: ',translate_whens(L,_,_,_))}.
3386
3387
3388
3389 create_assign(LHS,RHS,b(assign([LHS],[RHS]),subst,[])).
3390
3391 split_over_lines([],_) --> !.
3392 split_over_lines([S|Rest],Symbol) --> !,
3393 indention_level(I1,I2),{atom_codes(Symbol,X),length(X,N),I2 is I1+N+1},
3394 translate_subst_check(S),
3395 split_over_lines2(Rest,Symbol,I1,I2).
3396 split_over_lines(S,Symbol) --> {add_error(split_over_lines,'Illegal argument: ',Symbol:S)}.
3397
3398 split_over_lines2([],_,_,_) --> !.
3399 split_over_lines2([S|Rest],Symbol,I1,I2) -->
3400 indention_level(_,I1), indent(Symbol),
3401 indention_level(_,I2), translate_subst(S),
3402 split_over_lines2(Rest,Symbol,I1,I2).
3403
3404 % print a predicate over several lines, at most one conjunct per line
3405 % N is the increment that should be added to the indentation
3406 %pred_over_lines(N,Pred) --> pred_over_lines(N,'@pred',Pred).
3407 pred_over_lines(N,Lbl,Pred) -->
3408 {conjunction_to_list(Pred,List)},
3409 preds_over_lines(N,Lbl,List).
3410 section_pred_over_lines(N,Title,Pred) -->
3411 ({get_eventb_default_label(Title,Lbl)} -> [] ; {Lbl='@pred'}),
3412 pred_over_lines(N,Lbl,Pred).
3413 get_eventb_default_label(properties,'@axm').
3414 get_eventb_default_label(assertions,'@thm').
3415
3416 % print a list of predicates over several lines, at most one conjunct per line
3417 preds_over_lines(N,Lbl,Preds) --> preds_over_lines(N,Lbl,'& ',Preds).
3418 % preds_over_lines(IndentationIncrease,EventBDefaultLabel,ClassicalBSeperator,ListOfPredicates)
3419 preds_over_lines(N,Lbl,Sep,Preds) -->
3420 indention_level(I1,I2),{I2 is I1+N},
3421 preds_over_lines1(Preds,Lbl,1,Sep),
3422 indention_level(_,I1).
3423 preds_over_lines1([],Lbl,Nr,Sep) --> !,
3424 preds_over_lines1([b(truth,pred,[])],Lbl,Nr,Sep).
3425 preds_over_lines1([H|T],Lbl,Nr,Sep) -->
3426 indent(' '), pp_label(Lbl,Nr),
3427 %({T==[]} -> pp_expr_indent(H) ; pp_expr_m_indent(H,40)),
3428 ({T==[]} -> pp_pred_nested(H,conjunct,0) ; pp_pred_nested(H,conjunct,40)),
3429 pp_description_pragma_of(H),
3430 {N1 is Nr+1},
3431 preds_over_lines2(T,Lbl,N1,Sep).
3432 preds_over_lines2([],_,_,_Sep) --> !.
3433 preds_over_lines2([E|Rest],Lbl,Nr,Sep) -->
3434 ({force_eventb_rodin_mode} -> indent(' '), pp_label(Lbl,Nr) ; indent(Sep)),
3435 pp_pred_nested(E,conjunct,40),
3436 pp_description_pragma_of(E),
3437 {N1 is Nr+1},
3438 preds_over_lines2(Rest,Lbl,N1,Sep).
3439
3440 % print event-b label for Rodin/Camille:
3441 pp_label(Lbl,Nr) -->
3442 ({force_eventb_rodin_mode}
3443 -> {atom_codes(Lbl,C1), number_codes(Nr,NC), append(C1,NC,AC), atom_codes(A,AC)},
3444 pp_atom_indent(A), pp_atom_indent(' ')
3445 ; []).
3446
3447 % a version of nested_print_bexpr / nbp that does not directly print to stream conjunct
3448 pp_pred_nested(TExpr,CurrentType,_) --> {TExpr = b(E,pred,_)},
3449 {get_binary_connective(E,NewType,Ascii,LHS,RHS), binary_infix(NewType,Ascii,Prio,left)},
3450 !,
3451 pp_rodin_label_indent(TExpr), % print any label
3452 inc_lvl(CurrentType,NewType),
3453 pp_pred_nested(LHS,NewType,Prio),
3454 {translate_in_mode(NewType,Ascii,Symbol)},
3455 indent(' '),pp_atom_indent(Symbol),
3456 indent(' '),
3457 {(is_associative(NewType) -> NewTypeR=NewType % no need for parentheses if same operator on right
3458 ; NewTypeR=right(NewType))},
3459 pp_pred_nested(RHS,NewTypeR,Prio),
3460 dec_lvl(CurrentType,NewType).
3461 pp_pred_nested(TExpr,_,_) --> {is_nontrivial_negation(TExpr,NExpr,InnerType,Prio)},
3462 !,
3463 pp_rodin_label_indent(TExpr), % print any label
3464 {translate_in_mode(negation,'not',Symbol)},
3465 pp_atom_indent(Symbol),
3466 inc_lvl(other,negation), % always need parentheses for negation
3467 pp_pred_nested(NExpr,InnerType,Prio),
3468 dec_lvl(other,negation).
3469 pp_pred_nested(TExpr,_,_) --> {TExpr = b(exists(Ids,RHS),pred,_)},
3470 !,
3471 pp_rodin_label_indent(TExpr), % print any label
3472 {translate_in_mode(exists,'#',FSymbol)},
3473 %indent(' '),
3474 pp_atom_indent(FSymbol),
3475 pp_expr_ids_in_mode_indent(Ids),pp_atom_indent('.'),
3476 inc_lvl(other,conjunct), % always need parentheses here
3477 {add_normal_typing_predicates(Ids,RHS,RHST), Prio=40}, % Prio of conjunction
3478 pp_pred_nested(RHST,conjunct,Prio),
3479 dec_lvl(other,conjunct).
3480 pp_pred_nested(TExpr,_,_) --> {TExpr = b(forall(Ids,LHS,RHS),pred,_)},
3481 !,
3482 pp_rodin_label_indent(TExpr), % print any label
3483 {translate_in_mode(forall,'!',FSymbol)},
3484 %indent(' '),
3485 pp_atom_indent(FSymbol),
3486 pp_expr_ids_in_mode_indent(Ids),pp_atom_indent('.'),
3487 inc_lvl(other,implication), % always need parentheses here
3488 {add_normal_typing_predicates(Ids,LHS,LHST), Prio=30}, % Prio of implication
3489 pp_pred_nested(LHST,implication,Prio),
3490 {translate_in_mode(implication,'=>',Symbol)},
3491 indent(' '),pp_atom_indent(Symbol),
3492 indent(' '),
3493 pp_pred_nested(RHS,right(implication),Prio),
3494 dec_lvl(other,implication).
3495 pp_pred_nested(TExpr,_,_) -->
3496 {\+ eventb_translation_mode,
3497 TExpr = b(let_predicate(Ids,Exprs,Body),pred,_)
3498 }, %Ids=[_]}, % TODO: enable printing with more than one id; see below
3499 !,
3500 pp_let_nested(Ids,Exprs,Body).
3501 pp_pred_nested(b(BOP,pred,_),_CurrentType,CurMinPrio) -->
3502 {indent_binary_predicate(BOP,LHS,RHS,OpStr),
3503 get_texpr_id(LHS,_),can_indent_texpr(RHS)},!,
3504 pp_expr_m_indent(LHS,CurMinPrio),
3505 insertstr(OpStr),
3506 increase_indentation_level(2),
3507 indent(''),
3508 pp_expr_indent(RHS), % only supports %, {}, bool which do not need parentheses
3509 decrease_indentation_level(2).
3510 pp_pred_nested(Expr,_CurrentType,CurMinPrio) --> {can_indent_texpr(Expr)},!,
3511 pp_expr_m_indent(Expr,CurMinPrio).
3512 pp_pred_nested(Expr,_CurrentType,CurMinPrio) --> pp_expr_m_indent(Expr,CurMinPrio).
3513
3514 indent_binary_predicate(equal(LHS,RHS),LHS,RHS,' = ').
3515 indent_binary_predicate(member(LHS,RHS),LHS,RHS,' : ').
3516
3517 pp_let_nested(Ids,Exprs,Body) -->
3518 indent('LET '),
3519 pp_expr_indent_l(Ids),
3520 insertstr(' BE '),
3521 {maplist(create_equality,Ids,Exprs,Equalities)},
3522 preds_over_lines(2,'@let_eq',Equalities),
3523 indent(' IN '),
3524 increase_indentation_level(2),
3525 pp_pred_nested(Body,let_predicate,40),
3526 decrease_indentation_level(2),
3527 indent(' END').
3528 pp_let_expr_nested(Ids,Exprs,Body) -->
3529 insertstr('LET '),
3530 pp_expr_indent_l(Ids),
3531 insertstr(' BE '),
3532 {maplist(create_equality,Ids,Exprs,Equalities)},
3533 preds_over_lines(2,'@let_eq',Equalities),
3534 indent('IN '),
3535 increase_indentation_level(2),
3536 pp_expr_indent(Body),
3537 decrease_indentation_level(2),
3538 indent('END').
3539
3540 is_nontrivial_negation(b(negation(NExpr),pred,_),NExpr,NewType,Prio) :-
3541 get_texpr_expr(NExpr,E),
3542 (E=negation(_) -> NewType=other,Prio=0
3543 ; get_binary_connective(E,NewType,Ascii,_,_),
3544 binary_infix(NewType,Ascii,Prio,_Assoc)).
3545
3546 pp_rodin_label_indent(b(_,_,Infos),(I,S),(I,T)) :- pp_rodin_label(Infos,S,T).
3547 % note: below we will print unnecessary parentheses in case of Atelier-B mode; but for readability it maye be better to add them
3548 inc_lvl(Old,New) --> {New=Old}, !,[].
3549 inc_lvl(_,_) --> pp_atom_indent('('), % not strictly necessary if higher_prio
3550 increase_indentation_level, indent(' ').
3551 dec_lvl(Old,New) --> {New=Old}, !,[].
3552 dec_lvl(_,_) --> decrease_indentation_level, indent(' '),pp_atom_indent(')').
3553
3554 is_associative(conjunct).
3555 is_associative(disjunct).
3556
3557 %higher_prio(conjunct,implication).
3558 %higher_prio(disjunct,implication).
3559 % priority of equivalence changes in Rodin vs Atelier-B, maybe better add parentheses
3560
3561 translate_ifs([]) --> !,
3562 indent('END').
3563 translate_ifs([Elsif]) -->
3564 {get_if_elsif(Elsif,P,S),
3565 optional_type(P,truth)},!,
3566 indent('ELSE'), insert_subst(S), indent('END').
3567 translate_ifs([Elsif|Rest]) -->
3568 {get_if_elsif(Elsif,P,S)},!,
3569 indent('ELSIF '), pp_expr_indent(P), insertstr(' THEN'),
3570 insert_subst(S),
3571 translate_ifs(Rest).
3572 translate_ifs(ElseList) -->
3573 {functor(ElseList,F,A),add_error(translate_ifs,'Could not translate IF-THEN-ELSE: ',F/A-ElseList),fail}.
3574
3575 get_if_elsif(Elsif,P,S) :-
3576 (optional_type(Elsif,if_elsif(P,S)) -> true
3577 ; add_internal_error('Is not an if_elsif:',get_if_elsif(Elsif,P,S)), fail).
3578
3579 insert_subst(S) -->
3580 indention_level(I,I2),{I2 is I+2},
3581 translate_subst_check(S),
3582 indention_level(_,I).
3583
3584 translate_subst_check(S) --> translate_subst(S),!.
3585 translate_subst_check(S) -->
3586 {b_functor(S,F,A),add_error(translate_subst,'Could not translate substitution: ',F/A-S),fail}.
3587
3588 b_functor(b(E,_,_),F,A) :- !,functor(E,F,A).
3589 b_functor(E,F,A) :- functor(E,F,A).
3590
3591 pp_description_pragma_of(enumerated_set_def(_,_)) --> !, "".
3592 pp_description_pragma_of(Expr) -->
3593 ({get_texpr_description(Expr,Desc)}
3594 -> insert_atom(' /*@desc '), insert_atom(Desc), insert_atom(' */')
3595 ; {true}).
3596 indent_expr(Expr) -->
3597 indent, pp_expr_indent(Expr),
3598 pp_description_pragma_of(Expr).
3599 %indent_expr_l([]) --> !.
3600 %indent_expr_l([Expr|Rest]) -->
3601 % indent_expr(Expr), indent_expr_l(Rest).
3602 indent_expr_l_sep([],_) --> !.
3603 indent_expr_l_sep([Expr|Rest],Sep) -->
3604 indent_expr(Expr),
3605 {(Rest=[] -> RealSep='' ; RealSep=Sep)},
3606 insert_atom(RealSep), % the threaded argument is a pair, not directly a string !
3607 indent_expr_l_sep(Rest,Sep).
3608 %indention_level(L) --> indention_level(L,L).
3609 increase_indentation_level --> indention_level(L,New), {New is L+1}.
3610 increase_indentation_level(N) --> indention_level(L,New), {New is L+N}.
3611 decrease_indentation_level --> indention_level(L,New), {New is L-1}.
3612 decrease_indentation_level(N) --> indention_level(L,New), {New is L-N}.
3613 indention_level(Old,New,(Old,S),(New,S)).
3614 indention_codes(Old,New,(Indent,Old),(Indent,New)).
3615 indent --> indent('').
3616 indent(M,(I,S),(I,T)) :- indent2(I,M,S,T).
3617 indent2(Level,Msg) -->
3618 "\n",do_indention(Level),ppatom(Msg).
3619
3620 insert_atom(Sep,(I,S),(I,T)) :- ppatom(Sep,S,T).
3621
3622 insertstr(M,(I,S),(I,T)) :- ppterm(M,S,T).
3623 insertcodes(M,(I,S),(I,T)) :- ppcodes(M,S,T).
3624
3625 do_indention(0,T,R) :- !, R=T.
3626 do_indention(N,[32|I],O) :-
3627 N>0,N2 is N-1, do_indention(N2,I,O).
3628
3629 optional_type(Typed,Expr) :- get_texpr_expr(Typed,E),!,Expr=E.
3630 optional_type(Expr,Expr).
3631
3632 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3633 % expressions and predicates
3634
3635 % pretty-type an expression in an indent-environment
3636 % currently, the indent level is just thrown away
3637 % TODO: pp_expr_indent dom( comprehension_set ) / union ( ...)
3638 pp_expr_indent(b(comprehension_set(Ids,Body),_,_)) -->
3639 {\+ eventb_translation_mode, % TODO: also print in Event-B mode:
3640 detect_lambda_comprehension(Ids,Body, FrontIDs,LambdaBody,ToExpr)},
3641 {add_normal_typing_predicates(FrontIDs,LambdaBody,TLambdaBody)},
3642 !,
3643 insertstr('%('), % to do: use lambda_symbol and improve layout below
3644 pp_expr_indent_l(FrontIDs),
3645 insertstr(') . ('),
3646 pred_over_lines(2,'@body',TLambdaBody),
3647 indent(' | '), increase_indentation_level(2),
3648 indent(''), pp_expr_indent(ToExpr), decrease_indentation_level(2),
3649 indent(')').
3650 pp_expr_indent(b(comprehension_set(Ids,Body),_,Info),(I,S),(I,T)) :-
3651 pp_comprehension_set5(Ids,Body,Info,_,special(_Kind),S,T),
3652 % throw away indent and check if a special pp rule is applicable
3653 !.
3654 pp_expr_indent(b(comprehension_set(Ids,Body),_,_)) -->
3655 !,
3656 insertstr('{'), pp_expr_indent_l(Ids),
3657 insertstr(' | '),
3658 pred_over_lines(2,'@body',Body),
3659 indent('}').
3660 pp_expr_indent(b(convert_bool(Body),_,_)) -->
3661 !,
3662 insertstr('bool('),
3663 pred_over_lines(2,'@bool',Body),
3664 indent(')').
3665 pp_expr_indent(b(if_then_else(Test,Then,Else),_,_)) -->
3666 !,
3667 insertstr('IF'),
3668 pred_over_lines(2,'@test',Test),
3669 indent('THEN'),increase_indentation_level(2),
3670 indent(''),pp_expr_indent(Then),decrease_indentation_level(2),
3671 indent('ELSE'),increase_indentation_level(2),
3672 indent(''),pp_expr_indent(Else),decrease_indentation_level(2),
3673 indent('END').
3674 pp_expr_indent(b(let_expression(Ids,Exprs,Body),_,_)) -->
3675 !,
3676 pp_let_expr_nested(Ids,Exprs,Body).
3677 % TODO: support a few more like dom/ran(comprehension_set) SIGMA, PI, \/ (union), ...
3678 pp_expr_indent(Expr,(I,S),(I,T)) :-
3679 %get_texpr_expr(Expr,F), functor(F,FF,NN), format(user_output,'Cannot indent: ~w/~w~n',[FF,NN]),
3680 pp_expr(Expr,_,_LimitReached,S,T). % throw away indent
3681
3682 can_indent_texpr(b(E,_,_)) :- can_indent_expr(E).
3683 can_indent_expr(comprehension_set(_,_)).
3684 can_indent_expr(convert_bool(_)).
3685 can_indent_expr(if_then_else(_,_,_)).
3686 can_indent_expr(let_expression(_,_,_)).
3687
3688 pp_expr_indent_l([E]) --> !, pp_expr_indent(E).
3689 pp_expr_indent_l(Exprs,(I,S),(I,T)) :-
3690 pp_expr_l(Exprs,_LR,S,T). % throw away indent
3691 pp_expr_m_indent(Expr,MinPrio,(I,S),(I,T)) :-
3692 pp_expr_m(Expr,MinPrio,_LimitReached,S,T).
3693 pp_atom_indent(A,(I,S),(I,T)) :- ppatom(A,S,T).
3694 pp_expr_ids_in_mode_indent(Ids,(I,S),(I,T)) :- pp_expr_ids_in_mode(Ids,_,S,T).
3695
3696
3697
3698
3699 is_boolean_value(b(B,boolean,_),BV) :- boolean_aux(B,BV).
3700 boolean_aux(boolean_true,pred_true).
3701 boolean_aux(boolean_false,pred_false).
3702 boolean_aux(value(V),BV) :- nonvar(V),!,BV=V.
3703
3704
3705 constants_in_mode(F,S) :-
3706 constants(F,S1), translate_in_mode(F,S1,S).
3707
3708 constants(pred_true,'TRUE').
3709 constants(pred_false,'FALSE').
3710 constants(boolean_true,'TRUE').
3711 constants(boolean_false,'FALSE').
3712 constants(max_int,'MAXINT').
3713 constants(min_int,'MININT').
3714 constants(empty_set,'{}').
3715 constants(bool_set,'BOOL').
3716 constants(float_set,'FLOAT').
3717 constants(real_set,'REAL').
3718 constants(string_set,'STRING').
3719 constants(empty_sequence,'[]').
3720 constants(event_b_identity,'id').
3721
3722 constants(truth,Res) :- eventb_translation_mode,!,Res=true.
3723 constants(truth,Res) :- animation_minor_mode(tla),!,Res='TRUE'.
3724 constants(truth,Res) :- atelierb_mode(_),!,Res='(TRUE:BOOL)'. % __truth; we could also do TRUE=TRUE
3725 constants(truth,'btrue').
3726 constants(falsity,Res) :- eventb_translation_mode,!,Res=false.
3727 constants(falsity,Res) :- animation_minor_mode(tla),!,Res='FALSE'.
3728 constants(falsity,Res) :- atelierb_mode(_),!,Res='(TRUE=FALSE)'.
3729 constants(falsity,'bfalse'). % __falsity
3730 constants(unknown_truth_value(Msg),Res) :- % special internal constant
3731 ajoin(['?(',Msg,')'],Res).
3732
3733 function_like_in_mode(F,S) :-
3734 function_like(F,S1),
3735 translate_in_mode(F,S1,S).
3736
3737 function_like(convert_bool,bool).
3738 function_like(convert_real,real). % cannot be used on its own: dom(real) is not accepted by Atelier-B
3739 function_like(convert_int_floor,floor). % ditto
3740 function_like(convert_int_ceiling,ceiling). % ditto
3741 function_like(successor,succ). % can also be used on its own; e.g., dom(succ)=INTEGER is ok
3742 function_like(predecessor,pred). % ditto
3743 function_like(max,max).
3744 function_like(max_real,max).
3745 function_like(min,min).
3746 function_like(min_real,min).
3747 function_like(card,card).
3748 function_like(pow_subset,'POW').
3749 function_like(pow1_subset,'POW1').
3750 function_like(fin_subset,'FIN').
3751 function_like(fin1_subset,'FIN1').
3752 function_like(identity,id).
3753 function_like(first_projection,prj1).
3754 function_like(first_of_pair,'prj1'). % used to be __first_of_pair, will be dealt with separately to generate parsable representation
3755 function_like(second_projection,prj2).
3756 function_like(second_of_pair,'prj2'). % used to be __second_of_pair, will be dealt with separately to generate parsable representation
3757 function_like(iteration,iterate).
3758 function_like(event_b_first_projection_v2,prj1).
3759 function_like(event_b_second_projection_v2,prj2).
3760 function_like(reflexive_closure,closure).
3761 function_like(closure,closure1).
3762 function_like(domain,dom).
3763 function_like(range,ran).
3764 function_like(seq,seq).
3765 function_like(seq1,seq1).
3766 function_like(iseq,iseq).
3767 function_like(iseq1,iseq1).
3768 function_like(perm,perm).
3769 function_like(size,size).
3770 function_like(first,first).
3771 function_like(last,last).
3772 function_like(front,front).
3773 function_like(tail,tail).
3774 function_like(rev,rev).
3775 function_like(general_concat,conc).
3776 function_like(general_union,union).
3777 function_like(general_intersection,inter).
3778 function_like(trans_function,fnc).
3779 function_like(trans_relation,rel).
3780 function_like(tree,tree).
3781 function_like(btree,btree).
3782 function_like(const,const).
3783 function_like(top,top).
3784 function_like(sons,sons).
3785 function_like(prefix,prefix).
3786 function_like(postfix,postfix).
3787 function_like(sizet,sizet).
3788 function_like(mirror,mirror).
3789 function_like(rank,rank).
3790 function_like(father,father).
3791 function_like(son,son).
3792 function_like(subtree,subtree).
3793 function_like(arity,arity).
3794 function_like(bin,bin).
3795 function_like(left,left).
3796 function_like(right,right).
3797 function_like(infix,infix).
3798
3799 function_like(rec,rec).
3800 function_like(struct,struct).
3801
3802 function_like(negation,not).
3803 function_like(bag_items,items).
3804
3805 function_like(finite,finite). % from Event-B, TO DO: if \+ eventb_translation_mode then print as S:FIN(S)
3806 function_like(witness,'@witness'). % from Event-B
3807
3808 function_like(floored_div,'FDIV') :- \+ animation_minor_mode(tla). % using external function
3809
3810 unary_prefix(unary_minus,-,210).
3811 unary_prefix(unary_minus_real,-,210).
3812 unary_prefix(mu,'MU',210) :- animation_minor_mode(z).
3813
3814 unary_prefix_parentheses(compaction,'compaction').
3815 unary_prefix_parentheses(bag_items,'bag_items').
3816 unary_prefix_parentheses(mu,'MU') :- \+ animation_minor_mode(z). % write with () for external function
3817
3818 unary_postfix(reverse,'~',230). % relational inverse
3819
3820
3821 always_surround_by_parentheses(parallel_product).
3822 always_surround_by_parentheses(composition).
3823
3824 binary_infix_symbol(b(T,_,_),Symbol) :- functor(T,F,2), binary_infix_in_mode(F,Symbol,_,_).
3825
3826 % EXPR * EXPR --> EXPR
3827 binary_infix(composition,';',20,left).
3828 binary_infix(overwrite,'<+',160,left).
3829 binary_infix(direct_product,'><',160,left). % Rodin requires parentheses
3830 binary_infix(parallel_product,'||',20,left).
3831 binary_infix(concat,'^',160,left).
3832 binary_infix(relations,'<->',125,left).
3833 binary_infix(partial_function,'+->',125,left).
3834 binary_infix(total_function,'-->',125,left).
3835 binary_infix(partial_injection,'>+>',125,left).
3836 binary_infix(total_injection,'>->',125,left).
3837 binary_infix(partial_surjection,'+->>',125,left).
3838 binary_infix(total_surjection,Symbol,125,left) :-
3839 (eventb_translation_mode -> Symbol = '->>'; Symbol = '-->>').
3840 binary_infix(total_bijection,'>->>',125,left).
3841 binary_infix(partial_bijection,'>+>>',125,left).
3842 binary_infix(total_relation,'<<->',125,left). % only in Event-B
3843 binary_infix(surjection_relation,'<->>',125,left). % only in Event-B
3844 binary_infix(total_surjection_relation,'<<->>',125,left). % only in Event-B
3845 binary_infix(insert_front,'->',160,left).
3846 binary_infix(insert_tail,'<-',160,left).
3847 binary_infix(domain_restriction,'<|',160,left).
3848 binary_infix(domain_subtraction,'<<|',160,left).
3849 binary_infix(range_restriction,'|>',160,left).
3850 binary_infix(range_subtraction,'|>>',160,left).
3851 binary_infix(intersection,'/\\',160,left).
3852 binary_infix(union,'\\/',160,left).
3853 binary_infix(restrict_front,'/|\\',160,left).
3854 binary_infix(restrict_tail,'\\|/',160,left).
3855 binary_infix(couple,'|->',160,left).
3856 binary_infix(interval,'..',170,left).
3857 binary_infix(add,+,180,left).
3858 binary_infix(add_real,+,180,left).
3859 binary_infix(minus,-,180,left).
3860 binary_infix(minus_real,-,180,left).
3861 binary_infix(set_subtraction,'\\',180,left) :- eventb_translation_mode,!. % symbol is not allowed by Atelier-B
3862 binary_infix(set_subtraction,-,180,left).
3863 binary_infix(minus_or_set_subtract,-,180,left).
3864 binary_infix(multiplication,*,190,left).
3865 binary_infix(multiplication_real,*,190,left).
3866 binary_infix(cartesian_product,**,190,left) :- eventb_translation_mode,!.
3867 binary_infix(cartesian_product,*,190,left).
3868 binary_infix(mult_or_cart,*,190,left). % in case type checker not yet run
3869 binary_infix(div,/,190,left).
3870 binary_infix(div_real,/,190,left).
3871 binary_infix(floored_div,div,190,left) :- animation_minor_mode(tla).
3872 binary_infix(modulo,mod,190,left).
3873 binary_infix(power_of,**,200,right).
3874 binary_infix(power_of_real,**,200,right).
3875 binary_infix(typeof,oftype,120,right). % Event-B oftype operator; usually removed by btypechecker, technically has no associativity in our parser, but right associativity matches better
3876
3877 binary_infix(ring,'\x2218\',160,left). % our B Parser gives ring same priority as direct_product or overwrite
3878
3879 % PRED * PRED --> PRED
3880 binary_infix(implication,'=>',30,left).
3881 binary_infix(conjunct,'&',40,left).
3882 binary_infix(disjunct,or,40,left).
3883 binary_infix(equivalence,'<=>',Prio,left) :- % in Rodin this has the same priority as implication
3884 (eventb_translation_mode -> Prio=30 ; Prio=60).
3885
3886
3887 % EXPR * EXPR --> PRED
3888 binary_infix(equal,=,60,left).
3889 binary_infix(not_equal,'/=',160,left).
3890 binary_infix(less_equal,'<=',160,left).
3891 binary_infix(less,'<',160,left).
3892 binary_infix(less_equal_real,'<=',160,left).
3893 binary_infix(less_real,'<',160,left).
3894 binary_infix(greater_equal,'>=',160,left).
3895 binary_infix(greater,'>',160,left).
3896 binary_infix(member,':',60,left).
3897 binary_infix(not_member,'/:',160,left).
3898 binary_infix(subset,'<:',110,left).
3899 binary_infix(subset_strict,'<<:',110,left).
3900 binary_infix(not_subset,'/<:',110,left).
3901 binary_infix(not_subset_strict,'/<<:',110,left).
3902
3903 binary_infix(values_entry,'=',60,left).
3904
3905 % atelierb_mode(prover(_)): translation for AtelierB's PP/ML prover
3906 % atelierb_mode(native): translation to native B supported by AtelierB
3907 :- dynamic latex_mode/0, unicode_mode/0, atelierb_mode/1, force_eventb_rodin_mode/0.
3908
3909 %latex_mode.
3910 %unicode_mode.
3911 %force_eventb_rodin_mode. % Force Event-B output even if not in eventb minor mode
3912
3913 eventb_translation_mode :- animation_minor_mode(eventb),!.
3914 eventb_translation_mode :- force_eventb_rodin_mode.
3915
3916 set_force_eventb_mode :- assertz(force_eventb_rodin_mode).
3917 unset_force_eventb_mode :-
3918 (retract(force_eventb_rodin_mode) -> true ; add_internal_error('Was not in forced Event-B mode: ',force_eventb_rodin_mode)).
3919
3920 set_unicode_mode :- assertz(unicode_mode).
3921 set_latex_mode :- assertz(latex_mode).
3922 unset_unicode_mode :-
3923 (retract(unicode_mode) -> true ; add_internal_error('Was not in Unicode mode: ',unset_unicode_mode)).
3924 unset_latex_mode :-
3925 (retract(latex_mode) -> true
3926 ; add_internal_error('Was not in Latex mode: ',unset_latex_mode)).
3927
3928 set_atelierb_mode(Mode) :- asserta(atelierb_mode(Mode)).
3929 unset_atelierb_mode :-
3930 (retract(atelierb_mode(_)) -> true ; add_internal_error('Was not in Atelier-B mode: ',unset_atelierb_mode)).
3931
3932 get_translation_mode(M) :- unicode_mode, !, M=unicode.
3933 get_translation_mode(M) :- latex_mode, !, M=latex.
3934 get_translation_mode(M) :- atelierb_mode(native), !, M=atelierb.
3935 get_translation_mode(M) :- atelierb_mode(prover(pp)), !, M=atelierb_pp.
3936 get_translation_mode(M) :- atelierb_mode(prover(ml)), !, M=atelierb_ml.
3937 get_translation_mode(ascii).
3938
3939 % TO DO: provide better stack-based setting/unsetting of modes or use options parameter
3940 set_translation_mode(ascii) :- !, retractall(unicode_mode), retractall(latex_mode), retractall(atelierb_mode(_)).
3941 set_translation_mode(unicode) :- !, set_unicode_mode.
3942 set_translation_mode(latex) :- !, set_latex_mode.
3943 set_translation_mode(atelierb) :- !, set_atelierb_mode(native).
3944 set_translation_mode(atelierb_pp) :- !, set_atelierb_mode(prover(pp)). % translation for PP/ML prover
3945 set_translation_mode(atelierb_ml) :- !, set_atelierb_mode(prover(ml)).
3946 set_translation_mode(Mode) :- add_internal_error('Illegal mode:',set_translation_mode(Mode)).
3947
3948 unset_translation_mode(ascii) :- !.
3949 unset_translation_mode(unicode) :- !,unset_unicode_mode.
3950 unset_translation_mode(latex) :- !,unset_latex_mode.
3951 unset_translation_mode(atelierb) :- !,unset_atelierb_mode.
3952 unset_translation_mode(atelierb_pp) :- !,unset_atelierb_mode.
3953 unset_translation_mode(atelierb_ml) :- !,unset_atelierb_mode.
3954 unset_translation_mode(Mode) :- add_internal_error('Illegal mode:',unset_translation_mode(Mode)).
3955
3956 with_translation_mode(Mode, Call) :-
3957 get_translation_mode(OldMode),
3958 (OldMode == Mode -> Call ;
3959 set_translation_mode(ascii), % Clear all existing translation mode settings first
3960 set_translation_mode(Mode),
3961 call_cleanup(Call, set_translation_mode(OldMode))
3962 % FIXME This might not restore all translation modes fully!
3963 % For example, if both unicode_mode and latex_mode are set,
3964 % then with_translation_mode(ascii, ...) will only restore unicode_mode.
3965 % Not sure if this might cause problems for some code.
3966 ).
3967
3968 % The language mode is currently linked to the animation minor mode,
3969 % so be careful when changing it!
3970 % TODO Allow overriding the language for translate without affecting the animation mode
3971
3972 get_language_mode(csp_and(Lang)) :-
3973 csp_with_bz_mode,
3974 !,
3975 (animation_minor_mode(Lang) -> true ; Lang = b).
3976 get_language_mode(Lang) :- animation_minor_mode(Lang), !.
3977 get_language_mode(Lang) :- animation_mode(Lang).
3978
3979 set_language_mode(csp_and(Lang)) :-
3980 !,
3981 set_animation_mode(csp_and_b),
3982 (Lang == b -> true ; set_animation_minor_mode(Lang)).
3983 set_language_mode(csp) :- !, set_animation_mode(csp).
3984 set_language_mode(xtl) :- !, set_animation_mode(xtl).
3985 set_language_mode(b) :- !, set_animation_mode(b).
3986 set_language_mode(Lang) :-
3987 set_animation_mode(b),
3988 set_animation_minor_mode(Lang).
3989
3990 with_language_mode(Lang, Call) :-
3991 get_language_mode(OldLang),
3992 (OldLang == Lang -> Call ;
3993 set_language_mode(Lang),
3994 call_cleanup(Call, set_language_mode(OldLang))
3995 % FIXME This might not restore all animation modes fully!
3996 % It's apparently possible to have multiple animation minor modes,
3997 % which get/set_language_mode doesn't handle.
3998 % (Are multiple animation minor modes actually used anywhere?)
3999 ).
4000
4001 exists_symbol --> {latex_mode},!, "\\exists ".
4002 exists_symbol --> {unicode_mode},!, pp_colour_code(magenta),[8707],pp_colour_code(reset).
4003 exists_symbol --> pp_colour_code(blue),"#",pp_colour_code(reset).
4004 forall_symbol --> {latex_mode},!, "\\forall ".
4005 forall_symbol --> {unicode_mode},!, pp_colour_code(magenta),[8704],pp_colour_code(reset).
4006 forall_symbol --> pp_colour_code(blue),"!",pp_colour_code(reset).
4007 dot_symbol --> {latex_mode},!, "\\cdot ".
4008 dot_symbol --> {unicode_mode},!, [183]. %"·". % dot also used in Rodin
4009 dot_symbol --> ".".
4010 dot_bullet_symbol --> {latex_mode},!, "\\cdot ".
4011 dot_bullet_symbol --> [183]. %"·". % dot also used in Rodin
4012 set_brackets(X,Y) :- latex_mode,!,X='\\{', Y='\\}'.
4013 set_brackets('{','}').
4014 left_set_bracket --> {latex_mode},!, "\\{ ".
4015 left_set_bracket --> "{".
4016 right_set_bracket --> {latex_mode},!, "\\} ".
4017 right_set_bracket --> "}".
4018 maplet_symbol --> {latex_mode},!, "\\mapsto ".
4019 maplet_symbol --> {unicode_mode},!, [8614].
4020 maplet_symbol --> "|->". % also provide option to use colours? pp_colour_code(blue) ,...
4021
4022 lambda_symbol --> {unicode_mode},!, [955]. % '\x3BB\'
4023 lambda_symbol --> {latex_mode},!, "\\lambda ".
4024 lambda_symbol --> pp_colour_code(blue),"%",pp_colour_code(reset).
4025
4026 and_symbol --> {unicode_mode},!, [8743]. % ''\x2227\''
4027 and_symbol --> {latex_mode},!, "\\wedge ".
4028 and_symbol --> "&".
4029
4030 hash_card_symbol --> {latex_mode},!, "\\# ".
4031 hash_card_symbol --> "#".
4032 ldots --> {latex_mode},!, "\\ldots ".
4033 ldots --> "...".
4034
4035 empty_set_symbol --> {get_preference(translate_print_all_sequences,true)},!, pp_empty_sequence.
4036 empty_set_symbol --> {unicode_mode},!, [8709].
4037 empty_set_symbol --> {latex_mode},!, "\\emptyset ".
4038 empty_set_symbol --> "{}".
4039
4040 underscore_symbol --> {latex_mode},!, "\\_".
4041 underscore_symbol --> "_".
4042
4043 string_start_symbol --> {latex_mode},!, "\\textnormal{``".
4044 string_start_symbol --> pp_colour_code(blue), """".
4045 string_end_symbol --> {latex_mode},!, "''}".
4046 string_end_symbol --> pp_colour_code(reset), """".
4047
4048
4049 unary_postfix_in_mode(Op,Trans2,Prio) :-
4050 unary_postfix(Op,Trans,Prio), % print(op(Op,Trans)),nl,
4051 translate_in_mode(Op,Trans,Trans2).
4052
4053 binary_infix_in_mode(Op,Trans2,Prio,Assoc) :-
4054 binary_infix(Op,Trans,Prio,Assoc), % print(op(Op,Trans)),nl,
4055 translate_in_mode(Op,Trans,Trans2).
4056
4057 latex_integer_set_translation('NATURAL', '\\mathbb N '). % \nat in bsymb.sty
4058 latex_integer_set_translation('NATURAL1', '\\mathbb N_1 '). % \natn
4059 latex_integer_set_translation('INTEGER', '\\mathbb Z '). % \intg
4060 latex_integer_set_translation('REAL', '\\mathbb R '). % \intg
4061
4062 latex_translation(empty_set, '\\emptyset ').
4063 latex_translation(implication, '\\mathbin\\Rightarrow ').
4064 latex_translation(conjunct,'\\wedge ').
4065 latex_translation(disjunct,'\\vee ').
4066 latex_translation(equivalence,'\\mathbin\\Leftrightarrow ').
4067 latex_translation(negation,'\\neg ').
4068 latex_translation(not_equal,'\\neq ').
4069 latex_translation(less_equal,'\\leq ').
4070 latex_translation(less_equal_real,'\\leq ').
4071 latex_translation(greater_equal,'\\geq ').
4072 latex_translation(member,'\\in ').
4073 latex_translation(not_member,'\\not\\in ').
4074 latex_translation(subset,'\\subseteq ').
4075 latex_translation(subset_strict,'\\subset ').
4076 latex_translation(not_subset,'\\not\\subseteq ').
4077 latex_translation(not_subset_strict,'\\not\\subset ').
4078 latex_translation(union,'\\cup ').
4079 latex_translation(intersection,'\\cap ').
4080 latex_translation(couple,'\\mapsto ').
4081 latex_translation(cartesian_product,'\\times').
4082 latex_translation(rec,'\\mathit{rec}').
4083 latex_translation(struct,'\\mathit{struct}').
4084 latex_translation(convert_bool,'\\mathit{bool}').
4085 latex_translation(max,'\\mathit{max}').
4086 latex_translation(max_real,'\\mathit{max}').
4087 latex_translation(min,'\\mathit{min}').
4088 latex_translation(min_real,'\\mathit{min}').
4089 latex_translation(modulo,'\\mod ').
4090 latex_translation(card,'\\mathit{card}').
4091 latex_translation(successor,'\\mathit{succ}').
4092 latex_translation(predecessor,'\\mathit{pred}').
4093 latex_translation(domain,'\\mathit{dom}').
4094 latex_translation(range,'\\mathit{ran}').
4095 latex_translation(size,'\\mathit{size}').
4096 latex_translation(first,'\\mathit{first}').
4097 latex_translation(last,'\\mathit{last}').
4098 latex_translation(front,'\\mathit{front}').
4099 latex_translation(tail,'\\mathit{tail}').
4100 latex_translation(rev,'\\mathit{rev}').
4101 latex_translation(seq,'\\mathit{seq}').
4102 latex_translation(seq1,'\\mathit{seq}_{1}').
4103 latex_translation(perm,'\\mathit{perm}').
4104 latex_translation(fin_subset,'\\mathit{FIN}').
4105 latex_translation(fin1_subset,'\\mathit{FIN}_{1}').
4106 latex_translation(first_projection,'\\mathit{prj}_{1}').
4107 latex_translation(second_projection,'\\mathit{prj}_{2}').
4108 latex_translation(pow_subset,'\\mathbb P\\hbox{}'). % POW \pow would require bsymb.sty
4109 latex_translation(pow1_subset,'\\mathbb P_1'). % POW1 \pown would require bsymb.sty
4110 latex_translation(concat,'\\stackrel{\\frown}{~}'). % was '\\hat{~}').
4111 latex_translation(relations,'\\mathbin\\leftrightarrow'). % <->, \rel requires bsymb.sty
4112 latex_translation(total_relation,'\\mathbin{\\leftarrow\\mkern-14mu\\leftrightarrow}'). % <<-> \trel requires bsymb.sty
4113 latex_translation(total_surjection_relation,'\\mathbin{\\leftrightarrow\\mkern-14mu\\leftrightarrow}'). % <<->> \strel requires bsymb.sty
4114 latex_translation(surjection_relation,'\\mathbin{\\leftrightarrow\\mkern-14mu\\rightarrow}'). % <->> \srel requires bsymb.sty
4115 latex_translation(partial_function,'\\mathbin{\\mkern6mu\\mapstochar\\mkern-6mu\\rightarrow}'). % +-> \pfun requires bsymb.sty, but \mapstochar is not supported by Mathjax
4116 latex_translation(partial_injection,'\\mathbin{\\mkern9mu\\mapstochar\\mkern-9mu\\rightarrowtail}'). % >+> \pinj requires bsymb.sty
4117 latex_translation(partial_surjection,'\\mathbin{\\mkern6mu\\mapstochar\\mkern-6mu\\twoheadrightarrow}'). % >+> \psur requires bsymb.sty
4118 latex_translation(total_function,'\\mathbin\\rightarrow'). % --> \tfun would require bsymb.sty
4119 latex_translation(total_surjection,'\\mathbin\\twoheadrightarrow'). % -->> \tsur requires bsymb.sty
4120 latex_translation(total_injection,'\\mathbin\\rightarrowtail'). % >-> \tinj requires bsymb.sty
4121 latex_translation(total_bijection,'\\mathbin{\\rightarrowtail\\mkern-18mu\\twoheadrightarrow}'). % >->> \tbij requires bsymb.sty
4122 latex_translation(domain_restriction,'\\mathbin\\lhd'). % <| domres requires bsymb.sty
4123 latex_translation(range_restriction,'\\mathbin\\rhd'). % |> ranres requires bsymb.sty
4124 latex_translation(domain_subtraction,'\\mathbin{\\lhd\\mkern-14mu-}'). % <<| domsub requires bsymb.sty
4125 latex_translation(range_subtraction,'\\mathbin{\\rhd\\mkern-14mu-}'). % |>> ransub requires bsymb.sty
4126 latex_translation(overwrite,'\\mathbin{\\lhd\\mkern-9mu-}'). % <+ \ovl requires bsymb.sty
4127 latex_translation(ring,'\\circ '). % not tested
4128 latex_translation(general_sum,'\\Sigma ').
4129 latex_translation(general_product,'\\Pi ').
4130 latex_translation(lambda,'\\lambda ').
4131 latex_translation(quantified_union,'\\bigcup\\nolimits'). % \Union requires bsymb.sty
4132 latex_translation(quantified_intersection,'\\bigcap\\nolimits'). % \Inter requires bsymb.sty
4133 %latex_translation(truth,'\\top').
4134 %latex_translation(falsity,'\\bot').
4135 latex_translation(truth,'{\\color{olive} \\top}'). % requires \usepackage{xcolor} in Latex
4136 latex_translation(falsity,'{\\color{red} \\bot}').
4137 latex_translation(boolean_true,'{\\color{olive} \\mathit{TRUE}}').
4138 latex_translation(boolean_false,'{\\color{red} \\mathit{FALSE}}').
4139 latex_translation(pred_true,'{\\color{olive} \\mathit{TRUE}}').
4140 latex_translation(pred_false,'{\\color{red} \\mathit{FALSE}}').
4141 latex_translation(reverse,'^{-1}').
4142
4143 ascii_to_unicode(Ascii,Unicode) :-
4144 translate_prolog_constructor(BAst,Ascii), % will not backtrack
4145 unicode_translation(BAst,Unicode).
4146
4147
4148 % can be used to translate Latex shortcuts to B Unicode operators for editors
4149 latex_to_unicode(LatexShortcut,Unicode) :-
4150 latex_to_b_ast(LatexShortcut,BAst),
4151 unicode_translation(BAst,Unicode).
4152 latex_to_unicode(LatexShortcut,Unicode) :- % allow to use B AST names as well
4153 unicode_translation(LatexShortcut,Unicode).
4154 latex_to_unicode(LatexShortcut,Unicode) :-
4155 greek_symbol(LatexShortcut,Unicode).
4156
4157 get_latex_keywords(List) :-
4158 findall(Id,latex_to_unicode(Id,_),Ids),
4159 sort(Ids,List).
4160
4161 get_latex_keywords_with_backslash(BList) :-
4162 get_latex_keywords(List),
4163 maplist(atom_concat('\\'),List,BList).
4164
4165 latex_to_b_ast(and,conjunct).
4166 latex_to_b_ast(bcomp,ring). % bsymb: backwards composition
4167 latex_to_b_ast(bigcap,quantified_intersection).
4168 latex_to_b_ast(bigcup,quantified_union).
4169 latex_to_b_ast(cap,intersection).
4170 latex_to_b_ast(cart,cartesian_product).
4171 latex_to_b_ast(cprod,cartesian_product).
4172 latex_to_b_ast(cdot,dot_symbol).
4173 latex_to_b_ast(cup,union).
4174 latex_to_b_ast(dprod,direct_product).
4175 latex_to_b_ast(dres,domain_restriction).
4176 latex_to_b_ast(dsub,domain_subtraction).
4177 latex_to_b_ast(emptyset,empty_set).
4178 latex_to_b_ast(exp,power_of).
4179 %latex_to_b_ast(fcomp,composition). % bsymb: forwards composition
4180 latex_to_b_ast(geq,greater_equal).
4181 latex_to_b_ast(implies,implication).
4182 latex_to_b_ast(in,member).
4183 latex_to_b_ast(int,'INTEGER').
4184 latex_to_b_ast(intg,'INTEGER'). % from bsymb
4185 latex_to_b_ast(lambda,lambda).
4186 latex_to_b_ast(land,conjunct).
4187 latex_to_b_ast(leq,less_equal).
4188 latex_to_b_ast(leqv,equivalence).
4189 latex_to_b_ast(lhd,domain_restriction).
4190 latex_to_b_ast(limp,implication).
4191 latex_to_b_ast(lor,disjunct).
4192 latex_to_b_ast(lnot,negation).
4193 latex_to_b_ast(mapsto,couple).
4194 latex_to_b_ast(nat,'NATURAL').
4195 latex_to_b_ast(natn,'NATURAL1').
4196 latex_to_b_ast(neg,negation).
4197 latex_to_b_ast(neq,not_equal).
4198 latex_to_b_ast(nin,not_member).
4199 latex_to_b_ast(not,negation).
4200 latex_to_b_ast(nsubseteq,not_subset).
4201 latex_to_b_ast(nsubset,not_subset_strict).
4202 latex_to_b_ast(or,disjunct).
4203 %latex_to_b_ast(ovl,overwrite).
4204 latex_to_b_ast(pfun,partial_function).
4205 latex_to_b_ast(pinj,partial_injection).
4206 latex_to_b_ast(psur,partial_surjection).
4207 latex_to_b_ast(pow,pow_subset).
4208 latex_to_b_ast(pown,pow1_subset).
4209 latex_to_b_ast(pprod,parallel_product).
4210 latex_to_b_ast(qdot,dot_symbol).
4211 latex_to_b_ast(real,'REAL').
4212 latex_to_b_ast(rel,relations).
4213 latex_to_b_ast(rhd,range_restriction).
4214 latex_to_b_ast(rres,range_restriction).
4215 latex_to_b_ast(rsub,range_subtraction).
4216 latex_to_b_ast(srel,surjection_relation).
4217 latex_to_b_ast(subseteq,subset).
4218 latex_to_b_ast(subset,subset_strict).
4219 latex_to_b_ast(tbij,total_bijection).
4220 latex_to_b_ast(tfun,total_function).
4221 latex_to_b_ast(tinj,total_injection).
4222 latex_to_b_ast(trel,total_relation).
4223 latex_to_b_ast(tsrel,total_surjection_relation).
4224 latex_to_b_ast(tsur,total_surjection).
4225 latex_to_b_ast(upto,interval).
4226 latex_to_b_ast(vee,disjunct).
4227 latex_to_b_ast(wedge,conjunct).
4228 latex_to_b_ast('INT','INTEGER').
4229 latex_to_b_ast('NAT','NATURAL').
4230 latex_to_b_ast('N','NATURAL').
4231 latex_to_b_ast('Pi',general_product).
4232 latex_to_b_ast('POW',pow_subset).
4233 latex_to_b_ast('REAL','REAL').
4234 latex_to_b_ast('Rightarrow',implication).
4235 latex_to_b_ast('Sigma',general_sum).
4236 latex_to_b_ast('Leftrightarrow',equivalence).
4237 latex_to_b_ast('Inter',quantified_intersection).
4238 latex_to_b_ast('Union',quantified_union).
4239 latex_to_b_ast('Z','INTEGER').
4240
4241 unicode_translation(implication, '\x21D2\').
4242 unicode_translation(conjunct,'\x2227\').
4243 unicode_translation(disjunct,'\x2228\').
4244 unicode_translation(negation,'\xAC\').
4245 unicode_translation(equivalence,'\x21D4\').
4246 unicode_translation(not_equal,'\x2260\').
4247 unicode_translation(less_equal,'\x2264\').
4248 unicode_translation(less_equal_real,'\x2264\').
4249 unicode_translation(greater_equal,'\x2265\').
4250 unicode_translation(member,'\x2208\').
4251 unicode_translation(not_member,'\x2209\').
4252 unicode_translation(subset,'\x2286\').
4253 unicode_translation(subset_strict,'\x2282\').
4254 unicode_translation(not_subset,'\x2288\').
4255 unicode_translation(not_subset_strict,'\x2284\').
4256 unicode_translation(supseteq,'\x2287\'). % ProB parser supports unicode symbol by reversing arguments
4257 unicode_translation(supset_strict,'\x2283\'). % ditto
4258 unicode_translation(not_supseteq,'\x2289\'). % ditto
4259 unicode_translation(not_supset_strict,'\x2285\'). % ditto
4260 unicode_translation(union,'\x222A\').
4261 unicode_translation(intersection,'\x2229\').
4262 unicode_translation(cartesian_product,'\xD7\'). % also 0x2217 in Camille or 0x2A2F (vector or cross product) in IDP
4263 unicode_translation(couple,'\x21A6\').
4264 unicode_translation(div,'\xF7\').
4265 unicode_translation(dot_symbol,'\xB7\'). % not a B AST operator, cf dot_symbol 183
4266 unicode_translation(floored_div,'\xF7\') :-
4267 animation_minor_mode(tla). % should we provide another Unicode character here for B?
4268 unicode_translation(power_of,'\x02C4\'). % version of ^, does not exist in Rodin ?!, upwards arrow x2191 used below for restrict front
4269 unicode_translation(power_of_real,'\x02C4\').
4270 unicode_translation(interval,'\x2025\').
4271 unicode_translation(domain_restriction,'\x25C1\').
4272 unicode_translation(domain_subtraction,'\x2A64\').
4273 unicode_translation(range_restriction,'\x25B7\').
4274 unicode_translation(range_subtraction,'\x2A65\').
4275 unicode_translation(relations,'\x2194\').
4276 unicode_translation(partial_function,'\x21F8\').
4277 unicode_translation(total_function,'\x2192\').
4278 unicode_translation(partial_injection,'\x2914\').
4279 unicode_translation(partial_surjection,'\x2900\').
4280 unicode_translation(total_injection,'\x21A3\').
4281 unicode_translation(total_surjection,'\x21A0\').
4282 unicode_translation(total_bijection,'\x2916\').
4283 unicode_translation('INTEGER','\x2124\').
4284 unicode_translation('NATURAL','\x2115\').
4285 unicode_translation('NATURAL1','\x2115\\x2081\'). % \x2115\ is subscript 1
4286 unicode_translation('REAL','\x211D\'). % 8477 in decimal
4287 unicode_translation(real_set,'\x211D\').
4288 %unicode_translation(bool_set,'\x1D539\'). % conversion used by IDP, but creates SPIO_E_ENCODING_INVALID problem
4289 unicode_translation(pow_subset,'\x2119\').
4290 unicode_translation(pow1_subset,'\x2119\\x2081\'). % \x2115\ is subscript 1
4291 unicode_translation(lambda,'\x3BB\').
4292 unicode_translation(general_product,'\x220F\').
4293 unicode_translation(general_sum,'\x2211\').
4294 unicode_translation(quantified_union,'\x22C3\'). % 8899 in decimal
4295 unicode_translation(quantified_intersection,'\x22C2\'). % 8898 in decimal
4296 unicode_translation(empty_set,'\x2205\').
4297 unicode_translation(truth,'\x22A4\'). % 8868 in decimal
4298 unicode_translation(falsity,'\x22A5\'). % 8869 in decimal
4299 unicode_translation(direct_product,'\x2297\').
4300 unicode_translation(parallel_product,'\x2225\').
4301 unicode_translation(reverse,'\x207B\\xB9\') :- \+ force_eventb_rodin_mode. % the one ¹ is ASCII 185
4302 % this symbol is not accepted by Rodin
4303 % unicode_translation(infinity,'\x221E\'). % 8734 in decimal
4304 unicode_translation(concat,'\x2312\'). % Arc character
4305 unicode_translation(insert_front,'\x21FE\').
4306 unicode_translation(insert_tail,'\x21FD\').
4307 unicode_translation(restrict_front,'\x2191\'). % up arrow
4308 unicode_translation(restrict_tail,'\x2192\').
4309 unicode_translation(forall, '\x2200\'). % usually forall_symbol used
4310 unicode_translation(exists, '\x2203\'). % usually exists_symbol used
4311 unicode_translation(eqeq,'\x225c\').
4312
4313 %unicode_translation(overwrite,'\xE103\'). % from kernel_lang_20.pdf
4314 unicode_translation(ring,'\x2218\'). % from Event-B
4315 unicode_translation(typeof,'\x2982\'). % Event-B oftype operator
4316
4317 % see Chapter 3 of Atelier-B prover manual:
4318 %atelierb_pp_translation(E,PP,_) :- write(pp(PP,E)),nl,fail.
4319 atelierb_pp_translation(set_minus,pp,'_moinsE'). % is set_subtraction ??
4320 atelierb_pp_translation(cartesian_product,pp,'_multE').
4321 atelierb_pp_translation('INTEGER',_,'INTEGER').
4322 %atelierb_pp_translation('INT','(MININT..MAXINT)'). % does not seem necessary
4323 atelierb_pp_translation('NATURAL',_,'NATURAL').
4324 atelierb_pp_translation('NATURAL1',_,'(NATURAL - {0})').
4325 atelierb_pp_translation('NAT1',_,'(NAT - {0})').
4326 %atelierb_pp_translation('NAT','(0..MAXINT)'). % does not seem necessary
4327 %atelierb_pp_translation('NAT1','(1..MAXINT)'). % does not seem necessary
4328 atelierb_pp_translation(truth,_,btrue).
4329 atelierb_pp_translation(falsity,_,bfalse).
4330 atelierb_pp_translation(boolean_true,_,'TRUE').
4331 atelierb_pp_translation(boolean_false,_,'FALSE').
4332 atelierb_pp_translation(empty_sequence,_,'{}').
4333
4334
4335
4336 quantified_in_mode(F,S) :-
4337 quantified(F,S1), translate_in_mode(F,S1,S).
4338
4339 translate_in_mode(F,S1,Result) :-
4340 ( unicode_mode, unicode_translation(F,S) -> true
4341 ; latex_mode, latex_translation(F,S) -> true
4342 ; atelierb_mode(prover(PPML)), atelierb_pp_translation(F,PPML,S) -> true
4343 ; colour_translation(F,S1,S) -> true
4344 ; S1=S),
4345 (colour_translation(F,S,Res) -> Result=Res ; Result=S).
4346
4347 :- use_module(tools_printing,[get_terminal_colour_code/2, no_color/0]).
4348 use_colour_codes :- \+ no_color,
4349 get_preference(pp_with_terminal_colour,true).
4350 colour_translation(F,S1,Result) :- use_colour_codes,
4351 colour_construct(F,Colour),!,
4352 get_terminal_colour_code(Colour,R1),
4353 get_terminal_colour_code(reset,R2),
4354 ajoin([R1,S1,R2],Result).
4355 colour_construct(pred_true,green).
4356 colour_construct(pred_false,red).
4357 colour_construct(boolean_true,green).
4358 colour_construct(boolean_false,red).
4359 colour_construct(truth,green).
4360 colour_construct(falsity,red).
4361 colour_construct(_,blue).
4362
4363 % pretty print a colour code if colours are enabled:
4364 pp_colour_code(Colour) --> {use_colour_codes,get_terminal_colour_code(Colour,C), atom_codes(C,CC)},!,CC.
4365 pp_colour_code(_) --> [].
4366
4367
4368 quantified(general_sum,'SIGMA').
4369 quantified(general_product,'PI').
4370 quantified(quantified_union,'UNION').
4371 quantified(quantified_intersection,'INTER').
4372 quantified(lambda,X) :- atom_codes(X,[37]).
4373 quantified(forall,'!').
4374 quantified(exists,'#').
4375
4376
4377 translate_prolog_constructor(C,R) :- unary_prefix(C,R,_),!.
4378 translate_prolog_constructor(C,R) :- unary_postfix(C,R,_),!.
4379 translate_prolog_constructor(C,R) :- binary_infix_in_mode(C,R,_,_),!.
4380 translate_prolog_constructor(C,R) :- function_like_in_mode(C,R),!.
4381 translate_prolog_constructor(C,R) :- constants_in_mode(C,R),!.
4382 translate_prolog_constructor(C,R) :- quantified_in_mode(C,R),!.
4383
4384 % translate the Prolog constuctor of an AST node into a form for printing to the user
4385 translate_prolog_constructor_in_mode(Constructor,Result) :-
4386 unicode_mode,
4387 unicode_translation(Constructor,Unicode),!, Result=Unicode.
4388 translate_prolog_constructor_in_mode(Constructor,Result) :-
4389 latex_mode,
4390 latex_translation(Constructor,Latex),!, Result=Latex.
4391 translate_prolog_constructor_in_mode(C,R) :- translate_prolog_constructor(C,R).
4392
4393 translate_subst_or_bexpr_in_mode(Mode,TExpr,String) :-
4394 with_translation_mode(Mode, translate_subst_or_bexpr(TExpr,String)).
4395
4396
4397 translate_bexpression_to_unicode(TExpr,String) :-
4398 with_translation_mode(unicode, translate_bexpression(TExpr,String)).
4399
4400 translate_bexpression(TExpr,String) :-
4401 (pp_expr(TExpr,String) -> true
4402 ; add_error(translate_bexpression,'Could not translate bexpression: ',TExpr),String='???').
4403
4404 translate_bexpression_to_codes(TExpr,Codes) :-
4405 reset_pp,
4406 pp_expr(TExpr,_,_LimitReached,Codes,[]).
4407
4408 pp_expr(TExpr,String) :-
4409 translate_bexpression_to_codes(TExpr,Codes),
4410 atom_codes_with_limit(String, Codes).
4411
4412 translate_bexpression_with_limit(T,S) :- translate_bexpression_with_limit(T,200,report_errors,S).
4413 translate_bexpression_with_limit(TExpr,Limit,String) :-
4414 translate_bexpression_with_limit(TExpr,Limit,report_errors,String).
4415 translate_bexpression_with_limit(TExpr,Limit,report_errors,String) :- compound(String),!,
4416 add_internal_error('Result is instantiated to a compound term:',
4417 translate_bexpression_with_limit(TExpr,Limit,report_errors,String)),fail.
4418 translate_bexpression_with_limit(TExpr,Limit,ReportErrors,String) :-
4419 (catch_call(pp_expr_with_limit(TExpr,Limit,String)) -> true
4420 ; (ReportErrors=report_errors,
4421 add_error(translate_bexpression,'Could not translate bexpression: ',TExpr),String='???')).
4422
4423 pp_expr_with_limit(TExpr,Limit,String) :-
4424 set_up_limit_reached(Codes,Limit,LimitReached),
4425 reset_pp,
4426 pp_expr(TExpr,_,LimitReached,Codes,[]),
4427 atom_codes_with_limit(String, Limit, Codes).
4428
4429
4430
4431 % pretty-type an expression, if the expression has a priority >MinPrio, parenthesis
4432 % can be ommitted, if not the expression has to be put into parenthesis
4433 pp_expr_m(TExpr,MinPrio,LimitReached,S,Srest) :-
4434 add_outer_paren(Prio,MinPrio,S,Srest,X,Xrest), % use co-routine to instantiate S as soon as possible
4435 pp_expr(TExpr,Prio,LimitReached,X,Xrest).
4436
4437 :- block add_outer_paren(-,?,?,?,?,?).
4438 add_outer_paren(Prio,MinPrio,S,Srest,X,Xrest) :-
4439 ( Prio > MinPrio -> % was >=, but problem with & / or with same priority or with non associative operators !
4440 S=X, Srest=Xrest
4441 ;
4442 [Open] = "(", [Close] = ")",
4443 S = [Open|X], Xrest = [Close|Srest]).
4444 % warning: if prio not set we will have a pending co-routine and instantiation_error in atom_codes later
4445
4446 :- use_module(translate_keywords,[classical_b_keyword/1, translate_keyword_id/2]).
4447 translated_identifier('_zzzz_binary',R) :- !,
4448 (latex_mode -> R='z''''' ; R='z__'). % TO DO: could cause clash with user IDs
4449 translated_identifier('_zzzz_unary',R) :- !,
4450 (latex_mode -> R='z''' ; R='z_'). % TO DO: ditto
4451 translated_identifier('__RANGE_LAMBDA__',R) :- !,
4452 (latex_mode -> R='\\rho\'' ; unicode_mode -> R= '\x03c1\' % RHO
4453 ; R = 'RANGE_LAMBDA__'). %ditto, could clash with user IDs !!
4454 % TO DO: do we need to treat _prj_arg1__, _prj_arg2__, _lambda_result_ here ?
4455 translated_identifier(ID,Result) :-
4456 latex_mode,!,
4457 my_greek_latex_escape_atom(ID,Greek,Res), %print_message(translate_latex(ID,Greek,Res)),
4458 (Greek=greek -> Result = Res ; ajoin(['\\mathit{',Res,'}'],Result)).
4459 translated_identifier(X,X).
4460
4461 pp_identifier(Atom) --> {id_requires_escaping(Atom), \+ eventb_translation_mode, \+ latex_mode}, !,
4462 ({atelierb_mode(_)}
4463 -> pp_identifier_for_atelierb(Atom)
4464 ; pp_backquoted_identifier(Atom)
4465 ).
4466 pp_identifier(Atom) --> ppatom_opt_scramble(Atom).
4467
4468 % print atom using backquotes, we use same escaping rules as in a string
4469 % requires B parser version 2.9.30 or newer
4470 pp_backquoted_identifier(Atom) --> {atom_codes(Atom,Codes)}, pp_backquoted_id_codes(Codes).
4471 pp_backquoted_id_codes(Codes) --> {append(Prefix,[0'. | Suffix],Codes), Suffix=[_|_]},
4472 !, % we need to split the id and quote each part separately; otherwise the parser will complain
4473 % see issue https://github.com/hhu-stups/prob-issues/issues/321
4474 % However, ids with dots are not accepted for constants and variables; so this does not solve all problems
4475 "`", pp_codes_opt_scramble(Prefix), "`.", % TODO: we could check if id_requires_escaping
4476 pp_backquoted_id_codes(Suffix).
4477 pp_backquoted_id_codes(Codes) --> "`", pp_codes_opt_scramble(Codes), "`".
4478
4479 :- use_module(tools_strings,[is_simple_classical_b_identifier/1]).
4480 id_requires_escaping(ID) :- classical_b_keyword(ID).
4481 id_requires_escaping(ID) :- \+ is_simple_classical_b_identifier(ID).
4482
4483 pp_identifier_for_atelierb(Atom) -->
4484 {atom_codes(Atom,Codes),
4485 strip_illegal_id_codes(Codes,Change,Codes2),
4486 Change==true},!,
4487 {atom_codes(A2,Codes2)},
4488 ppatom_opt_scramble(A2).
4489 pp_identifier_for_atelierb(Atom) --> ppatom_opt_scramble(Atom).
4490
4491 % remove illegal codes in an identifier (probably EventB or Z)
4492 strip_illegal_id_codes([0'_ | T ],Change,[946 | TR]) :- !, Change=true, strip_illegal_id_codes(T,_,TR).
4493 strip_illegal_id_codes(Codes,Change,Res) :- strip_illegal_id_codes2(Codes,Change,Res).
4494
4495 strip_illegal_id_codes2([],_,[]).
4496 strip_illegal_id_codes2([H|T],Change,Res) :- strip_code(H,Res,TR),!, Change=true, strip_illegal_id_codes2(T,_,TR).
4497 strip_illegal_id_codes2([H|T],Change,[H|TR]) :- strip_illegal_id_codes2(T,Change,TR).
4498
4499 strip_code(46,[0'_, 0'_ |T],T). % replace dot . by two underscores
4500 strip_code(36,[946|T],T) :- T \= [48]. % replace dollar $ by beta unless it is $0 at the end
4501 strip_code(92,[950|T],T). % replace dollar by zeta; probably from Zed
4502 % TODO: add more symbols and ensure that the new codes do not exist
4503
4504
4505
4506 :- use_module(tools,[latex_escape_atom/2]).
4507
4508 greek_or_math_symbol(Symbol) :- greek_symbol(Symbol,_).
4509 % other Latex math symbols
4510 greek_or_math_symbol('varepsilon').
4511 greek_or_math_symbol('varphi').
4512 greek_or_math_symbol('varpi').
4513 greek_or_math_symbol('varrho').
4514 greek_or_math_symbol('varsigma').
4515 greek_or_math_symbol('vartheta').
4516 greek_or_math_symbol('vdash').
4517 greek_or_math_symbol('models').
4518
4519 greek_symbol('Alpha','\x0391\').
4520 greek_symbol('Beta','\x0392\').
4521 greek_symbol('Chi','\x03A7\').
4522 greek_symbol('Delta','\x0394\').
4523 greek_symbol('Epsilon','\x0395\').
4524 greek_symbol('Eta','\x0397\').
4525 greek_symbol('Gamma','\x0393\').
4526 greek_symbol('Iota','\x0399\').
4527 greek_symbol('Kappa','\x039A\').
4528 greek_symbol('Lambda','\x039B\').
4529 greek_symbol('Mu','\x039C\').
4530 greek_symbol('Nu','\x039D\').
4531 greek_symbol('Phi','\x03A6\').
4532 greek_symbol('Pi','\x03A0\').
4533 greek_symbol('Psi','\x03A8\').
4534 greek_symbol('Rho','\x03A1\').
4535 greek_symbol('Omega','\x03A9\').
4536 greek_symbol('Omicron','\x039F\').
4537 greek_symbol('Sigma','\x03A3\').
4538 greek_symbol('Theta','\x0398\').
4539 greek_symbol('Upsilon','\x03A5\').
4540 greek_symbol('Xi','\x039E\').
4541 greek_symbol('alpha','\x03B1\').
4542 greek_symbol('beta','\x03B2\').
4543 greek_symbol('delta','\x03B4\').
4544 greek_symbol('chi','\x03C7\').
4545 greek_symbol('epsilon','\x03B5\').
4546 greek_symbol('eta','\x03B7\').
4547 greek_symbol('gamma','\x03B3\').
4548 greek_symbol('iota','\x03B9\').
4549 greek_symbol('kappa','\x03BA\').
4550 greek_symbol('lambda','\x03BB\').
4551 greek_symbol('mu','\x03BC\').
4552 greek_symbol('nu','\x03BD\').
4553 greek_symbol('omega','\x03C9\').
4554 greek_symbol('omicron','\x03BF\').
4555 greek_symbol('pi','\x03C0\').
4556 greek_symbol('phi','\x03C6\').
4557 greek_symbol('psi','\x03C8\').
4558 greek_symbol('rho','\x03C1\').
4559 greek_symbol('sigma','\x03C3\').
4560 greek_symbol('tau','\x03C4\').
4561 greek_symbol('theta','\x03B8\').
4562 greek_symbol('upsilon','\x03C5\').
4563 greek_symbol('xi','\x03BE\').
4564 greek_symbol('zeta','\x03B6\').
4565
4566
4567 my_greek_latex_escape_atom(A,greek,Res) :-
4568 greek_or_math_symbol(A),get_preference(latex_pp_greek_ids,true),!,
4569 atom_concat('\\',A,Res).
4570 my_greek_latex_escape_atom(A,no_greek,EA) :- latex_escape_atom(A,EA).
4571
4572 % ppatom + scramble if BUGYLY is TRUE
4573 ppatom_opt_scramble(Name) --> {get_preference(bugly_pp_scrambling,true)},
4574 % {\+ bmachine:b_top_level_operation(Name)}, % comment in to not change name of B operations
4575 !,
4576 {bugly_scramble_id(Name,ScrName)},
4577 ppatom(ScrName).
4578 ppatom_opt_scramble(Name) -->
4579 {primes_to_unicode(Name, UnicodeName)},
4580 pp_atom_opt_latex(UnicodeName).
4581
4582 % Convert ASCII primes (apostrophes) in identifiers to Unicode primes
4583 % so they can be parsed by the classical B parser.
4584 primes_to_unicode(Name, UnicodeName) :-
4585 atom_codes(Name, Codes),
4586 phrase(primes_to_unicode(Codes), UCodes),
4587 atom_codes(UnicodeName, UCodes).
4588 primes_to_unicode([0'\'|T]) --> !,
4589 "\x2032\",
4590 primes_to_unicode(T).
4591 primes_to_unicode([C|T]) --> !,
4592 [C],
4593 primes_to_unicode(T).
4594 primes_to_unicode([]) --> "".
4595
4596 :- use_module(tools,[b_string_escape_codes/2]).
4597 :- use_module(tools_strings,[convert_atom_to_number/2]).
4598 % a version of ppatom which encodes/quotes symbols inside strings such as quotes "
4599 ppstring_opt_scramble(Name) --> {var(Name)},!,ppatom(Name).
4600 ppstring_opt_scramble(Name) --> {compound(Name)},!,
4601 {add_internal_error('Not an atom: ',ppstring_opt_scramble(Name,_,_))},
4602 "<<" ,ppterm(Name), ">>".
4603 ppstring_opt_scramble(Name) --> {get_preference(bugly_pp_scrambling,true)},!,
4604 pp_bugly_composed_string(Name).
4605 ppstring_opt_scramble(Name) --> {atom_codes(Name,Codes),b_string_escape_codes(Codes,EscCodes)},
4606 pp_codes_opt_latex(EscCodes).
4607
4608 % a version of ppstring_opt_scramble with codes list
4609 pp_codes_opt_scramble(Codes) --> {get_preference(bugly_pp_scrambling,true)},!,
4610 pp_bugly_composed_string_codes(Codes,[]).
4611 pp_codes_opt_scramble(Codes) --> {b_string_escape_codes(Codes,EscCodes)},
4612 pp_codes_opt_latex(EscCodes).
4613
4614 pp_bugly_composed_string(Name) --> {atom_codes(Name,Codes)},
4615 !, % we can decompose the string; scramble each string separately; TODO: provide option to define separators
4616 % idea is that if we have a string with spaces or other special separators we preserve the separators
4617 pp_bugly_composed_string_codes(Codes,[]).
4618
4619 pp_bugly_composed_string_codes([],Acc) --> {atom_codes(Atom,Acc)}, pp_bugly_string(Atom).
4620 pp_bugly_composed_string_codes(List,Acc) --> {decompose_string(List,Seps,T)},!,
4621 {reverse(Acc,Rev),atom_codes(Atom,Rev)}, pp_bugly_string(Atom),
4622 ppcodes(Seps),
4623 pp_bugly_composed_string_codes(T,[]).
4624 pp_bugly_composed_string_codes([H|T],Acc) --> pp_bugly_composed_string_codes(T,[H|Acc]).
4625
4626 decompose_string([Sep|T],[Sep],T) :- bugly_separator(Sep).
4627 % comment in and adapt for domain specific separators:
4628 %decompose_string(List,Seps,T) :- member(Seps,["LEU","DEF","BAL"]), append(Seps,T,List).
4629 %bugly_separator(10).
4630 %bugly_separator(13).
4631 bugly_separator(32).
4632 bugly_separator(0'-).
4633 bugly_separator(0'_).
4634 bugly_separator(0',).
4635 bugly_separator(0'.).
4636 bugly_separator(0';).
4637 bugly_separator(0':).
4638 bugly_separator(0'#).
4639 bugly_separator(0'[).
4640 bugly_separator(0']).
4641 bugly_separator(0'().
4642 bugly_separator(0')).
4643
4644 % scramble and pretty print individual strings or components of strings
4645 pp_bugly_string('') --> !, [].
4646 pp_bugly_string(Name) -->
4647 {convert_atom_to_number(Name,_)},!, % do not scramble numbers; we could check if LibraryStrings is available
4648 pp_atom_opt_latex(Name).
4649 pp_bugly_string(Name) -->
4650 {bugly_scramble_id(Name,ScrName)},
4651 ppatom(ScrName).
4652
4653 % ------------
4654
4655 pp_atom_opt_latex(Name) --> {latex_mode},!,
4656 {my_greek_latex_escape_atom(Name,_,EscName)},
4657 % should we add \mathrm{.} or \mathit{.}?
4658 ppatom(EscName).
4659 pp_atom_opt_latex(Name) --> ppatom(Name).
4660
4661 % a version of pp_atom_opt_latex working with codes
4662 pp_codes_opt_latex(Codes) --> {latex_mode},!,
4663 {atom_codes(Name,Codes),my_greek_latex_escape_atom(Name,_,EscName)},
4664 ppatom(EscName).
4665 pp_codes_opt_latex(Codes) --> ppcodes(Codes).
4666
4667 pp_atom_opt_latex_mathit(Name) --> {latex_mode},!,
4668 {latex_escape_atom(Name,EscName)},
4669 "\\mathit{",ppatom(EscName),"}".
4670 pp_atom_opt_latex_mathit(Name) --> ppatom(Name).
4671
4672 pp_atom_opt_mathit(EscName) --> {latex_mode},!,
4673 % we assume already escaped
4674 "\\mathit{",ppatom(EscName),"}".
4675 pp_atom_opt_mathit(Name) --> ppatom(Name).
4676
4677 pp_space --> {latex_mode},!, "\\ ".
4678 pp_space --> " ".
4679
4680 opt_scramble_id(ID,Res) :- get_preference(bugly_pp_scrambling,true),!,
4681 bugly_scramble_id(ID,Res).
4682 opt_scramble_id(ID,ID).
4683
4684 :- use_module(probsrc(gensym),[gensym/2]).
4685 :- dynamic bugly_scramble_id_cache/2.
4686 bugly_scramble_id(ID,Res) :- var(ID),!, add_internal_error('Illegal call: ',bugly_scramble_id(ID,Res)), ID=Res.
4687 bugly_scramble_id(ID,Res) :- bugly_scramble_id_cache(ID,ScrambledID),!,
4688 Res=ScrambledID.
4689 bugly_scramble_id(ID,Res) :- %print(gen_id(ID,Res)),nl,
4690 genbuglynr(Nr),
4691 gen_bugly_id(Nr,ScrambledID),
4692 assertz(bugly_scramble_id_cache(ID,ScrambledID)),
4693 %format(user_output,'BUGLY scramble ~w --> ~w~n',[ID,ScrambledID]),
4694 Res = ScrambledID.
4695
4696 gen_bugly_id_codes(Nr,[Char|TC]) :- Char is 97+ Nr mod 26,
4697 (Nr> 25 -> N1 is Nr // 26, gen_bugly_id_codes(N1,TC) ; TC=[]).
4698 gen_bugly_id(Nr,ScrambledID) :- gen_bugly_id_codes(Nr,Codes), atom_codes(ScrambledID,[97,97|Codes]).
4699 %gen_bugly_id(Nr,ScrambledID) :- ajoin(['aa',Nr],ScrambledID). % old version using aaNr
4700
4701 :- dynamic bugly_count/1.
4702 bugly_count(0).
4703 genbuglynr(Nr) :-
4704 retract(bugly_count(Nr)), N1 is Nr + 1,
4705 assertz(bugly_count(N1)).
4706
4707
4708 is_lambda_result_id(b(identifier(ID),_,_INFO),Suffix) :- % _INFO=[lambda_result], sometiems _INFO=[]
4709 is_lambda_result_name(ID,Suffix).
4710 is_lambda_result_name(LAMBDA_RESULT,Suffix) :- atomic(LAMBDA_RESULT),
4711 atom_codes(LAMBDA_RESULT,[95,108,97,109,98,100,97,95,114,101,115,117,108,116,95|Suffix]). % _lambda_result_
4712
4713 pp_expr(TE,P) --> %{print('OBSOLETE'),nl,nl},
4714 pp_expr(TE,P,_LimitReached).
4715
4716 pp_expr(TExpr,Prio,_) --> {var(TExpr)},!,"_",{Prio=500}.
4717 pp_expr(_,Prio,LimitReached) --> {LimitReached==limit_reached},!,"...",{Prio=500}.
4718 pp_expr(b(Expr,Type,Info),Prio,LimitReached) --> !,
4719 pp_expr0(Expr,Type,Info,Prio,LimitReached).
4720 pp_expr(Expr,Prio,LimitReached) -->
4721 pp_expr1(Expr,any,[],Prio,LimitReached).
4722
4723 pp_expr0(identifier(ID),_Type,_Info,Prio,_LimitReached) --> {is_lambda_result_name(ID,Suffix)},!, {Prio=500},
4724 {append("LAMBDA_RESULT___",Suffix,ASCII), atom_codes(R,ASCII)}, ppatom(R).
4725 pp_expr0(Expr,_Type,Info,Prio,_LimitReached) -->
4726 {eventb_translation_mode},
4727 pp_theory_operator(Expr,Info,Prio),!.
4728 pp_expr0(Expr,Type,Info,Prio,LimitReached) -->
4729 {check_info(Expr,Type,Info)},
4730 pp_rodin_label(Info),
4731 (pp_expr1(Expr,Type,Info,Prio,LimitReached) -> {true}
4732 ; {add_error(translate,'Could not translate:',Expr,Expr),fail}
4733 ).
4734
4735 check_info(Expr,_,Info) :- var(Info), add_error(translate,'Illegal variable info field for expression: ', Expr),fail.
4736 check_info(_,_,_).
4737
4738 pp_theory_operator(general_sum(_,Membercheck,_),_Info,500) -->
4739 {get_texpr_expr(Membercheck,member(_,Arg))},
4740 ppatom('SUM('),pp_expr(Arg,_),ppatom(')').
4741 pp_theory_operator(general_product(_,Membercheck,_),_Info,500) -->
4742 {get_texpr_expr(Membercheck,member(_Couple,Arg))},
4743 ppatom('PRODUCT('),pp_expr(Arg,_),ppatom(')').
4744 pp_theory_operator(function(_,Arg),Info,500) -->
4745 {memberchk_in_info(theory_operator(O,N),Info),decouplise_expr(N,Arg,Args)},
4746 ppatom(O),"(",pp_expr_l_sep(Args,",",_LR),")".
4747 pp_theory_operator(member(Arg,_),Info,500) -->
4748 {memberchk_in_info(theory_operator(O,N),Info),decouplise_expr(N,Arg,Args)},
4749 ppatom(O),"(",pp_expr_l_sep(Args,",",_LR),")".
4750
4751 decouplise_expr(1,E,R) :- !,R=[E].
4752 decouplise_expr(N,E,R) :-
4753 get_texpr_expr(E,couple(A,B)),!,
4754 N2 is N-1,
4755 decouplise_expr(N2,A,R1),append(R1,[B],R).
4756 decouplise_expr(N,E,[E]) :-
4757 print_message(call_failed(decouplise_expr(N,E,_))),nl.
4758
4759 % will pretty print (first) rodin or pragma label
4760 pp_rodin_label(_Infos) --> {preference(translate_suppress_rodin_positions_flag,true),!}.
4761 pp_rodin_label(_Infos) --> {preference(bugly_pp_scrambling,true),!}.
4762 pp_rodin_label(Infos) --> {var(Infos)},!, "/* ILLEGAL VARIABLE INFO FIELD */".
4763 pp_rodin_label(Infos) --> {get_info_labels(Infos,Label)},!,
4764 pp_start_label_pragma,
4765 ppatoms_opt_latex(Label),
4766 pp_end_label_pragma.
4767 pp_rodin_label(Infos) --> {preference(pp_wd_infos,true)},!, pp_wd_info(Infos).
4768 pp_rodin_label(_Infos) --> [].
4769
4770 % print infos about well-definedness attached to AST node:
4771 pp_wd_info(Infos) --> {member(discharged_wd_po,Infos)},!, "/*D",
4772 ({member(contains_wd_condition,Infos)} -> "-WD*/ " ; "*/ ").
4773 pp_wd_info(Infos) --> {member(contains_wd_condition,Infos)},!, "/*WD*/ ".
4774 pp_wd_info(_Infos) --> [].
4775
4776 pp_start_label_pragma -->
4777 {(atelierb_mode(prover(_))
4778 ; get_preference(translate_print_typing_infos,true))}, % proxy for parseable;
4779 % set by translate_bvalue_to_parseable_classicalb; important for parsertests with labels
4780 !,
4781 "/*@label ".
4782 pp_start_label_pragma --> "/* @". % shorter version, for viewing in UI
4783 pp_end_label_pragma --> " */ ".
4784
4785 ppatoms([]) --> !, [].
4786 ppatoms([ID|T]) --> !,ppatom(ID), " ", ppatoms(T).
4787 ppatoms(X) --> {add_error(ppatoms,'Not a list of atoms: ',ppatoms(X))}.
4788
4789 ppatoms_opt_latex([]) --> !, [].
4790 ppatoms_opt_latex([ID]) --> !,pp_atom_opt_latex(ID).
4791 ppatoms_opt_latex([ID|T]) --> !,pp_atom_opt_latex(ID), " ", ppatoms_opt_latex(T).
4792 ppatoms_opt_latex(X) --> {add_error(ppatoms_opt_latex,'Not a list of atoms: ',ppatoms_opt_latex(X))}.
4793
4794 %:- use_module(bsyntaxtree,[is_set_type/2]).
4795 :- load_files(library(system), [when(compile_time), imports([environ/2])]).
4796 pp_expr1(Expr,_,_,Prio,_) --> {var(Expr)},!,"_",{Prio=500}.
4797 pp_expr1(event_b_comprehension_set(Ids,E,P),Type,_Info,Prio,LimitReached) -->
4798 {b_ast_cleanup:rewrite_event_b_comprehension_set(Ids,E,P,Type, NewExpression)},!,
4799 pp_expr(NewExpression,Prio,LimitReached).
4800 pp_expr1(union(b(event_b_identity,Type,_), b(closure(Rel),Type,_)),_,Info,500,LimitReached) -->
4801 /* closure(Rel) = id \/ closure1(Rel) */
4802 ? {member_in_info(was(reflexive_closure),Info)},!,
4803 "closure(",pp_expr(Rel,_,LimitReached),")".
4804 pp_expr1(comprehension_set([_],_),_,Info,500,_LimitReached) -->
4805 {memberchk_in_info(freetype(P),Info),!},ppatom(P).
4806 % used instead of constants(Expr,Symbol) case below:
4807 pp_expr1(greater_equal(A,Y),Type,Info,Prio,LimitReached) --> % x:NATURAL was rewritten to x>=0, see test 499, 498
4808 {memberchk_in_info(was(member(A,B)),Info), get_integer(Y,_)},
4809 pp_expr1(member(A,B),Type,Info,Prio,LimitReached).
4810 pp_expr1(comprehension_set([TID],b(B,_,_)),Type,Info,Prio,LimitReached) -->
4811 {memberchk_in_info(was(integer_set(S)),Info)},
4812 {S='INTEGER' -> B=truth
4813 ; get_texpr_id(TID,ID),
4814 B=greater_equal(TID2,Y), get_integer(Y,I),
4815 get_texpr_id(TID2,ID),
4816 (I=0 -> S='NATURAL' ; I=1,S='NATURAL1')}, % TO DO: check bounds
4817 !,
4818 pp_expr1(integer_set(S),Type,Info,Prio,LimitReached).
4819 pp_expr1(interval(b(A,_,_),B),Type,Info,Prio,LimitReached) -->
4820 {memberchk_in_info(was(integer_set(S)),Info)},
4821 {B=b(max_int,integer,_)}, % TO DO ? allow value(int(Mx))
4822 {A=min_int -> S='INT' ; A=integer(0) -> S='NAT' ; A=integer(1),S='NAT1'},
4823 !,
4824 pp_expr1(integer_set(S),Type,Info,Prio,LimitReached).
4825 pp_expr1(falsity,_,Info,Prio,LimitReached) --> {memberchk_in_info(was(Pred),Info)},!,
4826 ({(unicode_mode ; latex_mode)}
4827 -> {translate_in_mode(falsity,'falsity',Symbol)},
4828 ppatom(Symbol),
4829 ({get_preference(pp_propositional_logic_mode,true)} -> {true}
4830 ; " ", enter_comment, " ", pp_expr2(Pred,Prio,LimitReached), " ", exit_comment)
4831 ; enter_comment, " falsity ",exit_comment, " ",
4832 pp_expr2(Pred,Prio,LimitReached)). % Pred is not wrapped
4833 pp_expr1(truth,_,Info,Prio,LimitReached) --> {memberchk_in_info(was(Pred),Info)},!,
4834 ({(unicode_mode ; latex_mode)}
4835 -> {translate_in_mode(truth,'truth',Symbol)},
4836 ppatom(Symbol),
4837 ({get_preference(pp_propositional_logic_mode,true)} -> {true}
4838 ; " ",enter_comment, " ", pp_expr2(Pred,Prio,LimitReached), " ", exit_comment)
4839 ; enter_comment, " truth ", exit_comment, " ",
4840 pp_expr2(Pred,Prio,LimitReached)). % Pred is not wrapped
4841 % TO DO: do this for other expressions as well; but then we have to ensure that ast_cleanup generates complete was(_) infos
4842 % :- load_files(library(system), [when(compile_time), imports([environ/2])]). % directive moved above to avoid Spider warning
4843 pp_expr1(event_b_identity,Type,_Info,500,_LimitReached) -->
4844 {\+ eventb_translation_mode}, %{atelierb_mode(prover(_)},
4845 {is_set_type(Type,couple(ElType,ElType))},
4846 !,
4847 "id(", {pretty_normalized_type(ElType,S)},ppatom(S), ")".
4848 pp_expr1(typeset,SType,_Info,500,_LimitReached) --> % normally removed by ast_cleanup
4849 {is_set_type(SType,Type)},
4850 !,
4851 ({normalized_type_requires_outer_paren(Type)} -> "(" ; ""),
4852 {pretty_normalized_type(Type,S)},ppatom(S),
4853 ({normalized_type_requires_outer_paren(Type)} -> ")" ; "").
4854 :- if(environ(prob_safe_mode,true)).
4855 pp_expr1(exists(Parameters,_),_,Info,_Prio,_LimitReached) -->
4856 {\+ member_in_info(used_ids(_),Info),
4857 add_error(translate,'Missing used_ids Info for exists: ',Parameters:Info),fail}.
4858 %pp_expr1(exists(Ids,P1),_,Info,250) --> !, { member_in_info(used_ids(Used),Info)},
4859 % exists_symbol,pp_expr_ids_in_mode(Ids,LimitReached),
4860 % {add_normal_typing_predicates(Ids,P1,P)},
4861 % " /* Used = ", ppterm(Used), " */ ",
4862 % ".",pp_expr_m(P,221).
4863 :- endif.
4864 pp_expr1(Expr,Type,Info,Prio,LimitReached) --> {member_in_info(sharing(ID,Count,_,_),Info),number(Count),Count>1},!,
4865 "( ",enter_comment," CSE ",ppnumber(ID), ":#", ppnumber(Count),
4866 ({member_in_info(negated_cse,Info)} -> " (neg) " ; " "),
4867 ({member_in_info(contains_wd_condition,Info)} -> " (wd) " ; " "),
4868 exit_comment, " ",
4869 {delete(Info,sharing(_,_,_,_),Info2)},
4870 pp_expr1(Expr,Type,Info2,Prio,LimitReached), ")".
4871 %pp_expr1(Expr,_,Info,Prio) --> {member_in_info(contains_wd_condition,Info)},!,
4872 % "( /* (wd) */ ", pp_expr2(Expr,Prio), ")".
4873 % pp_expr1(Expr,subst,_Info,Prio) --> !, translate_subst2(Expr,Prio). % TO DO: also allow substitutions here
4874 pp_expr1(value(V),Type,_,Prio,LimitReached) --> !,
4875 {(nonvar(V),V=closure(_,_,_) -> Prio=300 ; Prio=500)}, pp_value_with_type(V,Type,LimitReached).
4876 pp_expr1(comprehension_set(Ids,P1),_,Info,500,LimitReached) --> !,
4877 pp_comprehension_set(Ids,P1,Info,LimitReached).
4878 %pp_expr1(Expr,_,Info,Prio,LimitReached) --> {pp_is_important_info_field(Expr,Info,_)},
4879 % !, pp_important_infos(Expr,Info), pp_expr2(Expr,Prio,LimitReached).
4880 pp_expr1(first_of_pair(X),_,Info,500,LimitReached) --> {was_eventb_destructor(Info,X,Op,Arg)},!,
4881 ppatom(Op), "(",pp_expr(Arg,_,LimitReached), ")".
4882 pp_expr1(second_of_pair(X),_,Info,500,LimitReached) --> {was_eventb_destructor(Info,X,Op,Arg)},!,
4883 ppatom(Op), "(",pp_expr(Arg,_,LimitReached), ")".
4884 %pp_expr1(let_expression(_Ids,Exprs,_P),_Type,Info,500,LimitReached) -->
4885 % % pretty print direct definition operator calls, which get translated using create_z_let
4886 % % However: the lets can get removed; in which case the translated direct definition will be pretty printed
4887 % % also: what if the body of the let has been modified ??
4888 % {member(was(extended_expr(DirectDefOp)),Info),
4889 % bmachine_eventb:stored_operator_direct_definition(DirectDefOp,_Proj,_Theory,Parameters,_Def,_WD,_TypeParas,_Kind),
4890 % %length(Exprs,Arity),,length(Parameters,Arity1), write(found_dd(DirectDefOp,Arity1,Arity2,Proj,Theory)),nl,
4891 % same_length(Parameters,ActualParas), %same_length(TypeParameters,TP),
4892 % append(ActualParas,_TP,Exprs)
4893 % },
4894 % !,
4895 % ppatom(DirectDefOp),
4896 % pp_expr_wrap_l('(',ActualParas,')',LimitReached).
4897 pp_expr1(Expr,_,_Info,Prio,LimitReached) --> pp_expr2(Expr,Prio,LimitReached).
4898
4899 was_eventb_destructor(Info,X,Op,Arg) :- eventb_translation_mode,
4900 member(was(extended_expr(Op)),Info),peel_projections(X,Arg).
4901 is_projection(first_of_pair(A),A).
4902 is_projection(second_of_pair(A),A).
4903 % peel projections constructed for Event-B destructor operator
4904 peel_projections(b(A,_,_),R) :-
4905 (is_projection(A,RA) -> peel_projections(RA,R)
4906 ; A = freetype_destructor(_,_,R)).
4907
4908
4909 :- public pp_important_infos/4. % debugging utility
4910 pp_important_infos(Expr,Info) -->
4911 {findall(PPI,pp_is_important_info_field(Expr,Info,PPI),PPInfos), PPInfos \= []},
4912 " ", enter_comment, ppterm(PPInfos), exit_comment, " ".
4913 pp_is_important_info_field(_,Infos,'DO_NOT_ENUMERATE'(X)) :- member(prob_annotation('DO_NOT_ENUMERATE'(X)),Infos).
4914 pp_is_important_info_field(exists(_,_),Infos,'LIFT') :- member(allow_to_lift_exists,Infos).
4915 pp_is_important_info_field(exists(_,_),Infos,used_ids(Used)) :- member(used_ids(Used),Infos).
4916 pp_is_important_info_field(exists(_,_),Infos,'(wd)') :- member(contains_wd_condition,Infos).
4917
4918
4919 pp_expr2(Expr,_,_LimitReached) --> {var(Expr)},!,"_".
4920 pp_expr2(_,_,LimitReached) --> {LimitReached==limit_reached},!,"...".
4921 pp_expr2(atom_string(V),500,_) --> !,pp_atom_opt_latex_mathit(V). % hardwired_atom
4922 pp_expr2(global_set(V),500,_) --> !, pp_identifier(V).
4923 pp_expr2(freetype_set(V),500,_) --> !,{pretty_freetype(V,P)},ppatom_opt_scramble(P).
4924 pp_expr2(lazy_lookup_expr(I),500,_) --> !, pp_identifier(I).
4925 pp_expr2(lazy_lookup_pred(I),500,_) --> !, pp_identifier(I).
4926 pp_expr2(identifier(I),500,_) --> !,
4927 {( I=op(Id) -> true; I=Id)},
4928 ( {atomic(Id)} -> ({translated_identifier(Id,TId)},
4929 ({latex_mode} -> ppatom(TId) ; pp_identifier(TId)))
4930 ;
4931 "'",ppterm(Id), "'").
4932 pp_expr2(integer(N),500,_) --> !, ppnumber(N).
4933 pp_expr2(real(N),500,_) --> !, ppatom(N).
4934 pp_expr2(integer_set(S),500,_) --> !,
4935 {integer_set_mapping(S,T)},ppatom(T).
4936 pp_expr2(string(S),500,_) --> !, string_start_symbol, ppstring_opt_scramble(S), string_end_symbol.
4937 pp_expr2(set_extension(Ext),500,LimitReached) --> !, {set_brackets(L,R)},
4938 pp_expr_wrap_l(L,Ext,R,LimitReached).
4939 pp_expr2(sequence_extension(Ext),500,LimitReached) --> !,
4940 pp_begin_sequence,
4941 ({get_preference(translate_print_cs_style_sequences,true)} -> pp_expr_l_sep(Ext,"",LimitReached)
4942 ; pp_expr_l_sep(Ext,",",LimitReached)),
4943 pp_end_sequence.
4944 pp_expr2(assign(LHS,RHS),10,LimitReached) --> !,
4945 pp_expr_wrap_l(',',LHS,'',LimitReached), ":=", pp_expr_wrap_l(',',RHS,'',LimitReached).
4946 pp_expr2(assign_single_id(LHS,RHS),10,LimitReached) --> !, pp_expr2(assign([LHS],[RHS]),10,LimitReached).
4947 pp_expr2(parallel(RHS),10,LimitReached) --> !,
4948 pp_expr_wrap_l('||',RHS,'',LimitReached).
4949 pp_expr2(sequence(RHS),10,LimitReached) --> !,
4950 pp_expr_wrap_l(';',RHS,'',LimitReached).
4951 pp_expr2(event_b_comprehension_set(Ids,E,P1),500,LimitReached) --> !, % normally conversion above should trigger; this is if we call pp_expr for untyped expressions
4952 pp_event_b_comprehension_set(Ids,E,P1,LimitReached).
4953 pp_expr2(recursive_let(Id,S),500,LimitReached) --> !,
4954 ({eventb_translation_mode} -> "" % otherwise we get strange characters in Rodin
4955 ; enter_comment," recursive ID ", pp_expr(Id,_,LimitReached), " ", exit_comment),
4956 pp_expr(S,_,LimitReached).
4957 pp_expr2(image(A,B),300,LimitReached) --> !,
4958 pp_expr_m(A,249,LimitReached),"[", % was 0; but we may have to bracket A; e.g., f <| {2} [{2}] is not ok; 250 is priority of lambda
4959 pp_expr_m(B,0,LimitReached),"]". % was 500, now set to 0: we never need an outer pair of () !?
4960 pp_expr2(function(A,B),300,LimitReached) --> !,
4961 pp_expr_m(A,249,LimitReached), % was 0; but we may have to bracket A; e.g., f <| {2} (2) is not ok; 250 is priority of lambda
4962 pp_function_left_bracket,
4963 pp_expr_m(B,0,LimitReached), % was 500, now set to 0: we never need an outer pair of () !?
4964 pp_function_right_bracket.
4965 pp_expr2(definition(A,B),300,LimitReached) --> !, % definition call; usually inlined,...
4966 ppatom(A),
4967 pp_function_left_bracket,
4968 pp_expr_l_sep(B,",",LimitReached),
4969 pp_function_right_bracket.
4970 pp_expr2(operation_call_in_expr(A,B),300,LimitReached) --> !,
4971 pp_expr_m(A,249,LimitReached),
4972 pp_function_left_bracket,
4973 pp_expr_l_sep(B,",",LimitReached),
4974 pp_function_right_bracket.
4975 pp_expr2(enumerated_set_def(GS,ListEls),200,LimitReached) --> !, % for pretty printing enumerate set defs
4976 {reverse(ListEls,RLE)}, /* they have been inserted in inverse order */
4977 pp_identifier(GS), "=", pp_expr_wrap_l('{',RLE,'}',LimitReached).
4978 pp_expr2(forall(Ids,D1,P),Prio,LimitReached) --> !,
4979 ({eventb_translation_mode} -> {Prio=60} ; {Prio=250}), % in Rodin forall/exists cannot be mixed with &, or, <=>, ...
4980 forall_symbol,pp_expr_ids_in_mode(Ids,LimitReached),
4981 {add_normal_typing_predicates(Ids,D1,D)},
4982 dot_symbol,pp_expr_m(b(implication(D,P),pred,[]),221,LimitReached).
4983 pp_expr2(exists(Ids,P1),Prio,LimitReached) --> !,
4984 ({eventb_translation_mode} -> {Prio=60} ; {Prio=250}), % exists has Prio 250, but dot has 220
4985 exists_symbol,pp_expr_ids_in_mode(Ids,LimitReached),
4986 {add_normal_typing_predicates(Ids,P1,P)},
4987 dot_symbol,
4988 ({eventb_translation_mode} -> {MinPrio=29} ; {MinPrio=500}),
4989 % used to be 221, but #x.x>7 or #x.not(...) are not parsed by Atelier-B or ProB, x.x and x.not are parsed as composed identifiers
4990 % In Event-B ∃y·y>x ∧ (y=x+1 ∨ y=x+2) is valid and requires no outer parenthesis
4991 pp_expr_m(P,MinPrio,LimitReached).
4992 pp_expr2(record_field(R,I),250,LimitReached) --> !,
4993 pp_expr_m(R,251,LimitReached),"'",pp_identifier(I).
4994 pp_expr2(rec(Fields),500,LimitReached) --> !,
4995 {function_like_in_mode(rec,Symbol)},
4996 ppatom(Symbol), "(",pp_expr_fields(Fields,LimitReached),")".
4997 pp_expr2(struct(Rec),500,LimitReached) -->
4998 {get_texpr_expr(Rec,rec(Fields)),Val=false ; get_texpr_expr(Rec,value(rec(Fields)))},!,
4999 {function_like_in_mode(struct,Symbol)},
5000 ppatom(Symbol), "(",
5001 ({Val==false} -> pp_expr_fields(Fields,LimitReached)
5002 ; pp_value_l(Fields,',',LimitReached)),
5003 ")".
5004 pp_expr2(freetype_case(_FT,L,Expr),Prio,LimitReached) --> !,
5005 %{Prio=500}, pp_freetype_term('__is_ft_case',FT,L,Expr,LimitReached).
5006 % we now pretty-print it as Expr : ran(L) assuming there is a constant L generated for every case
5007 {FTCons = b(identifier(L),any,[]), RanFTCons = b(range(FTCons),any,[])},
5008 pp_expr(b(member(Expr,RanFTCons),pred,[]),Prio,LimitReached).
5009 pp_expr2(freetype_constructor(_FT,Case,Expr),Prio,LimitReached) --> !,
5010 {FTCons = b(identifier(Case),any,[])},
5011 pp_expr(b(function(FTCons,Expr),any,[]),Prio,LimitReached).
5012 % ppatom_opt_scramble(Case),ppatom('('),pp_expr(Expr,_,LimitReached),ppatom(')').
5013 pp_expr2(freetype_destructor(_FT,Case,Expr),Prio,LimitReached) --> !,
5014 % pretty print it as: Case~(Expr)
5015 {FTCons = b(identifier(Case),any,[]), Destr = b(reverse(FTCons),any,[])},
5016 pp_expr(b(function(Destr,Expr),any,[]),Prio,LimitReached).
5017 % ({unicode_mode}
5018 % -> {unicode_translation(reverse,PowMinus1Symbol)},
5019 % ppatom(Case),ppatom(PowMinus1Symbol), % Note: we do not print the freetype's name FT
5020 % "(",pp_expr_m(Expr,0,LimitReached),")"
5021 % ; pp_freetype_term('__ft~',FT,Case,Expr,LimitReached) % TODO: maybe find better print
5022 % ).
5023 pp_expr2(let_predicate(Ids,Exprs,P),1,LimitReached) --> !,
5024 pp_expr_let_exists(Ids,Exprs,P,LimitReached). % instead of pp_expr_let
5025 pp_expr2(let_expression(Ids,Exprs,P),1,LimitReached) --> !,
5026 pp_expr_let(Ids,Exprs,P,LimitReached).
5027 pp_expr2(let_expression_global(Ids,Exprs,P),1,LimitReached) --> !, " /", "* global *", "/ ",
5028 pp_expr_let(Ids,Exprs,P,LimitReached).
5029 pp_expr2(lazy_let_pred(Id,Expr,P),Pr,LimitReached) --> !, pp_expr2(lazy_let_expr(Id,Expr,P),Pr,LimitReached).
5030 pp_expr2(lazy_let_subst(Id,Expr,P),Pr,LimitReached) --> !, pp_expr2(lazy_let_expr(Id,Expr,P),Pr,LimitReached).
5031 pp_expr2(lazy_let_expr(Id,Expr,P),1,LimitReached) --> !,
5032 pp_expr_let([Id],[Expr],P,LimitReached).
5033 pp_expr2(norm_conjunct(Cond,[]),1,LimitReached) --> !, % norm_conjunct: flattened version generated by b_interpreter_check,...
5034 "( ",pp_expr(Cond,_,LimitReached), ")".
5035 pp_expr2(norm_conjunct(Cond,[H|T]),1,LimitReached) --> !,
5036 "( ",pp_expr(Cond,_,LimitReached), ") ", and_symbol, " (", pp_expr2(norm_conjunct(H,T),_,LimitReached), ")".
5037 pp_expr2(assertion_expression(Cond,Msg,Expr),1,LimitReached) --> !,
5038 " ASSERT_EXPR (",
5039 pp_expr_m(b(convert_bool(Cond),pred,[]),30,LimitReached), ",",
5040 pp_expr_m(string(Msg),30,LimitReached), ",",
5041 pp_expr_m(Expr,30,LimitReached),
5042 " )".
5043 %pp_expr2(assertion_expression(Cond,_Msg,Expr),1) --> !,
5044 % "__ASSERT ",pp_expr_m(Cond,30),
5045 % " IN ", pp_expr_m(Expr,30).
5046 pp_expr2(partition(S,Elems),500,LimitReached) -->
5047 {eventb_translation_mode ;
5048 \+ atelierb_mode(_), length(Elems,Len), Len>50 % we need to print a quadratic number of disjoints
5049 },!,
5050 "partition(",pp_expr(S,_,LimitReached),
5051 ({Elems=[]} -> ")" ; pp_expr_wrap_l(',',Elems,')',LimitReached)).
5052 pp_expr2(partition(S,Elems),500,LimitReached) --> !,
5053 "(",pp_expr(S,_,LimitReached), " = ",
5054 ({Elems=[]} -> "{})"
5055 ; pp_expr_l_sep(Elems,"\\/",LimitReached), pp_all_disjoint(Elems,LimitReached),")").
5056 pp_expr2(finite(S),Prio,LimitReached) --> {\+ eventb_translation_mode}, %{atelierb_mode(_)},
5057 !,
5058 pp_expr2(member(S,b(fin_subset(S),set(any),[])),Prio,LimitReached).
5059 pp_expr2(if_then_else(If,Then,Else),1,LimitReached) --> {animation_minor_mode(z)},!,
5060 "\\IF ",pp_expr_m(If,30,LimitReached),
5061 " \\THEN ",pp_expr_m(Then,30,LimitReached),
5062 " \\ELSE ",pp_expr_m(Else,30,LimitReached).
5063 %pp_expr2(if_then_else(If,Then,Else),1) --> {unicode_mode},!,
5064 % "if ",pp_expr_m(If,30), " then ",pp_expr_m(Then,30), " else ",pp_expr_m(Else,30).
5065 pp_expr2(if_then_else(If,Then,Else),Prio,LimitReached) --> {atelierb_mode(_)},!,
5066 % print IF-THEN-ELSE using a translation that Atelier-B can understand:
5067 {rewrite_if_then_else_expr_to_b(if_then_else(If,Then,Else), NExpr),
5068 get_texpr_type(Then,Type),
5069 NAst = b(NExpr,Type,[])},
5070 % construct {d,x| If => x=Then & not(if) => x=Else}(TRUE)
5071 pp_expr(NAst,Prio,LimitReached).
5072 pp_expr2(if_then_else(If,Then,Else),1,LimitReached) --> !,
5073 pp_atom_opt_mathit('IF'),pp_space, % "IF ",
5074 pp_expr_m(If,30,LimitReached),
5075 pp_space, pp_atom_opt_mathit('THEN'),pp_space, %" THEN ",
5076 pp_expr_m(Then,30,LimitReached),
5077 pp_space, pp_atom_opt_mathit('ELSE'),pp_space, %" ELSE ",
5078 pp_expr_m(Else,30,LimitReached),
5079 pp_space, pp_atom_opt_mathit('END'). %" END"
5080 pp_expr2(kodkod(Id,Identifiers),300,LimitReached) --> !,
5081 "KODKOD_CALL(",ppnumber(Id),": ",pp_expr_ids(Identifiers,LimitReached),")".
5082 pp_expr2(Expr,500,_) -->
5083 {constants_in_mode(Expr,Symbol)},!,ppatom(Symbol).
5084 pp_expr2(equal(A,B),Prio,LimitReached) -->
5085 {get_preference(pp_propositional_logic_mode,true), % a mode for printing propositional logic formuli
5086 is_boolean_value(B,BV),
5087 get_texpr_id(A,_)},!,
5088 ({BV=pred_true} -> pp_expr(A,Prio,LimitReached)
5089 ; pp_expr2(negation(b(equal(A,b(boolean_true,boolean,[])),pred,[])),Prio,LimitReached)).
5090 pp_expr2(Expr,Prio,LimitReached) -->
5091 {functor(Expr,F,1),
5092 unary_prefix(F,Symbol,Prio),!,
5093 arg(1,Expr,Arg),APrio is Prio+1},
5094 ppatom(Symbol), " ",
5095 pp_expr_m(Arg,APrio,LimitReached).
5096 pp_expr2(Expr,500,LimitReached) -->
5097 {functor(Expr,F,1),
5098 unary_prefix_parentheses(F,Symbol),!,
5099 arg(1,Expr,Arg)},
5100 pp_atom_opt_latex(Symbol), "(", pp_expr(Arg,_,LimitReached), ")".
5101 pp_expr2(Expr,Prio,LimitReached) -->
5102 {functor(Expr,F,1),
5103 unary_postfix_in_mode(F,Symbol,Prio),!,
5104 arg(1,Expr,Arg),APrio is Prio+1},
5105 pp_expr_m(Arg,APrio,LimitReached),ppatom(Symbol).
5106 pp_expr2(power_of(Left,Right),Prio,LimitReached) --> {latex_mode},!, % special case, as we need to put {} around RHS
5107 {Prio=200, LPrio is Prio+1, RPrio = Prio},
5108 pp_expr_m(Left,LPrio,LimitReached),
5109 "^{",
5110 pp_expr_m(Right,RPrio,LimitReached),
5111 "}".
5112 pp_expr2(power_of_real(Left,Right),Prio,LimitReached) --> !,
5113 ({get_texpr_expr(Right,convert_real(RI))}
5114 -> pp_expr2(power_of(Left,RI),Prio,LimitReached) % the Atelier-B power_of expects integer exponent
5115 ; pp_external_call('RPOW',[Left,Right],expression,Prio,LimitReached)
5116 ).
5117 pp_expr2(Expr,OPrio,LimitReached) -->
5118 {functor(Expr,F,2),
5119 binary_infix_in_mode(F,Symbol,Prio,Ass),!,
5120 arg(1,Expr,Left),
5121 arg(2,Expr,Right),
5122 ( Ass = left, binary_infix_symbol(Left,Symbol) -> LPrio is Prio-1, RPrio is Prio+1
5123 ; Ass = right, binary_infix_symbol(Right,Symbol) -> LPrio is Prio+1, RPrio is Prio-1
5124 ; LPrio is Prio+1, RPrio is Prio+1)},
5125 % Note: Prio+1 is actually not necessary, Prio would be sufficient, as pp_expr_m uses a strict comparison <
5126 ({always_surround_by_parentheses(F)} -> "(",{OPrio=1000} ; {OPrio=Prio}),
5127 pp_expr_m(Left,LPrio,LimitReached),
5128 " ", ppatom(Symbol), " ",
5129 pp_expr_m(Right,RPrio,LimitReached),
5130 ({always_surround_by_parentheses(F)} -> ")" ; []).
5131 pp_expr2(first_of_pair(X),500,LimitReached) --> {get_texpr_type(X,couple(From,To))},!,
5132 "prj1(", % TO DO: Latex version
5133 ({\+ atelierb_mode(_)} % eventb_translation_mode
5134 -> "" % no need to print types in Event-B or with new parser;
5135 % TODO: also with new parser no longer required; only print in Atelier-B mode
5136 ; {pretty_normalized_type(From,FromT),
5137 pretty_normalized_type(To,ToT)},
5138 pp_atom_opt_latex(FromT), ",", pp_atom_opt_latex(ToT),
5139 ")("
5140 ),
5141 pp_expr(X,_,LimitReached),")".
5142 pp_expr2(second_of_pair(X),500,LimitReached) --> {get_texpr_type(X,couple(From,To))},!,
5143 "prj2(", % TO DO: Latex version
5144 ({\+ atelierb_mode(_)} -> "" % no need to print types in Event-B or with new parser
5145 ; {pretty_normalized_type(From,FromT),
5146 pretty_normalized_type(To,ToT)},
5147 pp_atom_opt_latex(FromT), ",", pp_atom_opt_latex(ToT),
5148 ")("
5149 ),
5150 pp_expr(X,_,LimitReached),")".
5151 pp_expr2(Call,Prio,LimitReached) --> {external_call(Call,Kind,Symbol,Args)},!,
5152 pp_external_call(Symbol,Args,Kind,Prio,LimitReached).
5153 pp_expr2(card(A),500,LimitReached) --> {latex_mode, get_preference(latex_pp_greek_ids,true)},!,
5154 "|",pp_expr_m(A,0,LimitReached),"|".
5155 pp_expr2(Expr,500,LimitReached) -->
5156 {functor(Expr,F,_),
5157 function_like_in_mode(F,Symbol),!,
5158 Expr =.. [F|Args]},
5159 ppatom(Symbol),
5160 ({Args=[]}
5161 -> "" % some operators like pred and succ do not expect arguments
5162 ; pp_expr_wrap_l('(',Args,')',LimitReached)).
5163 pp_expr2(Expr,250,LimitReached) -->
5164 {functor(Expr,F,3),
5165 quantified_in_mode(F,Symbol),
5166 Expr =.. [F,Ids,P1,E],
5167 !,
5168 add_normal_typing_predicates(Ids,P1,P)},
5169 ppatom(Symbol),pp_expr_ids(Ids,LimitReached),".(",
5170 pp_expr_m(P,11,LimitReached),pp_such_that_bar(E),
5171 pp_expr_m(E,11,LimitReached),")".
5172 pp_expr2(Expr,Prio,LimitReached) -->
5173 {functor(Expr,F,N),
5174 (debug_mode(on)
5175 -> format('**** Unknown functor ~w/~w in pp_expr2~n expression: ~w~n',[F,N,Expr])
5176 ; format('**** Unknown functor ~w/~w in pp_expr2~n',[F,N])
5177 ),
5178 %add_internal_error('Unknown Expression: ',pp_expr2(Expr,Prio)),
5179 Prio=20},
5180 ppterm_with_limit_reached(Expr,LimitReached).
5181
5182 :- use_module(external_function_declarations,[synonym_for_external_predicate/2]).
5183
5184 pp_external_call('MEMOIZE_STORED_FUNCTION',[TID],_,500,LimitReached) -->
5185 {get_integer(TID,ID),memoization:get_registered_function_name(ID,Name)},!,
5186 pp_expr_m(atom_string(Name),20,LimitReached),
5187 " /*@memo ", pp_expr_m(TID,20,LimitReached), "*/".
5188 pp_external_call('STRING_LENGTH',[Arg],_,Prio,LimitReached) -->
5189 {get_preference(allow_sequence_operators_on_strings,true)},!,
5190 pp_expr2(size(Arg),Prio,LimitReached).
5191 pp_external_call('STRING_APPEND',[Arg1,Arg2],_,Prio,LimitReached) -->
5192 {get_preference(allow_sequence_operators_on_strings,true)},!,
5193 pp_expr2(concat(Arg1,Arg2),Prio,LimitReached).
5194 pp_external_call('STRING_CONC',[Arg1],_,Prio,LimitReached) -->
5195 {get_preference(allow_sequence_operators_on_strings,true)},!,
5196 pp_expr2(general_concat(Arg1),Prio,LimitReached).
5197 % we could also pretty-print RMUL, ...
5198 pp_external_call(PRED,Args,pred,Prio,LimitReached) -->
5199 {get_preference(translate_ids_to_parseable_format,true),
5200 synonym_for_external_predicate(PRED,FUNC)},
5201 !, % print external predicate as function, as parser can only parse the latter without access to DEFINITIONS
5202 pp_expr2(equal(b(external_function_call(FUNC,Args),boolean,[]),
5203 b(boolean_true,boolean,[])),Prio,LimitReached).
5204 pp_external_call(Symbol,Args,_,Prio,LimitReached) -->
5205 ({invisible_external_pred(Symbol)}
5206 -> pp_expr2(truth,Prio,LimitReached),
5207 " /* ",pp_expr_m(atom_string(Symbol),20,LimitReached),pp_expr_wrap_l('(',Args,') */',LimitReached)
5208 ; {Prio=500},pp_expr_m(atom_string(Symbol),20,LimitReached),
5209 pp_expr_wrap_l('(',Args,')',LimitReached) % pp_expr_wrap_l('/*EXT:*/(',Args,')')
5210 ).
5211
5212 invisible_external_pred('LEQ_SYM').
5213 invisible_external_pred('LEQ_SYM_BREAK'). % just for symmetry breaking foralls,...
5214 external_call(external_function_call(Symbol,Args),expression,Symbol,Args).
5215 external_call(external_pred_call(Symbol,Args),pred,Symbol,Args).
5216 external_call(external_subst_call(Symbol,Args),subst,Symbol,Args).
5217
5218 pp_all_disjoint([H1,H2],LimitReached) --> !, " ",and_symbol," ", pp_disjoint(H1,H2,LimitReached).
5219 pp_all_disjoint([H1|T],LimitReached) --> pp_all_disjoint_aux(T,H1,LimitReached), pp_all_disjoint(T,LimitReached).
5220 pp_all_disjoint([],_) --> "".
5221
5222 pp_all_disjoint_aux([],_,_) --> "".
5223 pp_all_disjoint_aux([H2|T],H1,LimitReached) --> " ",and_symbol," ",
5224 pp_disjoint(H1,H2,LimitReached), pp_all_disjoint_aux(T,H1,LimitReached).
5225
5226 pp_disjoint(H1,H2,LimitReached) --> pp_expr(H1,_), "/\\", pp_expr(H2,_,LimitReached), " = {}".
5227
5228
5229 % given a list of predicates and an ID either extract ID:Set and return Set or return its type as string
5230 select_membership([],TID,[],atom_string(TS)) :- % atom_string used as wrapper for pp_expr2
5231 get_texpr_type(TID,Type), pretty_type(Type,TS).
5232 select_membership([Pred|Rest],TID,Rest,Set) :-
5233 Pred = b(member(TID2,Set),pred,_),
5234 same_id(TID2,TID,_),!.
5235 select_membership([Pred|Rest],TID,Rest,Set) :-
5236 Pred = b(equal(TID2,EqValue),pred,_),
5237 same_id(TID2,TID,_),!, get_texpr_type(TID,Type),
5238 Set = b(set_extension([EqValue]),set(Type),[]).
5239 select_membership([Pred|T],TID,[Pred|Rest],Set) :-
5240 select_membership(T,TID,Rest,Set).
5241
5242 % pretty print prj1/prj2
5243 pp_prj12(Prj,Set1,Set2,LimitReached) -->
5244 ppatom(Prj),"(",pp_expr(Set1,_,LimitReached),",",pp_expr(Set2,_),")".
5245
5246 %:- use_module(bsyntaxtree,[is_a_disjunct/3, get_integer/2]).
5247
5248 pp_comprehension_set(Ids,P1,Info,LimitReached) -->
5249 pp_comprehension_set5(Ids,P1,Info,LimitReached,_).
5250
5251 % the extra argument of pp_comprehension_set5 indicates whether a special(Rule) was applied or not
5252 %pp_comprehension_set(IDs,Body,Info,LimitReached,_) --> {print(pp(IDs,Body,Info)),nl,fail}.
5253 pp_comprehension_set5([TID1,TID2,TID3],Body,_Info,LimitReached,special(Proj)) -->
5254 /* This comprehension set was a projection function (prj1/prj2) */
5255 % %(z_,z__).(z__ : NATURAL|z_) -> prj1(INTEGER,NATURAL)
5256 {get_texpr_id(TID1,ID1), % sometimes _zzzz_unary or _prj_arg1__
5257 get_texpr_id(TID2,ID2), % sometimes _zzzz_binary or _prj_arg2__
5258 get_texpr_id(TID3,LambdaID),
5259 ? get_lambda_equality(Body,LambdaID,RestBody,ResultExpr),
5260 get_texpr_id(ResultExpr,ResultID),
5261 (ResultID = ID1 -> Proj = prj1 ; ResultID = ID2, Proj = prj2),
5262 flatten_conjunctions(RestBody,Rest1),
5263 select_membership(Rest1,TID1,Rest2,Set1),
5264 select_membership(Rest2,TID2,[],Set2)},
5265 !,
5266 pp_prj12(Proj,Set1,Set2,LimitReached).
5267 pp_comprehension_set5([ID1|T],Body,Info,LimitReached,special(disjunct)) --> {is_a_disjunct(Body,B1,B2),
5268 get_last(T,ID1,_FrontIDs,LastID),
5269 is_lambda_result_id(LastID,_Suffix)},!, % we seem to have the union of two lambda expressions
5270 "(", pp_comprehension_set([ID1|T],B1,Info,LimitReached),
5271 " \\/ ", pp_comprehension_set([ID1|T],B2,Info,LimitReached), ")".
5272 pp_comprehension_set5([b(identifier('_pred_'),integer,_),
5273 b(identifier(LAMBDARES),integer,_)],Body,_,_,special(pred)) --> % '_lambda_result_'
5274 {Body = b(equal(LR,T),pred,_),
5275 LR = b(identifier(LAMBDARES),integer,_),
5276 T = b(minus(ARG,One),integer,_),
5277 get_integer(One,1),
5278 ARG = b(identifier('_pred_'),integer,_)},
5279 !,
5280 "pred".
5281 pp_comprehension_set5([b(identifier('_succ_'),integer,_),
5282 b(identifier(LAMBDARES),integer,_)],Body,_,_,special(succ)) --> % '_lambda_result_'
5283 {Body = b(equal(LR,T),pred,_),
5284 LR = b(identifier(LAMBDARES),integer,_),
5285 T = b(add(ARG,One),integer,_),
5286 get_integer(One,1),
5287 ARG = b(identifier('_succ_'),integer,_)},
5288 !,
5289 "succ".
5290 pp_comprehension_set5(Paras,Body,Info,LimitReached,special(lambda)) -->
5291 {detect_lambda_comprehension(Paras,Body, FrontIDs,LambdaBody,ToExpr)},
5292 !,
5293 {add_normal_typing_predicates(FrontIDs,LambdaBody,TLambdaBody)},
5294 ({eventb_translation_mode} -> "(" ; ""), % put brackets around the lambda in Rodin
5295 pp_annotations(Info,Body),
5296 lambda_symbol, % "%"
5297 pp_lambda_identifiers(FrontIDs,LimitReached),
5298 ".",
5299 ({eventb_translation_mode} -> {IPrio=30} ; {IPrio=11}, "("), % In Rodin it is not ok to write (P|E)
5300 pp_expr_m(TLambdaBody,IPrio,LimitReached), % Check 11 against prio of . and |
5301 pp_such_that_bar(ToExpr),
5302 pp_expr_m(ToExpr,IPrio,LimitReached),
5303 ")".
5304 pp_comprehension_set5(TIds,Body,Info,LimitReached,special(event_b_comprehension_set)) -->
5305 % detect Event-B style set comprehensions and use bullet • or Event-B notation such as {x·x ∈ 1 ‥ 3|x * 10}
5306 % gets translated to {`__comp_result__`|∃x·(x ∈ 1 ‥ 3 ∧ `__comp_result__` = x * 10)}
5307 ? {is_eventb_comprehension_set(TIds,Body,Info,Ids,P1,EXPR), \+ atelierb_mode(_)},!, % print rewritten version for AtelierB
5308 pp_annotations(Info,P1),
5309 left_set_bracket,
5310 pp_expr_l_pair_in_mode(Ids,LimitReached),
5311 {add_normal_typing_predicates(Ids,P1,P)},
5312 dot_bullet_symbol,
5313 pp_expr_m(P,11,LimitReached),
5314 pp_such_that_bar(P),
5315 pp_expr_m(EXPR,11,LimitReached),
5316 right_set_bracket.
5317 pp_comprehension_set5(Ids,P1,_Info,LimitReached,normal) --> {atelierb_mode(prover(ml))},!,
5318 "SET(",
5319 pp_expr_l_pair_in_mode(Ids,LimitReached),
5320 ").(",
5321 {add_normal_typing_predicates(Ids,P1,P)},
5322 pp_expr_m(P,11,LimitReached),
5323 ")".
5324 pp_comprehension_set5(Ids,P1,Info,LimitReached,normal) -->
5325 pp_annotations(Info,P1),
5326 left_set_bracket,
5327 pp_expr_l_pair_in_mode(Ids,LimitReached),
5328 {add_normal_typing_predicates(Ids,P1,P)},
5329 pp_such_that_bar(P),
5330 pp_expr_m(P,11,LimitReached),
5331 right_set_bracket.
5332
5333
5334 detect_lambda_comprehension([ID1|T],Body, FrontIDs,LambdaBody,ToExpr) :-
5335 get_last(T,ID1,FrontIDs,LastID),
5336 FrontIDs=[_|_], % at least one identifier for the lambda
5337 is_lambda_result_id(LastID,Suffix),
5338 % nl, print(lambda(Body,T,ID1)),nl,
5339 (is_an_equality(Body,From,ToExpr) -> LambdaBody = b(truth,pred,[])
5340 ; is_a_conjunct(Body,LambdaBody,Equality),
5341 is_an_equality(Equality,From,ToExpr)),
5342 is_lambda_result_id(From,Suffix).
5343
5344 pp_annotations(V,_) --> {var(V), format('Illegal variable info field in pp_annotations: ~w~n',[V])},!,
5345 "/* ILLEGAL VARIABLE INFO FIED */".
5346 ?pp_annotations(INFO,_) --> {member(prob_annotation('SYMBOLIC'),INFO)},!,
5347 "/*@symbolic*/ ".
5348 ?pp_annotations(_,b(_,_,INFO)) --> {nonvar(INFO),member(prob_annotation('SYMBOLIC'),INFO)},!,
5349 "/*@symbolic*/ ".
5350 % TO DO: maybe also print other annotations like memoize, recursive ?
5351 pp_annotations(_,_) --> "".
5352
5353 pp_event_b_comprehension_set(Ids,E,P1,LimitReached) -->
5354 left_set_bracket,pp_expr_l_pair_in_mode(Ids,LimitReached),
5355 {add_normal_typing_predicates(Ids,P1,P)},
5356 pp_such_that_bar(P),pp_expr_m(P,11,LimitReached),
5357 " . ", pp_expr_m(E,11,LimitReached),right_set_bracket.
5358
5359 pp_lambda_identifiers([H1,H2|T],LimitReached) --> {\+ eventb_translation_mode},!,
5360 "(",pp_expr_l([H1,H2|T],LimitReached),")".
5361 pp_lambda_identifiers(L,LimitReached) --> pp_expr_l_pair_in_mode(L,LimitReached).
5362
5363 pp_such_that_bar(_) --> {latex_mode},!, "\\mid ".
5364 pp_such_that_bar(b(unary_minus(_),_,_)) --> !, " | ". % otherwise AtelierB complains about illegal token |-
5365 pp_such_that_bar(b(unary_minus_real(_),_,_)) --> !, " | ". % otherwise AtelierB complains about illegal token |-
5366 pp_such_that_bar(_Next) --> "|".
5367 pp_such_that_bar --> {latex_mode},!, "\\mid ".
5368 pp_such_that_bar --> "|".
5369
5370 is_an_equality(b(equal(A,B),_,_),A,B).
5371
5372 integer_set_mapping(A,B) :- integer_set_mapping(A,_,B).
5373 integer_set_mapping(A,integer_set,B) :- unicode_mode, unicode_translation(A,B),!.
5374 integer_set_mapping(A,integer_set,B) :- latex_mode, latex_integer_set_translation(A,B),!.
5375 integer_set_mapping(A,integer_set,B) :- atelierb_mode(prover(PPML)),
5376 atelierb_pp_translation(A,PPML,B),!.
5377 integer_set_mapping(A,integer_set,B) :-
5378 eventb_translation_mode, eventb_integer_mapping(A,B),!.
5379 integer_set_mapping(ISet,user_set,Res) :- atomic(ISet),!,Res=ISet.
5380 integer_set_mapping(_ISet,unknown_set,'integer_set(??)').
5381
5382 eventb_integer_mapping('INTEGER','INT').
5383 eventb_integer_mapping('NATURAL','NAT').
5384 eventb_integer_mapping('NATURAL1','NAT1').
5385
5386 real_set_mapping(A,B) :- unicode_mode, unicode_translation(A,B),!.
5387 real_set_mapping(X,X). % TO DO: unicode_mode,...
5388
5389 :- dynamic comment_level/1.
5390 reset_pp :- retractall(comment_level(_)).
5391 enter_comment --> {retract(comment_level(N))},!, "(*", {N1 is N+1, assertz(comment_level(N1))}.
5392 enter_comment --> "/*", {assertz(comment_level(1))}.
5393 exit_comment --> {retract(comment_level(N))},!,
5394 ({N>1} -> "*)", {N1 is N-1, assertz(comment_level(N1))} ; "*/").
5395 exit_comment --> "*/", {add_internal_error('Unmatched closing comment:',exit_comment)}.
5396 % TO DO: ensure reset_pp is called when starting to pretty print, in case timeout occurs in previous pretty prints
5397
5398 %get_last([b(identifier(_lambda_result_10),set(couple(integer,set(couple(integer,integer)))),[])],b(identifier(i),integer,[]),[b(identifier(i),integer,[])],b(identifier(_lambda_result_10),set(couple(integer,set(couple(integer,integer)))),[]))
5399
5400 get_last([],Last,[],Last).
5401 get_last([H2|T],H1,[H1|LT],Last) :- get_last(T,H2,LT,Last).
5402
5403 pp_expr_wrap_l(Pre,Expr,Post,LimitReached) -->
5404 ppatom(Pre),pp_expr_l(Expr,LimitReached),ppatom(Post).
5405 %pp_freetype_term(Term,FT,L,Expr,LimitReached) -->
5406 % {pretty_freetype(FT,P)},
5407 % ppatom(Term),"(",ppatom_opt_scramble(P),",",
5408 % ppatom(L),",",pp_expr_m(Expr,500,LimitReached),")".
5409
5410 % print a list of expressions, seperated by commas
5411 pp_expr_l_pair_in_mode(List,LimitReached) --> {eventb_translation_mode},!,
5412 {maplet_symbol(MapletStr,[])},
5413 pp_expr_l_sep(List,MapletStr,LimitReached).
5414 pp_expr_l_pair_in_mode(List,LimitReached) --> pp_expr_l_sep(List,",",LimitReached).
5415 pp_expr_l(List,LimitReached) --> pp_expr_l_sep(List,",",LimitReached).
5416
5417 pp_expr_l_sep([Expr],_,LimitReached) --> !,
5418 pp_expr_m(Expr,0,LimitReached).
5419 pp_expr_l_sep(List,Sep,LimitReached) --> pp_expr_l2(List,Sep,LimitReached).
5420 pp_expr_l2([],_Sep,_) --> !.
5421 pp_expr_l2([Expr|Rest],Sep,LimitReached) -->
5422 {get_sep_prio(Sep,Prio)},
5423 pp_expr_m(Expr,Prio,LimitReached),
5424 pp_expr_l3(Rest,Sep,LimitReached).
5425 pp_expr_l3([],_Sep,_) --> !.
5426 pp_expr_l3(Rest,Sep,LimitReached) -->
5427 Sep,pp_expr_l2(Rest,Sep,LimitReached).
5428
5429 get_sep_prio(",",Prio) :- !, Prio=116. % Prio of , is 115
5430 get_sep_prio("\\/",Prio) :- !, Prio=161.
5431 get_sep_prio("/\\",Prio) :- !, Prio=161.
5432 get_sep_prio("|->",Prio) :- !, Prio=161.
5433 get_sep_prio([8614],Prio) :- !, Prio=161.
5434 %
5435 get_sep_prio(_,161).
5436
5437 % print the fields of a record
5438 pp_expr_fields([field(Name,Expr)],LimitReached) --> !,
5439 pp_identifier(Name),":",pp_expr_m(Expr,120,LimitReached).
5440 pp_expr_fields(Fields,LimitReached) -->
5441 pp_expr_fields2(Fields,LimitReached).
5442 pp_expr_fields2([],_) --> !.
5443 pp_expr_fields2([field(Name,Expr)|Rest],LimitReached) -->
5444 pp_identifier(Name),":",
5445 pp_expr_m(Expr,116,LimitReached),
5446 pp_expr_fields3(Rest,LimitReached).
5447 pp_expr_fields3([],_) --> !.
5448 pp_expr_fields3(Rest,LimitReached) -->
5449 ",",pp_expr_fields2(Rest,LimitReached).
5450
5451 % TO DO: test more fully; identifiers seem to be wrapped in brackets
5452 pp_expr_let_exists(Ids,Exprs,P,LimitReached) -->
5453 exists_symbol,
5454 ({eventb_translation_mode} -> % otherwise we get strange characters in Rodin, no (.) allowed in Rodin
5455 pp_expr_ids_in_mode(Ids,LimitReached),
5456 ".("
5457 ; " /* LET */ (",
5458 pp_expr_l_pair_in_mode(Ids,LimitReached),
5459 ").("
5460 ),
5461 pp_expr_let_pred_exprs(Ids,Exprs,LimitReached),
5462 ({is_truth(P)} -> ""
5463 ; " ",and_symbol," ", pp_expr_m(P,40,LimitReached)),
5464 ")".
5465
5466 pp_expr_let_pred_exprs([],[],_) --> !.
5467 pp_expr_let_pred_exprs([Id|Irest],[Expr|Erest],LimitReached) -->
5468 " ",pp_expr_let_id(Id,LimitReached),
5469 "=",pp_expr_m(Expr,400,LimitReached),
5470 ( {Irest=[]} -> [] ; " ", and_symbol),
5471 pp_expr_let_pred_exprs(Irest,Erest,LimitReached).
5472
5473 % print a LET expression
5474 pp_expr_let(_Ids,Exprs,P,LimitReached) -->
5475 {eventb_translation_mode,
5476 P=b(_,_,I), member(was(extended_expr(Op)),I)},!, % let was created by direct_definition for a theory operator call
5477 ppatom(Op),
5478 pp_function_left_bracket,
5479 pp_expr_l_sep(Exprs,",",LimitReached),
5480 %pp_expr_let_pred_exprs(Ids,Exprs,LimitReached) % write entire predicate with parameter names
5481 pp_function_right_bracket.
5482 pp_expr_let(Ids,Exprs,P,LimitReached) -->
5483 "LET ", pp_expr_ids_no_parentheses(Ids,LimitReached),
5484 " BE ", pp_expr_let_pred_exprs(Ids,Exprs,LimitReached),
5485 " IN ",pp_expr_m(P,5,LimitReached),
5486 " END".
5487
5488 pp_expr_let_id(ID,LimitReached) --> {atomic(ID),!, print(unwrapped_let_id(ID)),nl},
5489 pp_expr_m(identifier(ID),500,LimitReached).
5490 pp_expr_let_id(ID,LimitReached) --> pp_expr_m(ID,499,LimitReached).
5491
5492 % print a list of identifiers
5493 pp_expr_ids_in_mode([],_) --> !.
5494 pp_expr_ids_in_mode(Ids,LimitReached) --> {eventb_translation_mode ; Ids=[_]},!,
5495 pp_expr_l(Ids,LimitReached). % no (.) allowed in Event-B; not necessary in B if only one id
5496 pp_expr_ids_in_mode(Ids,LimitReached) --> "(",pp_expr_l(Ids,LimitReached),")".
5497
5498 pp_expr_ids([],_) --> !.
5499 pp_expr_ids(Ids,LimitReached) -->
5500 % ( {Ids=[Id]} -> pp_expr_m(Id,221)
5501 % ;
5502 "(",pp_expr_l(Ids,LimitReached),")".
5503
5504 pp_expr_ids_no_parentheses(Ids,LimitReached) --> pp_expr_l(Ids,LimitReached).
5505
5506
5507 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5508 % pretty print types for error messages
5509
5510 %:- use_module(probsrc(typing_tools), [normalize_type/2]).
5511 % replace seq(.) types before pretty printing:
5512 pretty_normalized_type(Type,String) :- typing_tools:normalize_type(Type,NT),!,
5513 pretty_type(NT,String).
5514 pretty_normalized_type(Type,String) :-
5515 add_internal_error('Cannot normalize type:',pretty_normalized_type(Type,String)),
5516 pretty_type(Type,String).
5517
5518 % for pp_expr: do we potentially have to add parentheses
5519 normalized_type_requires_outer_paren(couple(_,_)).
5520 % all other types are either identifiers or use prefix notation (POW(.), seq(.), struct(.))
5521
5522 pretty_type(Type,String) :-
5523 pretty_type_l([Type],[String]).
5524
5525 pretty_type_l(Types,Strings) :-
5526 extract_vartype_names(Types,N),
5527 pretty_type2_l(Types,N,Strings).
5528 pretty_type2_l([],_,[]).
5529 pretty_type2_l([T|TRest],Names,[S|SRest]) :-
5530 pretty_type2(T,Names,noparen,S),
5531 pretty_type2_l(TRest,Names,SRest).
5532
5533 extract_vartype_names(Types,names(Variables,Names)) :-
5534 term_variables(Types,Variables),
5535 name_variables(Variables,1,Names).
5536
5537 pretty_type2(X,names(Vars,Names),_,Name) :- var(X),!,exact_member_lookup(X,Name,Vars,Names).
5538 pretty_type2(any,_,_,'?').
5539 pretty_type2(set(T),N,_,Text) :- nonvar(T),T=couple(A,B),!,
5540 pretty_type2(A,N,paren,AT), pretty_type2(B,N,paren,BT),
5541 binary_infix_in_mode(relations,Symbol,_,_), % <->
5542 ajoin(['(',AT,Symbol,BT,')'],Text).
5543 pretty_type2(set(T),N,_,Text) :-
5544 pretty_type2(T,N,noparen,TT), function_like_in_mode(pow_subset,POW),
5545 ajoin([POW,'(',TT,')'],Text).
5546 pretty_type2(seq(T),N,_,Text) :-
5547 pretty_type2(T,N,noparen,TT), ajoin(['seq(',TT,')'],Text).
5548 pretty_type2(couple(A,B),N,Paren,Text) :-
5549 pretty_type2(A,N,paren,AT),pretty_type2(B,N,paren,BT),
5550 binary_infix_in_mode(cartesian_product,Cart,_,_),
5551 ajoin([AT,Cart,BT],Prod),
5552 ( Paren == noparen ->
5553 Text = Prod
5554 ;
5555 ajoin(['(',Prod,')'],Text)).
5556 pretty_type2(string,_,_,'STRING').
5557 pretty_type2(integer,_,_,Atom) :- integer_set_mapping('INTEGER',Atom).
5558 pretty_type2(real,_,_,Atom) :- real_set_mapping('REAL',Atom).
5559 pretty_type2(boolean,_,_,'BOOL').
5560 pretty_type2(global(G_Id),_,_,A) :- opt_scramble_id(G_Id,G), ajoin([G],A).
5561 pretty_type2(freetype(Id),N,_,A) :- pretty_freetype2(Id,N,A).
5562 pretty_type2(pred,_,_,predicate).
5563 pretty_type2(subst,_,_,substitution).
5564 pretty_type2(constant(List),_,_,A) :-
5565 (var(List) -> ['{??VAR??...}'] % should not happen
5566 ; ajoin_with_sep(List,',',P), ajoin(['{',P,'}'],A)).
5567 pretty_type2(record(Fields),N,_,Text) :-
5568 pretty_type_fields(Fields,N,FText),
5569 ajoin(['struct(',FText,')'],Text).
5570 pretty_type2(op(Params,Results),N,_,Text) :-
5571 pretty_type_l(Params,N,PText),
5572 ( nonvar(Results),Results=[] ->
5573 ajoin(['operation(',PText,')'],Text)
5574 ;
5575 pretty_type_l(Results,N,RText),
5576 ajoin([RText,'<--operation(',PText,')'],Text) ).
5577 pretty_type2(definition(DefType,_,_),_,_,DefType).
5578 pretty_type2(witness,_,_,witness).
5579 pretty_type2([],_,_,'[]') :- add_error(pretty_type,'Illegal list in type:','[]').
5580 pretty_type2([H|T],_,_,'[_]') :- add_error(pretty_type,'Illegal list in type:',[H|T]).
5581 pretty_type2(b(E,T,I),_,_,'?') :- add_error(pretty_type,'Illegal b/3 term in type:',b(E,T,I)).
5582
5583 pretty_type_l(L,_,'...') :- var(L),!.
5584 pretty_type_l([],_,'') :- !.
5585 pretty_type_l([E|Rest],N,Text) :-
5586 pretty_type2(E,N,noparen,EText),
5587 ( nonvar(Rest),Rest=[] ->
5588 EText=Text
5589 ;
5590 pretty_type_l(Rest,N,RText),
5591 ajoin([EText,',',RText],Text)).
5592
5593 pretty_type_fields(L,_,'...') :- var(L),!.
5594 pretty_type_fields([],_,'') :- !.
5595 pretty_type_fields([field(Name,Type)|FRest],N,Text) :- !,
5596 pretty_type2(Type,N,noparen,TText),
5597 ptf_seperator(FRest,Sep),
5598 pretty_type_fields(FRest,N,RestText),
5599 opt_scramble_id(Name,ScrName),
5600 ajoin([ScrName,':',TText,Sep,RestText],Text).
5601 pretty_type_fields(Err,N,Text) :-
5602 add_internal_error('Illegal field type: ',pretty_type_fields(Err,N,Text)), Text='??'.
5603 ptf_seperator(L,', ') :- var(L),!.
5604 ptf_seperator([],'') :- !.
5605 ptf_seperator(_,', ').
5606
5607 pretty_freetype(Id,A) :-
5608 extract_vartype_names(Id,N),
5609 pretty_freetype2(Id,N,A).
5610 pretty_freetype2(Id,_,A) :- var(Id),!,A='_'.
5611 pretty_freetype2(Id,_,A) :- atomic(Id),!,Id=A.
5612 pretty_freetype2(Id,N,A) :-
5613 Id=..[Name|TypeArgs],
5614 pretty_type2_l(TypeArgs,N,PArgs),
5615 ajoin_with_sep(PArgs,',',P),
5616 ajoin([Name,'(',P,')'],A).
5617
5618 name_variables([],_,[]).
5619 name_variables([_|VRest],Index,[Name|NRest]) :-
5620 (nth1(Index,"ABCDEFGHIJKLMNOPQRSTUVWXYZ",C) -> SName = [C] ; number_codes(Index,SName)),
5621 append("_",SName,CName),atom_codes(Name,CName),
5622 Next is Index+1,
5623 name_variables(VRest,Next,NRest).
5624
5625 ppatom(Var) --> {var(Var)},!, ppatom('$VARIABLE').
5626 ppatom(Cmp) --> {compound(Cmp)},!, ppatom('$COMPOUND_TERM').
5627 ppatom(Atom) --> {safe_atom_codes(Atom,Codes)}, ppcodes(Codes).
5628
5629 ppnumber(Number) --> {var(Number)},!,pp_clpfd_variable(Number).
5630 ppnumber(inf) --> !,"inf".
5631 ppnumber(minus_inf) --> !,"minus_inf".
5632 ppnumber(Number) --> {number(Number),number_codes(Number,Codes)},!, ppcodes(Codes).
5633 ppnumber(Number) --> {add_internal_error('Not a number: ',ppnumber(Number,_,_))}, "<<" ,ppterm(Number), ">>".
5634
5635 pp_numberedvar(N) --> "_",ppnumber(N),"_".
5636
5637 pp_clpfd_variable(X) --> "?:",{fd_dom(X,Dom)},write_to_codes(Dom), pp_frozen_info(X).
5638
5639 pp_frozen_info(_X) --> {get_preference(translate_print_frozen_infos,false)},!,[].
5640 pp_frozen_info(X) -->
5641 ":(",{frozen(X,Goal)},
5642 write_goal_with_max_depth(Goal),
5643 ")".
5644
5645 write_goal_with_max_depth((A,B)) --> !, "(",write_goal_with_max_depth(A),
5646 ", ", write_goal_with_max_depth(B), ")".
5647 write_goal_with_max_depth(Term) --> write_with_max_depth(3,Term).
5648
5649 write_with_max_depth(Depth,Term,S1,S2) :- write_term_to_codes(Term,S1,S2,[max_depth(Depth)]).
5650
5651 ppterm(Term) --> write_to_codes(Term).
5652
5653 ppcodes([],S,S).
5654 ppcodes([C|Rest],[C|In],Out) :- ppcodes(Rest,In,Out).
5655
5656 ppterm_with_limit_reached(Term,LimitReached) -->
5657 {write_to_codes(Term,Codes,[])}, ppcodes_with_limit_reached(Codes,LimitReached).
5658
5659 ppcodes_with_limit_reached([C|Rest],LimitReached,[C|In],Out) :- var(LimitReached), !,
5660 ppcodes_with_limit_reached(Rest,LimitReached,In,Out).
5661 ppcodes_with_limit_reached(_,_LimitReached,S,S).
5662
5663 % for debugging:
5664 :- public b_portray_hook/1.
5665 b_portray_hook(X) :-
5666 nonvar(X),
5667 (is_texpr(X), ground(X) -> write('{# '),print_bexpr_or_subst(X),write(' #}')
5668 ; X=avl_set(_), ground(X) -> write('{#avl '), print_bvalue(X), write(')}')
5669 ; X=wfx(WF0,_,WFE,Info) -> format('wfx(~w,$mutable,~w,~w)',[WF0,WFE,Info]) % to do: short summary of prios & call stack
5670 ).
5671
5672 install_b_portray_hook :- % register portray hook mainly for the Prolog debugger
5673 assertz(( user:portray(X) :- translate:b_portray_hook(X) )).
5674 remove_b_portray_hook :-
5675 retractall( user:portray(_) ).
5676
5677
5678 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5679 % Pretty-print of Event-B models as classical B
5680
5681 translate_eventb_to_classicalb(EBMachine,AddInfo,Rep) :-
5682 ( conversion_check(EBMachine) ->
5683 convert_eventb_classicalb(EBMachine,CBMachine),
5684 call_cleanup(( set_animation_mode(b), % clear minor mode "eventb"
5685 translate_machine(CBMachine,Rep,AddInfo),!),
5686 set_animation_minor_mode(eventb))
5687 ; \+ animation_minor_mode(eventb) -> add_error(translate,'Conversion only applicable to Event-B models')
5688 ;
5689 add_error_and_fail(translate,'Conversion not applicable, check if you limited the number of abstract level to 0')
5690 ).
5691
5692 convert_eventb_classicalb(EBMachine,CBMachine) :-
5693 select_section(operation_bodies,In,Out,EBMachine,CBMachine1),
5694 maplist(convert_eventop,In,Out),
5695 select_section(initialisation,IIn,IOut,CBMachine1,CBMachine),
5696 convert_event(IIn,[],IOut).
5697 convert_eventop(EBOp,CBOp) :-
5698 get_texpr_expr(EBOp,operation(Id,[],Args,EBBody)),
5699 get_texpr_info(EBOp,Info),
5700 convert_event(EBBody,Args,CBBody),
5701 % Remove the arguments
5702 create_texpr(operation(Id,[],[],CBBody),op([],[]),Info,CBOp).
5703 convert_event(TEvent,Parameters,TSubstitution) :-
5704 get_texpr_expr(TEvent,rlevent(_Id,_Section,_Status,_Parameters,Guard,_Theorems,Actions,_VariableWitnesses,_ParameterWitnesses,_Ums,_Refined)),
5705 in_parallel(Actions,PAction),
5706 convert_event2(Parameters,Guard,PAction,TSubstitution).
5707 convert_event2([],Guard,Action,Action) :-
5708 is_truth(Guard),!.
5709 convert_event2([],Guard,Action,Select) :-
5710 !,create_texpr(select([When]),subst,[],Select),
5711 create_texpr(select_when(Guard,Action),subst,[],When).
5712 convert_event2(Parameters,Guard,Action,Any) :-
5713 create_texpr(any(Parameters,Guard,Action),subst,[],Any).
5714 in_parallel([],Skip) :- !,create_texpr(skip,subst,[],Skip).
5715 in_parallel([A],A) :- !.
5716 in_parallel(Actions,Parallel) :- create_texpr(parallel(Actions),subst,[],Parallel).
5717
5718 conversion_check(Machine) :-
5719 animation_mode(b),
5720 animation_minor_mode(eventb),
5721 get_section(initialisation,Machine,Init),
5722 get_texpr_expr(Init,rlevent(_Id,_Sec,_St,_Par,_Grd,_Thms,_Act,_VW,_PW,_Ums,[])).
5723
5724 % ------------------------------------------------------------
5725
5726 % divide a B typed expression into columns for CSV export or Table viewing of its values
5727 get_bexpression_column_template(b(couple(A,B),_,_),(AVal,BVal),ColHeaders,Columns) :- !,
5728 get_bexpression_column_template(A,AVal,AHeaders,AColumns),
5729 get_bexpression_column_template(B,BVal,BHeaders,BColumns),
5730 append(AHeaders,BHeaders,ColHeaders),
5731 append(AColumns,BColumns,Columns).
5732 get_bexpression_column_template(TypedExpr,Value,[ColHeader],[Value]) :-
5733 translate:translate_bexpression_with_limit(TypedExpr,100,ColHeader).
5734
5735
5736 % a version of member that creates an error when info list not instantiated
5737 member_in_info(X,T) :- var(T),!, add_internal_error('Illegal info field:', member_in_info(X,T)),fail.
5738 member_in_info(X,[X|_]).
5739 member_in_info(X,[_|T]) :- member_in_info(X,T).
5740
5741 memberchk_in_info(X,T) :- var(T),!, add_internal_error('Illegal info field:', memberchk_in_info(X,T)),fail.
5742 memberchk_in_info(X,[X|_]) :- !.
5743 memberchk_in_info(X,[_|T]) :- memberchk_in_info(X,T).
5744
5745 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5746
5747 :- use_module(library(clpfd)).
5748
5749 % print also partially instantiated variables with CLP(FD) Info
5750 print_value_variable(X) :- var(X), !, print(X).
5751 print_value_variable(int(X)) :- print('int('), print_clpfd_variable(X), print(')').
5752 print_value_variable(fd(X,T)) :- print('fd('), print_clpfd_variable(X), print(','), print(T),print(')').
5753 print_value_variable(X) :- print(X).
5754
5755 print_clpfd_variable(X) :- var(X),!,print(X), print(':'), fd_dom(X,Dom), print(Dom), print_frozen_info(X).
5756 print_clpfd_variable(X) :- print(X).
5757
5758 %print_clpfd_variables([]).
5759 %print_clpfd_variables([H|T]) :- print('CLPFD: '),print_clpfd_variable(H), nl, print_clpfd_variables(T).
5760
5761
5762 :- public l_print_frozen_info/1.
5763 l_print_frozen_info([]).
5764 l_print_frozen_info([H|T]) :- print(H), print(' '),
5765 (var(H) -> print_frozen_info(H) ;
5766 H=fd_var(V,_) -> print_frozen_info(V) ; true), l_print_frozen_info(T).
5767
5768 print_frozen_info(X) :- frozen(X,Goal), print_frozen_goal(Goal).
5769 print_frozen_goal((A,B)) :- !, print_frozen_goal(A), print(','), print_frozen_goal(B).
5770 print_frozen_goal(prolog:trig_nondif(_A,_B,R,_S)) :- !, frozen(R,G2), print_frozen_goal2(G2).
5771 print_frozen_goal(G) :- print_frozen_goal2(G).
5772 print_frozen_goal2(V) :- var(V),!, print(V).
5773 print_frozen_goal2(true) :- !.
5774 print_frozen_goal2((A,B)) :- !, print_frozen_goal2(A), print(','), print_frozen_goal2(B).
5775 print_frozen_goal2(G) :- print(' :: '), tools_printing:print_term_summary(G).
5776
5777
5778 /* Event-B operators */
5779 translate_eventb_operators([]) --> !.
5780 translate_eventb_operators([Name-Call|Rest]) -->
5781 translate_eventb_operator(Call,Name),
5782 translate_eventb_operators(Rest).
5783
5784 translate_eventb_operator(Module:Call,Name) -->
5785 insertcodes("\n "),
5786 indention_codes(In,Out),
5787 {Call =.. [Functor|Args],
5788 translate_eventb_operator2(Functor,Args,Module,Call,Name,In,Out)}.
5789
5790
5791 translate_eventb_operator2(direct_definition,[Args,_RawWD,RawBody,TypeParas|_],_Module,_Call,Name) -->
5792 pp_eventb_direct_definition_header(Name,Args),!,
5793 ppcodes(" direct_definition ["),
5794 pp_eventb_operator_args(TypeParas),
5795 ppcodes("] "),
5796 {translate_in_mode(eqeq,'==',EqEqStr)}, ppatom(EqEqStr),
5797 ppcodes(" "),
5798 pp_raw_formula(RawBody). % TO DO: use indentation
5799 translate_eventb_operator2(axiomatic_definition,[Tag|_],_Module,_Call,Name) --> !,
5800 ppterm(Name),
5801 ppcodes(": Operator implemented by axiomatic definition using "),
5802 ppatom(Tag).
5803 translate_eventb_operator2(Functor,_,Module,_Call,Name) -->
5804 ppterm(Name),
5805 ppcodes(": Operator implemented by "),
5806 ppatom(Module),ppcodes(":"),ppatom(Functor).
5807
5808 % example direct definition:
5809 %direct_definition([argument(curM,integer_set(none)),argument(curH,integer_set(none))],truth(none),add(none,identifier(none,curM),multiplication(none,identifier(none,curH),integer(none,60))),[])
5810
5811 pp_eventb_direct_definition_header(Name,Args) -->
5812 ppterm(Name), ppcodes("("),
5813 pp_eventb_operator_args(Args), ppcodes(")").
5814
5815 translate_eventb_direct_definition_header(Name,Args,ResAtom) :-
5816 (pp_eventb_direct_definition_header(Name,Args,C,[])
5817 -> atom_codes(ResAtom,C) ; ResAtom='<<UNABLE TO PRETTY-PRINT OPERATOR HEADER>>').
5818 translate_eventb_direct_definition_body(RawBody,ResAtom) :-
5819 (pp_raw_formula(RawBody,C,[]) -> atom_codes(ResAtom,C) ; ResAtom='<<UNABLE TO PRETTY-PRINT OPERATOR BODY>>').
5820
5821 pp_raw_formula(RawExpr) --> {transform_raw(RawExpr,TExpr)},!, pp_expr(TExpr,_,_LR).
5822 pp_raw_formula(_) --> ppcodes("<<UNABLE TO PRETTY-PRINT>>").
5823
5824
5825 pp_eventb_operator_args([]) --> [].
5826 pp_eventb_operator_args([Arg]) --> !, pp_argument(Arg).
5827 pp_eventb_operator_args([Arg|T]) --> pp_argument(Arg), ppcodes(","),
5828 pp_eventb_operator_args(T).
5829 pp_argument(argument(ID,_RawType)) --> !, ppatom(ID).
5830 pp_argument(identifier(_,ID)) --> !, "<",ppatom(ID),">".
5831 pp_argument(Atom) --> ppatom(Atom).
5832
5833 % ---------------------------------------
5834
5835 % translate a predicate into B machine for manipulation
5836 translate_predicate_into_machine(Pred,MchName,ResultAtom) :-
5837 get_global_identifiers(Ignored,ignore_promoted_constants),
5838 find_typed_identifier_uses(Pred, Ignored, TUsedIds),
5839 get_texpr_ids(TUsedIds,UsedIds),
5840 add_typing_predicates(TUsedIds,Pred,TPred),
5841 set_print_type_infos(all,CHNG),
5842 specfile:set_animation_mode(b), % clear eventb minor mode; to do: set back
5843 translate_bexpression(TPred,PredAtom), %print(res(UsedIds,ResultAtom)),nl,
5844 reset_print_type_infos(CHNG),
5845 convert_and_ajoin_ids(UsedIds,AllIds),
5846 bmachine:get_full_b_machine(_Name,BMachine),
5847 include(relevant_section,BMachine,RelevantSections),
5848 % TO DO: we could filter out enumerate/deferred sets not occuring in Pred
5849 translate_section_list(RelevantSections,SetsParas),
5850 atom_codes(ASP,SetsParas),
5851 ajoin(['MACHINE ', MchName, '\n',ASP,'CONSTANTS ',AllIds,'\nPROPERTIES\n ',PredAtom,'\nEND\n'],ResultAtom).
5852
5853 relevant_section(deferred_sets/_).
5854 relevant_section(enumerated_elements/_).
5855 relevant_section(parameters/_).
5856
5857 :- use_module(library(system),[ datime/1]).
5858 :- use_module(specfile,[currently_opened_file/1]).
5859 :- use_module(probsrc(version), [format_prob_version/1]).
5860 % print a Proof Obligation aka Sequent as a B machine
5861 nested_print_sequent_as_classicalb(Stream,HypsList,Goal,AllHypsList,MchName,ProofInfos) :-
5862 set_suppress_rodin_positions(false,Chng), % ensure we print Rodin labels if available
5863 call_cleanup(nested_print_sequent_as_classicalb_aux(Stream,HypsList,Goal,AllHypsList,MchName,ProofInfos),
5864 reset_suppress_rodin_positions(Chng)).
5865
5866 % convert identifier by adding backquote if necessary for unicode, reserved keywords, ...
5867 convert_id(b(identifier(ID),_,_),CAtom) :- !, convert_id(ID,CAtom).
5868 convert_id(Atom,CAtom) :- atom(Atom),!,pp_identifier(Atom,Codes,[]), atom_codes(CAtom,Codes).
5869 convert_id(E,CAtom) :- add_internal_error('Illegal id: ',E), CAtom = '?'.
5870 convert_and_ajoin_ids(UsedIds,AllIdsWithCommas) :-
5871 maplist(convert_id,UsedIds,ConvUsedIds),
5872 ajoin_with_sep(ConvUsedIds,', ',AllIdsWithCommas).
5873
5874 nested_print_sequent_as_classicalb_aux(Stream,HypsList,Goal,AllHypsList,MchName,ProofInfos) :-
5875 conjunct_predicates(HypsList,HypsPred),
5876 conjunct_predicates([Goal|HypsList],Pred),
5877 get_global_identifiers(Ignored,ignore_promoted_constants), % the sets section below will not print the promoted enumerated set constants, they may also not be valid for the selected hyps only
5878 find_typed_identifier_uses(Pred, Ignored, TUsedIds),
5879 get_texpr_ids(TUsedIds,UsedIds),
5880 convert_and_ajoin_ids(UsedIds,AllIds),
5881 bmachine:get_full_b_machine(_Name,BMachine),
5882 include(relevant_section,BMachine,RelevantSections),
5883 % TO DO: we could filter out enumerate/deferred sets not occuring in Pred
5884 translate_section_list(RelevantSections,SetsParas),
5885 set_print_type_infos(all,CHNG),
5886 datime(datime(Yr,Mon,Day,Hr,Min,_Sec)),
5887 format(Stream,'MACHINE ~w~n /* Exported: ~w/~w/~w ~w:~w */~n',[MchName,Day,Mon,Yr,Hr,Min]),
5888 (currently_opened_file(File), bmachine:b_machine_name(Name)
5889 -> format(Stream,' /* Origin: ~w : ~w */~n',[Name,File]) ; true),
5890 write(Stream,' /* '),format_prob_version(Stream), format(Stream,' */~n',[]),
5891 format(Stream,' /* Use static asssertion checking (probcli -cbc_assertions) to look for counter examples */~n',[]),
5892 maplist(format_proof_infos(Stream),ProofInfos),
5893 format(Stream,'~sCONSTANTS~n ~w~nPROPERTIES /* Selected Hypotheses: */~n',[SetsParas,AllIds]),
5894 add_typing_predicates(TUsedIds,HypsPred,HypsT),
5895 current_output(OldStream),
5896 set_output(Stream),
5897 nested_print_bexpr_as_classicalb2(HypsT,s(0)), % TODO: pass stream to this predicate
5898 format(Stream,'~nASSERTIONS /* Proof Goal: */~n',[]),
5899 nested_print_bexpr_as_classicalb2(Goal,s(0)), % TODO: pass stream to this predicate
5900 (AllHypsList = [] -> true
5901 ; sort(AllHypsList,SAL), sort(HypsList,SL),
5902 ord_subtract(SAL,SL,RemainingHypsList), % TODO: we could preserve order
5903 conjunct_predicates(RemainingHypsList,AllHypsPred),
5904 find_typed_identifier_uses(AllHypsPred, Ignored, TAllUsedIds),
5905 get_texpr_ids(TAllUsedIds,AllUsedIds),
5906 ord_subtract(AllUsedIds,UsedIds,NewIds), % compute new ids not used in selected hyps and goal
5907 (NewIds = []
5908 -> format(Stream,'OPERATIONS~n CheckRemainingHypotheses = SELECT~n',[])
5909 ; ajoin_with_sep(NewIds,', ',NIdLst),
5910 format(Stream,'OPERATIONS~n CheckRemainingHypotheses(~w) = SELECT~n',[NIdLst])
5911 ),
5912 nested_print_bexpr_as_classicalb2(AllHypsPred,s(0)), % TODO: pass stream to this predicate
5913 format(Stream,' THEN skip~n END /* CheckRemainingHypotheses */~n',[])
5914 ),
5915 set_output(OldStream),
5916 reset_print_type_infos(CHNG),
5917 format(Stream,'DEFINITIONS~n SET_PREF_DISPROVER_MODE == TRUE~n ; SET_PREF_TRY_FIND_ABORT == FALSE~n',[]),
5918 format(Stream,' ; SET_PREF_ALLOW_REALS == FALSE~n',[]),
5919 % The Rodin DisproverCommand.java usually enables CHR;
5920 % TODO: we could also look for options(List) in ProofInfos and check use_chr_solver/true in List, ...
5921 (get_preference(use_clpfd_solver,false) -> format(Stream,' ; SET_PREF_CHR == FALSE~n',[]) ; true),
5922 (get_preference(use_chr_solver,true) -> format(Stream,' ; SET_PREF_CHR == TRUE~n',[]) ; true),
5923 (get_preference(use_smt_mode,true) -> format(Stream,' ; SET_PREF_SMT == TRUE~n',[]) ; true),
5924 (get_preference(use_smt_mode,true) -> format(Stream,' ; SET_PREF_SMT == TRUE~n',[]) ; true),
5925 (get_preference(use_common_subexpression_elimination,true) -> format(Stream,' ; SET_PREF_CSE == TRUE~n',[]) ; true),
5926 (get_preference(smt_supported_interpreter,true) -> format(Stream,' ; SET_PREF_SMT_SUPPORTED_INTERPRETER == TRUE~n',[]) ; true),
5927 format(Stream,'END~n',[]).
5928
5929 format_proof_infos(_,Var) :- var(Var),!.
5930 format_proof_infos(Stream,disprover_result(Prover,Hyps,Result)) :- nonvar(Result),functor(Result,FR,_),!,
5931 format(Stream,' /* ProB Disprover ~w result on ~w : ~w */~n',[Prover,Hyps,FR]).
5932 format_proof_infos(Stream,E) :- format(Stream,' /* ~w */~n',[E]).
5933
5934
5935 % ---------------------------------------
5936
5937
5938 % show non obvious functors
5939 get_texpr_top_level_symbol(TExpr,Symbol,2,infix) :-
5940 translate:binary_infix_symbol(TExpr,Symbol),!.
5941 get_texpr_top_level_symbol(b(E,_,_),Symbol,1,postfix) :-
5942 functor(E,F,1), translate:unary_postfix_in_mode(F,Symbol,_),!.
5943 get_texpr_top_level_symbol(b(E,_,_),Symbol,3,prefix) :-
5944 functor(E,F,Arity), (Arity=3 ; Arity=2), % 2 for exists
5945 quantified_in_mode(F,Symbol),!.
5946 get_texpr_top_level_symbol(b(E,_,_),Symbol,N,prefix) :-
5947 functor(E,F,N),
5948 function_like_in_mode(F,Symbol).
5949
5950 % ---------------
5951
5952 % feedback to user about values
5953 translate_bvalue_kind([],Res) :- !, Res='EMPTY-Set'.
5954 translate_bvalue_kind([_|_],Res) :- !, Res='LIST-Set'.
5955 translate_bvalue_kind(avl_set(A),Res) :- !, avl_size(A,Size), ajoin(['AVL-Set:',Size],Res).
5956 translate_bvalue_kind(int(_),Res) :- !, Res = 'INTEGER'.
5957 translate_bvalue_kind(term(floating(_)),Res) :- !, Res = 'FLOAT'.
5958 translate_bvalue_kind(string(_),Res) :- !, Res = 'STRING'.
5959 translate_bvalue_kind(pred_true,Res) :- !, Res = 'TRUE'.
5960 translate_bvalue_kind(pred_false,Res) :- !, Res = 'FALSE'.
5961 translate_bvalue_kind(fd(_,T),Res) :- !, Res = T.
5962 translate_bvalue_kind((_,_),Res) :- !, Res = 'PAIR'.
5963 translate_bvalue_kind(rec(_),Res) :- !, Res = 'RECORD'.
5964 translate_bvalue_kind(freeval(Freetype,_Case,_),Res) :- !, Res = Freetype.
5965 translate_bvalue_kind(CL,Res) :- custom_explicit_sets:is_interval_closure(CL,_,_),!, Res= 'INTERVAL'.
5966 translate_bvalue_kind(CL,Res) :- custom_explicit_sets:is_infinite_explicit_set(CL),!, Res= 'INFINITE-Set'.
5967 translate_bvalue_kind(closure(_,_,_),Res) :- !, Res= 'SYMBOLIC-Set'.
5968
5969
5970 % ---------------------------------------