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