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