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