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