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