1 % (c) 2009-2026 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(haskell_csp,[%clear_cspm_spec/0, % triggerred by clear specification event
6 parse_and_load_cspm_file/1, load_cspm_pl_file/1,
7
8 cspm_trans_enum/3,
9 animatable_process/1, animatable_process_cli/1,animatable_process_without_arguments/1,
10 channel/2, %cspPrintCompiled/2,
11 evaluate_argument/2, force_evaluate_argument/2, evaluate_int_argument/2,
12 force_evaluate_argument_for_member_check/2,
13 check_boolean_expression/1,
14
15 enumerate_channel_input_value/4,
16 enumerate_datatype_el/5,
17
18 is_a_datatype/2, csp_constructor/3,
19 %% csp_full_type_constructor/3,csp_full_type_constant/2, % exported by haskell_csp_analyzer.pl
20 dataTypeDef/2,
21 channel_type_list/2,
22 agent_compiled/3, % called in slicer_csp.pl ???
23 is_not_infinite_type/1,
24 channel_type_is_finite/2,
25 get_symbol_span/2,
26 extract_span_from_event/4, extract_span_info/2,
27 get_internal_csp_representation/1,
28 get_csp_assertions_as_string/2,get_csp_assertions/1, get_csp_processes/1,
29 translate_csp_assertion/2, %translate_csp_assertions/2, %get_csp_assertions_enum/2,
30 parse_and_load_cspm_file_into_specific_pl_file/2,
31 evaluate_type_list/2,
32 %% get_formula_from_cspm_file/2,
33 filter_formulas_from_pragmas/3,
34 add_error_with_span/4,add_internal_error_with_span/4,
35 evaluate_csp_expression/2,evaluate_csp_expression/3, parse_single_csp_expression/3,
36 evaluate_parsed_csp_expression_with_timing/2,
37 parse_single_csp_declaration/3,
38 add_symbol_error/4,
39 bindval/3, agent/3, agent_curry/3, subTypeDef/2, nameType/2,
40 symbol/4, cspTransparent/1, cspPrint/1, valid_constant/1,
41 parse_single_csp_expression_file/3,
42 %% perform_csp_self_check/0,
43 normalise_cspm_state/2,
44 check_compiled_term/1,
45 get_cspm_identifier/2,
46 ignore_infinite_datatypes/0 % TODO: get rid of this ugly hack
47 ]).
48
49
50 :- meta_predicate read_compiled_prolog_file(-,-,1).
51
52 :- use_module(probsrc(module_information)).
53 :- module_info(group,csp).
54 :- module_info(description,'Interpreter for CSP.').
55
56 :- use_module(library(lists)).
57 :- use_module(library(file_systems)).
58 %% :- use_module(library(process)).
59 %% :- use_module(library(system)).
60
61 /* the new CSP interpreter using the format produced by
62 Marc's Haskell compiler fecsp/cspcomp */
63
64 /********* PROB modules *********/
65 :- use_module(probsrc(error_manager)).
66 :- use_module(probsrc(self_check)).
67 :- use_module(probsrc(debug)).
68 :- use_module(probsrc(typechecker)).
69 :- use_module(probsrc(kernel_objects),[top_level_dif/2,enumerate_basic_type/3]).
70 :- use_module(probsrc(tools),[string_concatenate/3,flatten/2,split_atom/3, get_set_optional_prolog_flag/3]).
71 :- use_module(probsrc(preferences),[preference/2, set_preference/2, get_preference/2,init_preferences/0]).
72 :- use_module(probsrc(system_call),[system_call/4,system_call/5, get_writable_compiled_filename/3]).
73 :- use_module(probsrc(kernel_waitflags)).
74 :- use_module(probsrc(translate),[translate_cspm_state/2,translate_cspm_expression/2]).
75 :- use_module(probsrc(specfile),[process_algebra_mode/0,csp_with_bz_mode/0,currently_opened_file/1]).
76 /******** ------------ *********/
77
78 :- set_prolog_flag(double_quotes, codes).
79
80 /* Predicate for performing self check for all CSP modules */
81
82 :- public perform_general_csp_self_check/0.
83 perform_general_csp_self_check :-
84 perform_csp_self_check,
85 get_preference(use_clpfd_solver,Value),
86 (Value=false ->
87 NewValue = true
88 ; NewValue = false),
89 set_preference(use_clpfd_solver,NewValue),
90 perform_csp_self_check,
91 % reverting to the old use_clpfd_solver preference
92 set_preference(use_clpfd_solver,Value).
93
94 perform_csp_self_check :-
95 init_preferences,
96 perform_self_check(csp_basic),
97 perform_self_check(csp_tuples),
98 perform_self_check(csp_sequences),
99 perform_self_check(csp_sets),
100 perform_self_check(haskell_csp),
101 perform_self_check(haskell_csp_analyzer).
102
103 /* ------------------------------------- */
104
105
106 :- dynamic channel/2, bindval/3, agent/3, agent_curry/3, dataTypeDef/2, subTypeDef/2.
107 :- dynamic nameType/2, symbol/4, cspTransparent/1, cspPrint/1, assertRef/5.
108 :- dynamic assertModelCheck/3, assertModelCheckExt/4, pragma/1.
109 %:- dynamic assertLtl/4, assertCtl/4. % dynamic declarations still generated by parser it seems, but not used
110
111 :- discontiguous channel/2, agent/3, bindval/3, assertModelCheck/3.
112
113 :- use_module(probcspsrc(haskell_csp_analyzer)).
114 :- use_module(probcspsrc(csp_tuples)).
115 :- use_module(probcspsrc(csp_sets)).
116 :- use_module(probcspsrc(csp_basic)).
117
118 /* ------------------------------------- */
119 /* Sample .pl Translation of a CSP file */
120
121 dataTypeDef('FRUIT',[constructor(apples),constructor(oranges),constructor(pears)]).
122 channel(left,type(dotTupleType(['FRUIT']))).
123 bindval('SEND',prefix(span,[in(_x)],left,prefix(span,[out(_x)],mid,prefix(span,[],ack,val_of('SEND',no_loc_info_available))),span2),span).
124 symbol('SEND','SEND',src,'Process').
125
126
127 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
128 :- register_event_listener(start_unit_tests,reset_for_selfcheck,'Setup CSP dataTypeDef, channel,..').
129 %:- register_event_listener(stop_unit_tests, set_silent(false), 'Printing wf warnings again').
130
131 reset_for_selfcheck :- % TO DO: reset all facts and link with event_handling
132 clear_cspm_spec,
133 retractall(dataTypeDef(_,_)),
134 assertz( dataTypeDef('FRUIT',[constructor(apples),constructor(oranges),constructor(pears)])),
135 /* for testing is_not_infinite_type predicate */
136 assertz( dataTypeDef('Msg',[constructor('A'),constructor('B'),constructorC('con',dotTupleType(['SubMsg']))]) ),
137 assertz( dataTypeDef('Msg1',[constructor('A'),constructor('B')]) ),
138 assertz( dataTypeDef('SubMsg',[constructor('KA'),
139 constructorC(conc,dotTupleType(['Msg'])),constructorC(ste,dotTupleType([builtin_call('Seq'('Msg'))]))]) ),
140 assertz( dataTypeDef('Inf',[constructorC(ste,dotTupleType([builtin_call('Seq'('FRUIT'))]))]) ),
141 retractall( channel(_,_)),
142 assertz( channel(left,type(dotTupleType(['FRUIT']))) ),
143 assertz( channel(right,type(dotTupleType(['FRUIT']))) ),
144 assertz( channel(mid,type(dotTupleType(['FRUIT']))) ),
145 assertz( channel(receive,type(dotTupleType(['Msg']))) ),
146 assertz( channel(infinite,type(dotTupleType(['Inf']))) ),
147 retractall( bindval(_,_,_) ),
148 assertz( bindval('SEND',
149 prefix(no_loc_info_available,[in(_x)],left,
150 prefix(no_loc_info_available,[out(_x)],mid,
151 prefix(no_loc_info_available,[],ack,val_of('SEND',no_loc_info_available),no_loc_info_available),
152 no_loc_info_available),
153 no_loc_info_available),no_loc_info_available) ),
154 assertz( bindval('REC',prefix(no_loc_info_available,[in(_x)],mid,
155 prefix(no_loc_info_available,[out(_x)],right,
156 prefix(no_loc_info_available,[],ack,val_of('REC',no_loc_info_available),no_loc_info_available),
157 no_loc_info_available),no_loc_info_available),no_loc_info_available) ),
158 assertz( bindval('SYSTEM',sharing(closure([mid,ack]),val_of('SEND',no_loc_info_available),
159 val_of('REC',no_loc_info_available),no_loc_info_available),no_loc_info_available) ),
160 assertz( bindval('GEN1',
161 prefix(no_loc_info_available,[out(oranges)],
162 left,
163 prefix(no_loc_info_available,[out(oranges)],right,val_of('GEN2',no_loc_info_available),no_loc_info_available),
164 no_loc_info_available),no_loc_info_available) ),
165 assertz( bindval('GEN2',
166 prefix(no_loc_info_available,[out(pears)],left,
167 prefix(no_loc_info_available,[out(pears)],
168 right,val_of('GEN1',no_loc_info_available),no_loc_info_available),no_loc_info_available),no_loc_info_available) ),
169 assertz( bindval('MAIN',sharing(closure([left,right]),val_of('SYSTEM',no_loc_info_available),val_of('GEN1',no_loc_info_available),no_loc_info_available),no_loc_info_available) ),
170 assertz( bindval('P1',agent_call(no_loc_info_available,'Q',[int(10)]),no_loc_info_available) ),
171 retractall(agent(_,_,_)),
172 assertz( agent('P'(_),'prefix'('src_span'(8,8,8,9,87,1),['in'(_i2)],'c',
173 'prefix'('src_span'(8,15,8,16,94,1),['out'(_i2)],'c',
174 'stop'('src_span'(8,22,8,26,101,4)),'src_span'(8,19,8,21,97,10)),
175 'src_span'(8,12,8,14,90,17)),'src_span'(8,8,8,26,87,18)) ),
176 %assertz( agent('P2'(_n),agent_call(no_loc_info_available,'Q',['-'(_n, int(10))]),no_loc_info_available) ),
177 %assertz( agent('P1',agent_call(no_loc_info_available,'Q',[int(10)]),no_loc_info_available) ),
178 assertz( agent('Q'(_n),ifte('=='(_n,int(0)),stop(no_loc_info_available),
179 prefix(no_loc_info_available,[],'a',
180 agent_call(no_loc_info_available,'Q',['-'(_n,'int'(1))]),no_loc_info_available),
181 no_loc_info_available,no_loc_info_available,no_loc_info_available),no_loc_info_available) ),
182 retractall(symbol(_,_,_,_)),
183 assertz( symbol('SEND','SEND',src,'Process') ),
184 assertz( symbol('REC','REC',src(8,1,8,4,4,3),'Procsess') ),
185 assertz( symbol('SYSTEM','SYSTEM',src,'Process') ),
186 assertz( symbol('GEN1','GEN1',src,'Process') ),
187 assertz( symbol('GEN2','GEN2',src,'Process') ),
188 assertz( symbol('MAIN','MAIN',src(3,1,3,5,20,4),'Process') ),
189 retractall(assertRef(_,_,_,_,_)),
190 assertz( assertRef('False','val_of'('MAIN',no_loc_info_available),'Trace',
191 'val_of'('PROB_TEST_TRACE',no_loc_info_available),no_loc_info_available) ),
192 assertz( assertRef('True', 'val_of'('PROB_TEST_TRACE',no_loc_info_available),
193 'Trace', 'val_of'('MAIN',no_loc_info_available),no_loc_info_available) ),
194 retractall(assertModelCheckExt(_,_,_,_)),
195 assertz( assertModelCheckExt('False',
196 sharing(closure([left,right]),val_of('SYSTEM',no_loc_info_available),
197 val_of('GEN1',no_loc_info_available),no_loc_info_available), 'Deterministic','F') ),
198 assertz( assertModelCheckExt('True',
199 sharing(closure([left,right]),val_of('SYSTEM',no_loc_info_available),
200 val_of('GEN1',no_loc_info_available),no_loc_info_available), 'DeadlockFree','FD') ),
201 retractall(assertModelCheck(_,_,_)),
202 assertz( assertModelCheck('False',
203 'prefix'(no_loc_info_available,[],'dotTuple'(['a','int'(1)]),
204 'val_of'('P',no_loc_info_available),no_loc_info_available),'LivelockFree')),
205 retractall(pragma(_)),
206 assertz(pragma('assert_ltl "GF(a)"')),
207 assertz(pragma('ASSERT_LTL "GF(b)"')),
208 assertz(pragma('ASSERT_LTL_TRUE "true"')),
209 haskell_csp_analyzer:analyze.
210
211
212 % these predicates are generated by the csp analyzer, there are not the standard generated predicates from the translation
213 % process csp -> pl
214
215 /* ------------------------------------- */
216
217 /* ------------------------------------- */
218
219 animatable_process_without_arguments(X) :-
220 symbol(RenamedX,X,_,_),
221 (is_csp_process(RenamedX);is_possible_csp_process(RenamedX)).
222
223 animatable_process(X) :-
224 ? (symbol(RenamedX,X,_,_),(is_csp_process(RenamedX);is_possible_csp_process(RenamedX))) ;
225 (nonvar(X), X=agent_call(_Src,_F,_Args)) ;
226 (nonvar(X), X=agent_call_curry(_F,_Args)) ;
227 ? (agent(F,_,_),is_csp_process(F),animatable_process_with_arguments(F,proc(FName,N)),proc_with_arguments_to_string(FName,N,X)).
228
229 animatable_process_cli(X) :-
230 symbol(RenamedX,X,_,_),
231 (is_csp_process(RenamedX) ; is_possible_csp_process(RenamedX)).
232
233 animatable_process_with_arguments(X,proc(F,N)) :-
234 functor(X,F,N),N>0.
235
236 check_compiled_term(Term) :-
237 nonvar(Term),!,
238 Term=agent_call(_Src,F,Args),
239 length(Args,N),
240 ( (symbol(RenamedF,F,_,_),functor(P,RenamedF,N),is_csp_process(P)) ->
241 true
242 ; translate_cspm_state(Term,Proc),
243 add_error_fail(check_compiled_term, 'There is no such process in file: ',Proc)
244 ).
245
246 /* ------------------------------------- */
247
248 /* Predicates for calling the CSPM Parser and loading the corresponding to the Csp File Prolog File */
249
250 parse_and_load_cspm_file(CSPFile) :-
251 \+ file_exists(CSPFile),
252 !,
253 add_error_fail(parse_and_load_cspm_file,'CSP file does not exist:',CSPFile).
254 parse_and_load_cspm_file(CSPFile) :-
255 get_writable_compiled_filename(CSPFile,'.pl',PrologFile),
256 parse_and_load_cspm_file_into_specific_pl_file(CSPFile,PrologFile).
257
258 %% parse_and_load_cspm_file(CSPFile) :-
259 %% (parsercall: call_cspmj_parser(CSPFile,PrologFile)
260 %% -> load_cspm_pl_file(PrologFile,CSPFile)
261 %% ; add_error(parse_and_load_cspm_file,'Error while parsing CSP file: ',CSPFile),
262 %% add_error_fail(parse_and_load_cspm_file,'Std error: ','to be added')
263 %% ).
264
265 :- use_module(probsrc(tools_printing), [format_error_with_nl/2]).
266 /* Specific predicate for parsing and re-writting the Parse-Output into already existing prolog file.*/
267 % It will be needed by parsing a temporary files when the Csp Assertion Viewer is used.
268 parse_and_load_cspm_file_into_specific_pl_file(CSPFile, PrologFile) :-
269 debug_println(15,reading_cspm_file(CSPFile)),
270 get_cspm_parser_command(AbsParseCmd),
271 debug_println(5,parsecmd(AbsParseCmd)),
272 string_concatenate('--prologOut=', PrologFile, PrologFileOutArg),
273 debug_stats(parsing(AbsParseCmd,'translate',PrologFileOutArg, CSPFile)),
274 system_call(AbsParseCmd, ['translate',PrologFileOutArg, CSPFile], OutputText,ErrText,JExit),
275 debug_stats(done_parsing),
276 debug_println(15,parse_exit(JExit)),
277 (JExit=exit(0)
278 -> load_cspm_pl_file(PrologFile,CSPFile)
279 ; add_error(parse_and_load_cspm_file,'Error while parsing CSP file: ',CSPFile),
280 format_error_with_nl('Result of ~w: ~w',[AbsParseCmd,JExit]),
281 format_error_with_nl('Output:~s',[OutputText]),
282 format_error_with_nl('Error:~s',[ErrText]),
283 fail
284 ).
285
286 parse_single_csp_declaration(Decl,CSPFile,Result) :-
287 get_cspm_parser_command(Cmd),
288 string_concatenate('--declarationToPrologTerm=', Decl, DeclarationArgument),
289 system_call(Cmd, ['translate', DeclarationArgument, CSPFile],Text,ErrText,JExit),
290 (JExit=exit(0)
291 -> read_from_codes(Text,Result)
292 ; atom_codes(ErrT,ErrText),
293 add_error_fail(parsing_csp_declaration,'Std error: ',ErrT)
294 ).
295
296 :- use_module(probsrc(xtl_interface),[last_opened_cspm_file/1]).
297 parse_single_csp_expression(Context,Expr,Res) :-
298 ( Context==eval -> Filename='no-file'
299 ; Context==ltl ->
300 (csp_with_bz_mode
301 -> last_opened_cspm_file(Filename)
302 ; currently_opened_file(Filename)
303 )
304 ; add_internal_error('Internal Error: Unknown context argument: ', Context),fail
305 ),
306 parse_single_csp_expression_file(Expr,Filename,Res).
307
308 :- use_module(library(codesio)).
309 parse_single_csp_expression_file(Expr,CSPFile,Res) :-
310 get_cspm_parser_command(Cmd),
311 string_concatenate('--expressionToPrologTerm=', Expr, ExpressionArgument),
312 system_call(Cmd, ['translate', ExpressionArgument, CSPFile],Text,ErrText,JExit),
313 (JExit=exit(0)
314 -> read_from_codes(Text,Result),
315 translate_expression(Result,Res)
316 ; atom_codes(ErrT,ErrText),
317 add_error_fail(parsing_csp_expression,'Std error: ',ErrT)
318 ).
319
320 evaluate_csp_expression(Expr,Result) :-
321 ( parse_single_csp_expression(eval,Expr,ParsedExpr) ->
322 evaluate_parsed_csp_expression(ParsedExpr,Expr,Result)
323 ; add_error_fail(parsing_csp_expression, 'Error while parsing expression: ', Expr)
324 ).
325
326 evaluate_parsed_csp_expression(ParsedExpr,Expr,Result) :-
327 debug_println(9,parsed_csp_expression(ParsedExpr)),
328 haskell_csp_analyzer:compile_body(ParsedExpr,'evaluate',[],[],CompiledExpr),
329 ( evaluate_parsed_csp_expression_with_timing(CompiledExpr,Res) ->
330 ( translate_cspm_expression(Res, R) -> R=Result
331 ; add_error_fail(pretty_printing_evaluated_expression, 'Error while pretty-printing result: ', Res)
332 )
333 ; add_error_fail(evaluating_expression, 'Error while evaluating expression: ',Expr)
334 ).
335
336 evaluate_csp_expression(Expr,CSPFile,Result) :-
337 ( parse_single_csp_expression_file(Expr, CSPFile,ParsedExpr) ->
338 evaluate_parsed_csp_expression(ParsedExpr,Expr,Result)
339 ; add_error_fail(parsing_csp_expression, 'Error while parsing typed expression: ', Expr)
340 ).
341
342 :- use_module(probsrc(tools),[cputime/1]).
343 evaluate_parsed_csp_expression_with_timing(ParsedExpr,Res) :-
344 cputime(T1),
345 evaluate_expression(ParsedExpr,Res),
346 cputime(T2),
347 D is T2-T1,
348 print('% Time to evaluate expression: '),print(D), print(' ms.%'),nl.
349
350 % TODO: Which are the expressions allowed to be written in events
351 translate_expression(listExp(rangeEnum(List)),Res) :- !, Res=list(List).
352 translate_expression(setExp(rangeEnum(List)),Res) :- !, Res=setValue(List).
353 translate_expression(dotTuple(List),dotTuple(Res)) :- !,
354 maplist(translate_expression,List,Res).
355 translate_expression(X,X).
356
357 /* Predicates for reading a Prolog file (usually generated after translating the appropriate Csp file with the CSPM-Tool)
358 and filtering the asssertion declarations from it. Needed for the 'Check Csp Assertions' window in Tcl_Tk. */
359 read_compiled_prolog_file(CSPFile,Result,PredName) :-
360 get_writable_compiled_filename(CSPFile,'.pl', PrologFile),
361 debug_print(9,'opening Prolog file: '), debug_println(9,PrologFile),
362 my_see(PrologFile),
363 call(PredName,Result),
364 !,seen,debug_println(9,done).
365
366 my_see(File) :-
367 catch(see(File),
368 error(existence_error(_,_),_),
369 add_error_fail(my_see,'File does not exist: ',File)).
370
371 filter_assertion_declarations(Assertions) :-
372 read(Term), !,
373 ((Term = end_of_file) -> (Assertions = [])
374 ; (is_assertion(Term)
375 -> (Assertions = [Term|T])
376 ; (Assertions = T)
377 ), filter_assertion_declarations(T)
378 ).
379
380 :- assert_must_succeed((is_assertion(assertRef(_,_,_,_,_)),is_assertion(assertModelCheck(_,_,_)), is_assertion(assertModelCheckExt(_,_,_,_)))).
381
382 is_assertion(assertRef(_,_,_,_,_)).
383 is_assertion(assertModelCheck(_,_,_)).
384 is_assertion(assertModelCheckExt(_,_,_,_)).
385 is_assertion(assertLtl(_,_,_,_)).
386 is_assertion(assertCtl(_,_,_,_)).
387
388 filter_formulas_from_pragmas(Type,FlNList,FlFList) :-
389 findall(Formulas,(pragma(S),get_formulas_from_pragma(Type,pragma(S),_Names,Formulas)),FList),
390 findall(Names,(pragma(S),get_formulas_from_pragma(Type,pragma(S),Names,_Formulas)),NList),
391 flatten(NList,FlNList),
392 flatten(FList,FlFList).
393
394 get_formula_from_cspm_file(Type,Formula) :-
395 filter_formulas_from_pragmas(Type,_Ns,[String|_]),
396 (var(String) ->
397 Formula = ''
398 ; Formula=String
399 ).
400
401 get_formulas_from_cspm_file(Type,String) :-
402 filter_formulas_from_pragmas(Type,_Ns,Formulas),
403 convert_string_list_to_string(Formulas,String).
404
405 string_concatenate_sep(Sep,Atom,R) :-
406 string_concatenate(Atom,Sep,R).
407
408 convert_string_list_to_string(L,Res) :-
409 maplist(string_concatenate_sep(';'),L,LRes),
410 concatenate_string_list(LRes,Res).
411
412 get_formulas_from_pragma(Type,pragma(Str),Names,Formulas) :-
413 atom_codes(Str,CodeList),
414 (Type = ltl ->
415 ? ltl_equations(Names,Formulas,CodeList,[])
416 ;Type = ctl ->
417 ctl_equations(Names,Formulas,CodeList,[])
418 ;
419 Names=[], Formulas=[]
420 ).
421
422 %%%%%%%%%%%%%%%%%% Tests for the ASSERT_LTL Equations Parser below %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
423
424 :- assert_must_succeed((haskell_csp:reset_for_selfcheck)).
425 :- assert_must_succeed((haskell_csp: get_formulas_from_pragma(ltl,pragma('ASSERT_LTL_123=="F(e(a))" "Checking simple LTL property."'),
426 Names,Formulas),Names==[123],Formulas==['F(e(a))'])).
427 :- assert_must_fail((haskell_csp: get_formulas_from_pragma(ltl,pragma('ASSERT_LTL_0123=="F(e(a))" "First digit in number must be nonzero."'),
428 _Names,_Formulas))).
429 :- assert_must_succeed((haskell_csp: get_formulas_from_pragma(ltl,pragma('ASSERT_LTL=="F(e(a))"'),
430 Names,Formulas),Names==[[95]],Formulas==['F(e(a))'])).
431 :- assert_must_succeed((haskell_csp: get_formulas_from_pragma(ltl,pragma('assert_ltl "F(e(a))" "Checking simple LTL property."'),
432 Names,Formulas),Names==[[95]],Formulas==['F(e(a))'])).
433 :- assert_must_succeed((haskell_csp: get_formulas_from_pragma(ctl,pragma('assert_ctl "true" "Checking simple CTL property."'),
434 Names,Formulas),Names==[[95]],Formulas==['true'])).
435 :- assert_must_succeed((haskell_csp: get_formulas_from_pragma(ltl,pragma('assert_ltl "F(e(a))" "Parsing multiple LTL equations."; ASSERT_LTL_TRUE "F(e(b))"; ASSERT_LTL_2=="F(e(c))"; ASSERT_LTL "F(e(d))"'),
436 Names,Formulas),Names==[[95],[84,82,85,69],2,[95]],Formulas==['F(e(a))','F(e(b))','F(e(c))','F(e(d))'])).
437 :- assert_must_succeed((
438 haskell_csp: get_formulas_from_cspm_file(ltl,S), S == 'GF(a);GF(b);true;')).
439 :- assert_must_succeed((
440 haskell_csp: get_formula_from_cspm_file(ltl,S), S == 'GF(a)')).
441
442 %%%%%%%%%%%%%%%%%% Simple Parser for Parsing ASSERT_LTL Equations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
443
444 %%%%%%%%%%%%% CTL assertions %%%%%%%%%%%%%%%
445 ctl_equations([N|Ns],[F|Fs]) --> ctl_equation(N,F),ctl_equations2(Ns,Fs).
446 ctl_equations2(Ns,Fs) --> ows,sep,ows,ctl_equations(Ns,Fs),{Fs\=[],Ns\=[]}.
447 ctl_equations2([],[]) --> ows.
448
449 ctl_equation(N,F) --> ows,assert_id_ctl(N), ows, eq,!, ows, string(F), ows, optional_string.
450
451 assert_id_ctl(N) --> ass_ctl,!,ass_name(N).
452 assert_id_ctl(N) --> "assert_ctl",{N="_"},!.
453 assert_id_ctl(N) --> "ASSERT_CTL",{N="_"},!.
454
455 ass_ctl --> "ASSERT_CTL_".
456 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
457
458 ?ltl_equations([N|Ns],[F|Fs]) --> ltl_equation(N,F),ltl_equations2(Ns,Fs).
459 ?ltl_equations2(Ns,Fs) --> ows,sep,ows,ltl_equations(Ns,Fs),{Fs\=[],Ns\=[]}.
460 ltl_equations2([],[]) --> ows.
461
462 ltl_equation(N,F) --> ows,assert_id_ltl(N), ows, eq,!, ows, string(F), ows, optional_string.
463
464 string(Atom) --> [34], stringcontent(String), [34], {atom_codes(Atom,String)}. %34 is Ascii Code of "
465
466 optional_string --> [34], stringcontent(_String), [34],!.
467 optional_string --> "",!.
468
469 stringcontent([C|Rest]) --> [C], {C \= 34}, !, stringcontent(Rest).
470 stringcontent([]) --> [].
471
472 assert_id_ltl(N) --> ass,!,ass_name(N).
473 assert_id_ltl(N) --> "assert_ltl",{N="_"},!.
474 assert_id_ltl(N) --> "ASSERT_LTL",{N="_"},!.
475
476 ?ass_name(N) --> num(N),{number(N)},!.
477 ass_name(N) --> name_tail(N),!.
478
479 name_tail([C|Cs]) --> [C],{is_digit(C) ;
480 (0'A =< C,C =< 0'Z) ;
481 (0'a =< C,C =< 0'z) ;
482 C=0'_},
483 name_tail(Cs),!.
484 name_tail([]) --> [],!.
485
486 num(Number) --> nonzerodigit(D), num2(Rest),{number_codes(Number,[D|Rest])}.
487 num(Number) --> digit(D),{number_codes(Number,[D])}.
488 num2([D|Rest]) --> digit(D),!,num2(Rest).
489 num2([]) --> [].
490
491 digit(D) --> [D], {is_digit(D)},!.
492 nonzerodigit(ND) --> [ND], {is_nz_digit(ND)},!.
493
494 is_digit(D) :- 0'0 =< D, D =< 0'9.
495 is_nz_digit(D) :- 0'0 < D, D =< 0'9.
496
497 ?sep --> [C],{member(C,";,")}.
498
499 ?ows --> [C], {member(C," \t\n\r")}, !, ows.
500 ows --> "".
501
502 eq --> "==",!.
503 eq --> [32],!.
504 eq --> "",!.
505
506 ass --> "ASSERT_LTL_",!.
507
508 /* ------------------------------------------------------------------------------------------------------------- */
509
510 /* Predicates for getting the CSPM-Tool command from the library and loading cspm Prolog files.*/
511 get_cspm_parser_command(AbsParseCmd) :-
512 debug_println(9,getting_parser_cmd),
513 catch(
514 absolute_file_name(prob_lib(cspmf),AbsParseCmd,[access(exist),extensions(['.exe',''])]),
515 error(E,_),
516 add_error_fail(haskell_csp,'Could not find CSP-M Parser. Be sure to install cspmf in your ProB lib directory. ',E)),
517 debug_println(9,parser(AbsParseCmd)).
518
519
520 :- dynamic parseResult/5.
521 load_cspm_pl_file(PFile) :- load_cspm_pl_file(PFile,PFile).
522 load_cspm_pl_file(PrologFile,CSPFile) :- clear_cspm_spec,
523 \+ file_exists(PrologFile),!,
524 add_error(haskell_csp,'Could not generate Prolog encoding of CSP file: ',CSPFile),fail.
525 load_cspm_pl_file(PrologFile,CSPFile) :-
526 debug_println(15,consulting(PrologFile)),
527 cia_consult_without_redefine_warning(PrologFile), debug_stats(done_loading_pl_file),
528 /* TO DO: replace by safer load which checks that
529 only correct facts are loaded !!!! */
530 parseResult(ParseResult,ErrorMsg,StartLine,SC,Off),
531 (ParseResult='ok' -> analyze ;
532 add_error(haskell_csp,'Error while parsing CSP-M: ',ParseResult:CSPFile),
533 add_error(haskell_csp,'CSP-M Parse error message: ',ErrorMsg,src_position(StartLine,SC,Off,1))
534 ).
535
536 /* ------------------------------------------------------------------------------------------------------------ */
537
538 % A small pretty-printer for printing assert declarations
539 refinement_operator('Trace',' [T= ') :- !.
540 refinement_operator('Failure', ' [F= ') :- !.
541 refinement_operator('FailureDivergence',' [FD= ') :- !.
542 refinement_operator('RefusalTesting',' [R= ') :- !.
543 refinement_operator('RefusalTestingDiv',' [RD= ') :- !.
544 refinement_operator('RevivalTesting',' [V= ') :- !.
545 refinement_operator('RevivalTestingDiv',' [VD= ') :- !.
546 /* the clauses below will be called if we check the particular assertion direct from the command line and not from the .pl file */
547 refinement_operator('[T=',' [T= ') :- !.
548 refinement_operator('[F=', ' [F= ') :- !.
549 refinement_operator('[FD=',' [FD= ') :- !.
550 refinement_operator('[R=',' [R= ') :- !.
551 refinement_operator('[RD=',' [RD= ') :- !.
552 refinement_operator('[V=',' [V= ') :- !.
553 refinement_operator('[VD=',' [VD= ') :- !.
554 refinement_operator(A, _) :- add_error_fail(haskell_csp, 'Error while pretty-printing assert declaration. Invalid or unsupported refinement operator: ', A).
555
556 adding_not('True', 'not ') :- !.
557 adding_not('False', '') :- !.
558 adding_not(A,_) :- add_error_fail(haskell_csp,'Error while pretty-printing assert declaration. Unexpected argument infront the assertion declaration: ',A).
559
560 fdr_model('Deterministic', ' :[ deterministic ') :- !.
561 fdr_model('DeadlockFree', ' :[ deadlock free ') :- !.
562 fdr_model('LivelockFree', ' :[ livelock free ') :- !.
563 fdr_model(A,_) :- add_error_fail(haskell_csp, 'Error while pretty-printing assert declaration. Invalid or unsupported model inside of process assertion: ', A).
564
565 fdr_single_model('Deterministic', ' :[ deterministic [FD] ]') :- !.
566 fdr_single_model('DeadlockFree', ' :[ deadlock free [FD] ]') :- !.
567 fdr_single_model('LivelockFree', ' :[ livelock free ]') :- !.
568 fdr_single_model(A,_) :- add_error_fail(haskell_csp, 'Error while pretty-printing assert declaration. Invalid or unsupported model inside of process assertion: ', A).
569
570 fdr_ext('F', '[F] ]') :- !.
571 fdr_ext('FD', '[FD] ]') :- !.
572 fdr_ext(Ext, _) :- add_error_fail(haskell_csp, 'Not supported assertion type model: ',Ext).
573
574 :- assert_must_fail(proc_with_arguments_to_string('P',0,_)).
575 :- assert_must_fail(proc_with_arguments_to_string('P',-10,_)).
576 :- assert_must_succeed((proc_with_arguments_to_string('P',1,String), String=='P(-)')).
577 :- assert_must_succeed((proc_with_arguments_to_string('P',3,String), String=='P(-,-,-)')).
578
579 proc_with_arguments_to_string(Fun,N,FunRes) :-
580 ( N>1 ->
581 count_proc_arguments(N,R),
582 concatenate_string_list([Fun,'('|R],FunRes)
583 ; N =:= 1 ->
584 string_concatenate(Fun,'(-)',FunRes)
585 ).
586
587 count_proc_arguments(N,Res) :-
588 count_proc_arguments(N,['-',')'],Res).
589
590 count_proc_arguments(N,L,Res) :-
591 (N =:= 1 ->
592 Res=L
593 ; N>1 ->
594 N1 is N-1,
595 count_proc_arguments(N1,['-',','|L],Res)
596 ).
597
598 :- assert_must_succeed((string_to_proc_term('P(-,-,-)',Term), Term = 'P'(_A,_B,_C))).
599 :- assert_must_succeed((string_to_proc_term('P(-)',Term), Term = 'P'(_X))).
600 :- assert_must_succeed((string_to_proc_term('P',Term), Term = 'P')).
601 :- assert_must_succeed((string_to_proc_term(p(1,2),Term), Term == p(1,2))).
602
603 string_to_proc_term(Proc,Term) :-
604 atom(Proc),!,
605 split_atom(Proc,['(',',',')'],[Fun|A]),
606 length(A,N),
607 gen_vars(N,Args),
608 Term =.. [Fun|Args].
609 string_to_proc_term(X,X).
610
611 :- assert_must_succeed((string_to_proc_term('P(-,-,-)',Term), functor(Term,F,N), proc_with_arguments_to_string(F,N,Str), Str == 'P(-,-,-)')).
612
613 gen_vars(N,Vars) :-
614 ( N>0 -> N1 is N-1, gen_vars(N1,T),Vars=[_X|T]
615 ; N =:= 0 -> Vars = []).
616
617 :- assert_must_succeed(string_term_with_args('Fun(1,2,-)')).
618 :- assert_must_fail(string_term_with_args('Fun(1,2,3)')).
619 :- assert_must_fail(string_term_with_args('Fun(X,_,_Y)')).
620 :- assert_must_fail(string_term_with_args(_Fun)).
621
622 string_term_with_args(StrTerm) :-
623 atom(StrTerm),!,
624 split_atom(StrTerm,['(',',',')'],[_Fun|A]),
625 A\=[],member(-,A).
626
627 :- assert_must_succeed((haskell_csp:concatenate_string_list(['A','B','C'],'ABC'))).
628 :- assert_must_succeed((haskell_csp:concatenate_string_list([],''))).
629
630 concatenate_string_list(L,Res) :-
631 concatenate_string_list(L,'',Res).
632
633 concatenate_string_list([],Res,Res).
634 concatenate_string_list([H|T],Str,Res) :-
635 string_concatenate(Str,H,StrRes),
636 concatenate_string_list(T,StrRes,Res).
637
638 translate_csp_assertions(L,Res) :-
639 maplist(translate_csp_assertion_with_sep,L,LRes),
640 concatenate_string_list(LRes,Res).
641
642 translate_csp_assertion_with_sep(Ass,AssStrWithSep) :-
643 translate_with_sep(translate_csp_assertion,Ass,'$',AssStrWithSep).
644
645 % Sep must be an atom
646 translate_with_sep(TranslationPredicate,Arg,Sep,ArgStrSep) :-
647 functor(Fun,TranslationPredicate,2),arg(1,Fun,Arg),arg(2,Fun,ArgStr),
648 %Fun =.. [TranslationPredicate,Arg,ArgStr],
649 call(Fun),
650 string_concatenate(ArgStr,Sep,ArgStrSep).
651
652 translate_csp_assertion(AssertionExpr,ConcRes) :-
653 /* assert not? P [Op= Q */
654 (AssertionExpr = assertRef(N,P,Op,Q,_) ->
655 refinement_operator(Op,Operator),
656 translate_cspm_state(Q,Proc_2),
657 L=[Operator,Proc_2]
658 /* assert P |= LTL: "ltl-formula" */
659 ;AssertionExpr = assertLtl(N,P,Formula,_) ->
660 L = [' |= ', 'LTL: ', '\"', Formula, '\"']
661 /* assert P |= CTL: "ctl-formula" */
662 ;AssertionExpr = assertCtl(N,P,Formula,_) ->
663 L = [' |= ', 'CTL: ', '\"', Formula, '\"']
664 /* assert not? P :[Mod [E]] */
665 ;AssertionExpr = assertModelCheckExt(N,P,Mod,E) ->
666 fdr_model(Mod,Model),
667 fdr_ext(E,Ext),
668 L=[Model,Ext]
669 /* assert not? P :[Mod] */
670 ;AssertionExpr = assertModelCheck(N,P,Mod) ->
671 fdr_single_model(Mod,Model),
672 L=[Model]
673 ;
674 add_internal_error('Internal Error (CSP-M Parser): Unexpected assertion predicate: ',
675 translate_csp_assertion(AssertionExpr,ConcRes))
676 ),
677 adding_not(N,Not),
678 translate_cspm_state(P,Proc),
679 concatenate_string_list([Not, Proc|L], ConcRes).
680
681 %%%%%%%%%%%%%%%%%%%%%%%%%%% Testing get_csp_processes/1, get_csp_process/2 and translate_csp_assertions/2 predicates %%%%%%%%%%%%%%%%%%%%%%%%%%%%
682 find_and_assert_all_csp_processes_from_arity_zero :-
683 findall(P,(bindval(P,Body,_),definite_cspm_process_expression(Body),assertz(is_csp_process(P))),_L).
684
685 clear_all_is_csp_process_facts :- retractall(is_csp_process(_)).
686
687 :- assert_must_succeed((find_and_assert_all_csp_processes_from_arity_zero,
688 get_csp_processes(Res), %print(Res),nl,
689 clear_all_is_csp_process_facts,
690 Res==list(['P(-)','Q(-)','SEND','REC','SYSTEM','GEN1','GEN2','MAIN']))).
691 :- assert_must_succeed((findall(assertRef(A,B,C,D,S),
692 haskell_csp: assertRef(A,B,C,D,S),L),haskell_csp: translate_csp_assertions(L,String),
693 String == 'CSP: MAIN [T= CSP: PROB_TEST_TRACE$not CSP: PROB_TEST_TRACE [T= CSP: MAIN$')).
694 :- assert_must_succeed((findall(assertModelCheckExt(A,B,C,D),
695 haskell_csp: assertModelCheckExt(A,B,C,D),L),
696 findall(assertModelCheck(A,B,C),haskell_csp:assertModelCheck(A,B,C),L1,L),
697 haskell_csp: translate_csp_assertions(L1,String),
698 String == 'CSP: a.1->P :[ livelock free ]$CSP: SYSTEM [|{|left,right|}|] GEN1 :[ deterministic [F] ]$not CSP: SYSTEM [|{|left,right|}|] GEN1 :[ deadlock free [FD] ]$')).
699
700 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
701
702 /* Tcl_Tk cannot handle complicated prolog strings, that's why we have to convert the from the Csp prolog file filtered assertions
703 into simple string. Assertions will be separated with the '$' symbol. */
704 get_csp_assertions_as_string(CSPFile,R) :-
705 read_compiled_prolog_file(CSPFile,A,filter_assertion_declarations),
706 translate_csp_assertions(A,R),debug_print(9,'string_for_tcl: '),debug_println(9,R).
707
708 /* The same as above for the processes, these will be separate by '$' as well. Needed for the process comboboxes in the
709 'Check Csp Assertions' window in Tcl_Tk. */
710 get_csp_processes(list(R1)) :-
711 debug_nl(9), debug_println(9,getting_csp_processes),
712 findall(bindval(P,_,_),bindval(P,_,_),L),
713 findall(agent(F,Body,_),agent(F,Body,_),L1,L),
714 get_processes(L1,R1),
715 debug_println(9,R1), debug_nl(9).
716
717 get_processes([],[]).
718 get_processes([bindval(A,_,_)|T],R) :- !,
719 ? ( animatable_process(A) -> R=[A|Res] ; R=Res),
720 get_processes(T,Res).
721 get_processes([agent(Fun,Body,_)|T],R) :- !,
722 ? ( (definite_cspm_process_expression(Body),animatable_process_with_arguments(Fun,proc(F,N)))
723 -> proc_with_arguments_to_string(F,N,FunRes),R = [FunRes|Res]
724 ; R=Res
725 ),
726 get_processes(T,Res).
727
728 /* ------------------------------------------------------------------------------------------------------------------------- */
729
730 clear_cspm_spec :- % nl,print('RESET CSPM'),nl,nl,
731 retractall(parseResult(_,_,_,_,_)),
732 retractall(channel(_,_)),
733 retractall(bindval(_,_,_)),
734 retractall(cspTransparent(_)),
735 retractall(agent(_,_,_)),
736 retractall(dataTypeDef(_,_)),
737 retractall(subTypeDef(_,_)),
738 retractall(nameType(_,_)),
739 retractall(assertRef(_,_,_,_,_)),
740 % retractall(assertTauTrio(_,_,_,_,_,_)),
741 retractall(assertModelCheckExt(_,_,_,_)),
742 retractall(assertModelCheck(_,_,_)),
743 retractall(channel_type_list(_,_)),
744 retractall(csp_full_type_constructor(_,_,_)),
745 retractall(pragma(_)),
746 retractall(enum_warning_occured(_,_,_)).
747 %retractall(csp_full_expanded_type(_,_)),
748 %retractall(expanded_setFromTo(_,_,_)).
749
750 %:- use_module(probsrc(eventhandling),[register_event_listener/3]).
751 :- register_event_listener(clear_specification,clear_cspm_spec,
752 'Clearing any CSPM Specification.').
753
754 is_a_datatype(DT,L) :-
755 ? (dataTypeDef(DT,L) ; subTypeDef(DT,L)).
756
757 /* Tests for the is_not_infinite_type/1 predicate (see .pl translation sample on lines 68-106 ) */
758
759 :- assert_must_fail((assertz(csp_full_type_constructor(_,'SubMsg',[dataType('Msg')])),
760 assertz(csp_full_type_constructor(_,'Msg',[dataType('SubMsg')])),
761 haskell_csp:is_not_infinite_type(closure([tuple([receive])])))).
762 :- assert_must_succeed((assertz(csp_full_type_constructor(_,'FRUIT',
763 [constructor(apples),construcor(oranges),constructor(pears)])),
764 haskell_csp:is_not_infinite_type(closure([tuple([left])])))).
765 :- assert_must_fail((assertz(csp_full_type_constructor(_,'FRUIT',
766 [constructor(apples),construcor(oranges),constructor(pears)])),
767 assertz(csp_full_type_constructor(_,'SubMsg',[dataType('Msg')])),
768 assertz(csp_full_type_constructor(_,'Msg',[dataType('SubMsg')])),
769 haskell_csp:is_not_infinite_type(closure([tuple([left]),
770 tuple([mid]),tuple([right]),tuple([receive])])))).
771 :- assert_must_fail((assertz(csp_full_type_constructor(ste,'Inf',['Seq'(dataType('FRUIT'))])),
772 assertz(csp_full_type_constructor(_,'FRUIT',
773 [constructor(apples),construcor(oranges),constructor(pears)])),
774 haskell_csp:is_not_infinite_type(closure([tuple([infinite])])))).
775 :- assert_must_succeed((assertz(csp_full_type_constructor(_,'FRUIT',
776 [constructor(apples),construcor(oranges),constructor(pears)])),
777 haskell_csp:is_not_infinite_type(closure([tuple([left]),tuple([mid]),tuple([right])])))).
778 :- assert_must_fail((assertz(csp_full_type_constructor(_,'FRUIT',
779 [constructor(apples),construcor(oranges),constructor(pears)])),
780 assertz(csp_full_type_constructor(_,'SubMsg',[dataType('Msg')])),
781 assertz(csp_full_type_constructor(_,'Msg',[dataType('SubMsg')])),
782 assertz(csp_full_type_constructor(ste,'Inf',['Seq'(dataType('FRUIT'))])),
783 haskell_csp:is_not_infinite_type(closure([tuple([left]),tuple([mid]),
784 tuple([right]),tuple([infinite]),tuple([receive])])))).
785
786 :- assert_must_fail(haskell_csp:is_not_infinite_type(setFrom(1))).
787 :- assert_must_fail(haskell_csp:channel_type_is_finite('dotTupleType'([setValue([int(1),int(2)]), setFrom(1)]),2)).
788 :- assert_must_succeed((assertz(name_type('S', setFromTo(1,3))), haskell_csp: channel_type_is_finite('S',2))).
789
790 /* is_not_infinite_type/1 */
791 /* check if the Event set is from infinite type */
792 /* needed for the refinement checker, when generating counter-examples, TODO: re-implement predicate */
793 is_not_infinite_type(X) :- var(X),!,fail.
794 % at first we are only interesting of checking the whole closure for infinite types
795 is_not_infinite_type(closure(X)) :- !,
796 closure_is_finite_set(X).
797 %% TODO: Cover all other cases for this predicate (like setValue, setFrom, ...)
798
799
800 closure_is_finite_set(L) :-
801 maplist(single_element_closure_is_finite,L).
802
803 % the closure is basically the set of all channels in a specification
804 single_element_closure_is_finite(tuple([Ch|_List])) :-
805 (channel_type_list(Ch,ChannelTypeList) -> true
806 ; print(no_channel_type(Ch))),
807 !,
808 l_channel_type_is_finite(ChannelTypeList,2).
809 single_element_closure_is_finite(_X).
810
811 channel_type_is_finite(intType,_Rec) :- !,fail.
812 channel_type_is_finite(boolType,_Rec) :- !.
813 channel_type_is_finite(setFromTo(_L,_U),_Rec) :- !.
814 channel_type_is_finite(setFrom(_L),_Rec) :- !,fail. % endless set
815 % we got a dot tuple of types, we need to check for infinity all types in the tuple.
816 channel_type_is_finite('dotTupleType'(List),Rec):-!,
817 l_channel_type_is_finite(List,Rec).
818 channel_type_is_finite('typeTuple'(List),Rec) :- !,
819 l_channel_type_is_finite(List,Rec). % the same as last clausel
820 channel_type_is_finite(setValue(_L),_Rec) :- !.
821 channel_type_is_finite(dataType(DT),Rec) :-
822 ? is_a_datatype(DT,_),!,
823 check_datatype_el(DT,Rec).
824 channel_type_is_finite('Seq'(setValue([])),_Rec) :- !. % Seq({}) is the empty sequence <>
825 channel_type_is_finite('Seq'(_Type),_Rec) :- !, fail. % e.g. Seq({a,b,c}) indicator for endless datatype (there are endless numbers of sequences)
826 channel_type_is_finite(X,Rec) :-
827 name_type(X,Type),!,
828 channel_type_is_finite(Type,Rec).
829 channel_type_is_finite(_X,_Rec).
830
831 check_datatype_el(DT,MaxRec) :-
832 (MaxRec > 0 -> M1 is MaxRec -1,
833 ? (csp_constructor(_Cons,DT,ArgSubTypes) -> /* Subtypes recursion. */ l_channel_type_is_finite(ArgSubTypes,M1)
834 ; /* constructors from finite type (there is no recursion)*/ true)).
835 /* ending recursion of datatypes (recursion doesn't mean infinite type) */
836
837 channel_type_is_finite_rec(Rec,HType) :-
838 channel_type_is_finite(HType,Rec).
839
840 l_channel_type_is_finite(L,Rec) :-
841 maplist(channel_type_is_finite_rec(Rec),L).
842
843 /*
844 l_channel_type_is_finite([],_Rec).
845 l_channel_type_is_finite([HType|T],Rec) :-
846 (channel_type_is_finite(HType,Rec) ->
847 l_channel_type_is_finite(T,Rec)).
848 */
849
850 /* end of the implementation of is_not_infinite_type/1 predicate */
851
852 get_csp_assertions(CSP_Assertions) :-
853 findall(Ass, (is_assertion(Ass),Ass), CSP_Assertions),
854 debug_println(9,CSP_Assertions).
855
856 /*
857 get_csp_assertions_enum(CSPFile, Result) :-
858 read_compiled_prolog_file(CSPFile,CSP_Assertions,filter_assertion_declarations),
859 enumerate_assertions(CSP_Assertions,Result).
860
861 :- assert_must_succeed(haskell_csp:enumerate_assertions([a,b,c,d,e,f],[(a,0),(b,1),(c,2),(d,3),(e,4),(f,5)])).
862 :- assert_must_succeed(haskell_csp:enumerate_assertions([],[])).
863 enumerate_assertions(L,R) :- enumerate_assertions_acc(L,R,0).
864 enumerate_assertions_acc([],[],_).
865 enumerate_assertions_acc([H|T],[(H,Acc)|R],Acc) :- New_Acc is Acc +1, enumerate_assertions_acc(T,R,New_Acc).
866 */
867
868 cia_consult_without_redefine_warning(File) :-
869 (file_exists(File) -> true ; (add_error(haskell_csp,'CSP-M PL File does not exist: ',File),fail)),
870 debug_println(15,consult_without_redefine(File)),
871 get_set_optional_prolog_flag(redefine_warnings, Old, off),
872 get_set_optional_prolog_flag(single_var_warnings, Old2, off),
873 get_set_optional_prolog_flag(discontiguous_warnings, Old3, off),
874 (load_files(File,[compilation_mode(assert_all)]) %consult(File)
875 -> OK=true ; OK=false),
876 get_set_optional_prolog_flag(redefine_warnings, _, Old),
877 get_set_optional_prolog_flag(single_var_warnings, _, Old2),
878 get_set_optional_prolog_flag(discontiguous_warnings, _, Old3),
879 OK=true.
880
881 /* ------------------------------------- */
882
883
884 /* THE CSP OPERATIONAL SEMANTICS */
885
886
887 /* ------------------------------------- */
888 %
889 %trans_pre_compute(X,Results) :-
890 % findall(res(X,A,X1,Residue),call_residue(cspm_trans(X,A,X1),Residue), Results).
891 %
892 %
893 %trans_cont(Results,X,A,X1) :-
894 % member(res(X,A,X1,Residue),Results),
895 % % print(trans_cont(X,A,X1,Residue)),nl,
896 % call(Residue).
897
898 /* ------------------------------------- */
899
900 %cspm_trans(E,_,_) :- print(cspm_trans(E)),nl,fail.
901
902 :- assert_must_succeed(( haskell_csp:functor_dif(X,f), X=g(_) )).
903 :- assert_must_fail(( haskell_csp:functor_dif(X,f), X=f(_) )).
904
905 :- block functor_dif(-,?).
906 functor_dif(X,FY) :- functor(X,FX,_), FX\=FY.
907
908 :- assert_pre(haskell_csp:cspm_trans(E,_,_,_), nonvar(E)).
909 :- assert_post(haskell_csp:cspm_trans(_,A,NE,_), (nonvar(A),nonvar(NE))).
910 :- block cspm_trans(-,?,?,?).
911 % TO DO: comment out for efficiency:
912 /* ------ */
913 %cspm_trans(X,_,_) :- debug_println(9,cspm_trans(X)), var(X),
914 % add_error(csp_interpreter,'### Variable process expression in cspm_trans !!',X), fail.
915 cspm_trans(X,_,_,_) :- undefined_process_construct(X),
916 (get_preference(cspm_animate_all_processes,true),string_term_with_args(X) ->
917 add_message(cspm_trans,'Warning: Tried to expand a process with non-ground arguments: ',X),fail
918 ; add_error_fail(csp_interpreter,'### Undefined Construct in cspm_trans !! ',X)
919 ).
920 /* ------ */
921
922 cspm_trans(stop(_),_,_,_) :- fail.
923 cspm_trans(omega,_,_,_) :- fail.
924
925 cspm_trans(skip(SrcSpan),tick(SrcSpan),omega,_).
926 %cspm_trans(skip(SrcSpan),tick(SrcSpan),stop(SrcSpan),_).
927
928 %cspm_trans(cspPrint(X),io(V1,print,no_loc_info_available),cspPrint(X)) :- evaluate_argument(X,V1).
929
930 cspm_trans('CHAOS'(SrcSpan,_Set),tau(chaos_stop(SrcSpan)),stop(SrcSpan),_).
931 cspm_trans('CHAOS'(SrcSpan,Set),io(V1,Ch,SrcSpan),'CHAOS'(SrcSpan,Set),_WF) :- /* or should we add an intermediate tau ?? */
932 % print(evaluate_argument(Set,S)),nl,
933 evaluate_argument(Set,S),
934 % print(chaos(S)),nl,
935 expand_channel_pattern_expression(S,ECList,SrcSpan),
936 % print(setup_channel_skeleton(io(V1,Ch,SrcSpan))),nl,
937 setup_channel_skeleton(io(V1,Ch,SrcSpan)),
938 % print(chaos(io(V1,Ch),ECList)),nl,
939 hidden(io(V1,Ch,SrcSpan),ECList).
940
941 % print(hidden(io(V1,Ch,SrcSpan),ECList)),nl.
942
943 /* external choice */
944 cspm_trans('[]'(X,Y,Span),NA,Res,WF) :- cspm_trans(X,A,X1,WF),
945 shift_span_for_left_branch(Span,LSpan),
946 merge_span_into_event(A,LSpan,NA),
947 ( top_level_dif(A,tau(_)), Res=X1
948 ;
949 A=tau(_), tl_normalise('[]'(X1,Y,Span),Res) ).
950 cspm_trans('[]'(X,Y,Span),NA,Res,WF) :- cspm_trans(Y,A,Y1,WF),
951 shift_span_for_right_branch(Span,RSpan),
952 merge_span_into_event(A,RSpan,NA),
953 ( top_level_dif(A,tau(_)), Res=Y1
954 ;
955 A=tau(_), tl_normalise('[]'(X,Y1,Span),Res) ).
956
957 /* internal choice */
958 cspm_trans('|~|'(X,_Y,SrcSpan),tau(int_choice_left(SrcSpan,LSpan)),X,_WF) :-
959 shift_span_for_left_branch(SrcSpan,LSpan).
960 cspm_trans('|~|'(_X,Y,SrcSpan),tau(int_choice_right(SrcSpan,RSpan)),Y,_WF) :-
961 shift_span_for_right_branch(SrcSpan,RSpan).
962
963 /* -> PREFIX */
964 /* Note: set restrictions on values are encoded as inGuard Expressions */
965 cspm_trans(prefix(SPAN1,Values,ChannelExpr,CSP,SPAN2), io(EV,Channel,SPAN), NormCSP,WF) :-
966 evaluate_channel_outputs(Values,ChannelExpr,EV,Channel,SPAN,WF),
967 unify_spans(SPAN1,SPAN2,SPAN),
968 full_normalise_csp_process(CSP,NormCSP). % ,print(prefix(io(EV,Channel))),nl.
969
970
971 /* interleave */
972 %cspm_trans('|||'(X,Y,Span),A,R,WF) :- cspm_trans(sharing(setValue([]),X,Y),A,R).
973 /* Firing rules for the |||-operator:
974
975 P -a> P'
976 ----------------------------
977 P ||| Q -a> P' ||| Q
978
979 Q -a> Q'
980 ----------------------------
981 P ||| Q -a> P ||| Q'
982
983
984 P -tick> P'
985 ----------------------------
986 P ||| Q -tau> Omega ||| Q
987
988
989 Q -tick> Q'
990 ----------------------------
991 P ||| Q -tau> P ||| Omega
992
993 */
994
995 cspm_trans('|||'(omega,omega,Span),tick(Span),omega,_).
996 cspm_trans('|||'(X,Y,ISpan),A,Res,WF) :-
997 cspm_trans(X, ActionX, X1,WF),
998 shift_span_for_left_branch(ISpan,LSpan),
999 ( ActionX=tick(_), X2=omega
1000 ; functor_dif(ActionX,tick), X2=X1
1001 ),
1002 merge_span_into_event(ActionX,LSpan,MA),
1003 (ActionX=tick(_) -> A=tau(MA); A=MA),
1004 tl_normalise('|||'(X2,Y,ISpan),Res).
1005 cspm_trans('|||'(X,Y,ISpan),A,Res,WF) :-
1006 cspm_trans(Y, ActionY, Y1,WF),
1007 shift_span_for_right_branch(ISpan,RSpan),
1008 ( ActionY=tick(_), Y2=omega
1009 ; functor_dif(ActionY,tick), Y2=Y1
1010 ),
1011 merge_span_into_event(ActionY,RSpan,MA),
1012 (ActionY=tick(_) -> A=tau(MA); A=MA),
1013 tl_normalise('|||'(X,Y2,ISpan),Res).
1014
1015 /* sequential composition */
1016 cspm_trans(';'(P,Q,SeqSpan),AX,Res,WF) :-
1017 cspm_trans(P,A,P1,WF),
1018 ( A=tick(_),
1019 merge_span_into_event(A,SeqSpan,MA),
1020 AX = tau(MA),
1021 full_normalise_csp_process(Q,Res) /* is this required ?? */
1022 ; functor_dif(A,tick), AX=A,
1023 tl_normalise(';'(P1,Q,SeqSpan),Res)
1024 ).
1025
1026
1027 /* Sharing: [| a |] */
1028 cspm_trans(sharing(CList,X,Y,SrcSpan),A,Res,WF) :-
1029 evaluate_argument(CList,EvCList),
1030 expand_channel_pattern_expression(EvCList,ECList,SrcSpan),
1031 cspm_trans(esharing(ECList,X,Y,SrcSpan),A,Res,WF).
1032 cspm_trans(esharing(_,omega,omega,SrcSpan), tick(SrcSpan), omega ,_WF).
1033 cspm_trans(esharing(CList,X,Y,SrcSpan), Action, Result,WF) :-
1034 cspm_trans(X, ActionX, X1,WF),
1035 ( (ActionX=tick(TS),
1036 shift_span_for_left_branch(SrcSpan,LSpan),
1037 merge_span_into_event(tau(tick(TS)),LSpan,Action),
1038 Result = esharing(CList,omega,Y,SrcSpan))
1039 ; (functor_dif(ActionX,tick),
1040 shift_span_for_left_branch(SrcSpan,LSpan),
1041 merge_span_into_event(ActionX,LSpan,Action),
1042 not_hidden(ActionX,CList), /* covers tau */
1043 Result = esharing(CList,X1,Y,SrcSpan))
1044 ; (ActionX=io(V1,Ch,Sp1), Action = io(V,Ch,Span),
1045 %((transferReq,[int(3),ac1,ac2,true])=(Ch,V1) -> trace ; true),
1046 Result = esharing(CList,X1,Y1,SrcSpan),
1047 unify_spans(Sp1,SrcSpan,SP1b),
1048 hidden(Action,CList),
1049 unify_values(V1,V2,V,Ch,SP1b), % try and also incorporate Sp2 Span, without compromising speed
1050 % print(call_cspm_transY_B1(Y,io(V2,Ch),Y1)),nl,
1051 cspm_trans(Y, io(V2,Ch,Sp2), Y1,WF), /* <---- Y will be recomputed for every solution of X !!! */
1052 unify_spans(SP1b,Sp2,Span3),
1053 Span = span_info(sharing,Span3)
1054 )
1055 ).
1056 cspm_trans(esharing(CList,X,Y,SrcSpan), Action2, Result,WF) :-
1057 shift_span_for_right_branch(SrcSpan,RSpan),
1058 % print(esharing_call_cspm_transY_B2(Y,ActionY,Y1)),nl,
1059 cspm_trans(Y,ActionY,Y1,WF), /* this gets computed a second time; is there a way to avoid this? */
1060 %print(esharing_cspm_transY_B2(Y,ActionY)),nl,
1061 ( ActionY = tick(TS), Action=tau(tick(TS)), Result=esharing(CList,X,omega,SrcSpan)
1062 ; functor_dif(ActionY,tick), ActionY = Action,
1063 %print(try_non_sharing(ActionY)),nl,
1064 not_hidden(ActionY,CList), /* covers tau */
1065 Result = esharing(CList,X,Y1,SrcSpan)
1066 ),
1067 merge_span_into_event(Action,RSpan,Action2).
1068
1069
1070 /* Linked Parallel [ l <-> r,.. ] */
1071 cspm_trans(lParallel(LinkList,X,Y,Span), Action,Result,WF) :-
1072 evaluate_link_list(LinkList,EvLinkRenameList),
1073 %print(evlinklist(LinkList,EvLinkRenameList)),nl, %
1074 cspm_trans(elinkParallel(EvLinkRenameList,X,Y,Span),Action,Result,WF).
1075 cspm_trans(elinkParallel(_,omega,omega,Span), tick(Span), omega ,_WF).
1076 cspm_trans(elinkParallel(EvLinkRenameList,X,Y,LinkSpan),Action,Result,WF) :-
1077 cspm_trans(X,AX,X2,WF), % print(elink_x(X,AX,X2,EvLinkRenameList)),nl, print('State: '),print(X),nl,
1078 ( AX = tick(TS),
1079 shift_span_for_left_branch(LinkSpan,LSpan),
1080 merge_span_into_event(tau(tick(TS)),LSpan,Action),
1081 Result=elinkParallel(EvLinkRenameList,omega,Y,LinkSpan)
1082 ;
1083 functor_dif(AX,tick),
1084 ( shift_span_for_left_branch(LinkSpan,LSpan),
1085 merge_span_into_event(AX,LSpan,Action),
1086 Result = elinkParallel(EvLinkRenameList,X2,Y,LinkSpan),
1087 not_renamed(AX,EvLinkRenameList)
1088 % ,print(not_renamed(AX,EvLinkRenameList)),nl %%
1089 ;
1090 Action=tau(link(AX,io(V,Ch,Span))),
1091 Result = elinkParallel(EvLinkRenameList,X2,Y2,LinkSpan),
1092 force_rename_action(AX,EvLinkRenameList,io(V1,Ch,Sp0)),
1093 unify_spans(LinkSpan,Sp0,Sp1),
1094 %% print(renamed(AX,io(V1,Ch),EvLinkRenameList)),nl, %%
1095 unify_values(V1,V2,V,Ch,Sp1), % try and also incorporate Sp2 Span, without compromising speed
1096 % MAYBE TO DO ?: instantiate V2 as much as possible ! --> in()/dot issues
1097 %% print(cspm_trans(Y,io(V2,Ch,Sp2),Y2)),nl, %%
1098 cspm_trans(Y,io(V2,Ch,Sp2),Y2,WF), /* <---- Y will be recomputed for every solution of X !!! */
1099 unify_spans(Sp1,Sp2,Span3),
1100 %% print(unify(Sp1,Sp2,Span3)),nl, %%
1101 Span = span_info(sharing,Span3)
1102 )
1103 ).
1104 cspm_trans(elinkParallel(EvLinkRenameList,X,Y,LinkSpan),Action2,
1105 elinkParallel(EvLinkRenameList,X,YR,LinkSpan),WF) :-
1106 shift_span_for_right_branch(LinkSpan,RSpan),
1107 rev_rename_list(EvLinkRenameList,RevList),
1108 cspm_trans(Y,ActionY,Y2,WF), /* TO DO: try and avoid recomputation of cspm_trans(Y) ?! */
1109 ( ActionY=tick(TS), Action=tau(tick(TS)), YR=omega
1110 ;
1111 functor_dif(ActionY,tick),ActionY=Action,YR=Y2,not_renamed(Action,RevList)
1112 ),
1113 merge_span_into_event(Action,RSpan,Action2).
1114
1115 cspm_trans(aParallel(CListX,X,CListY,Y,SrcSpan),A,NewState,WF) :- %print(expanding_aparx),nl,
1116 evaluate_argument(CListX,EvCListX),
1117 expand_channel_pattern_expression(EvCListX,ECListX,SrcSpan), %print(expanding_apary),nl,
1118 evaluate_argument(CListY,EvCListY),
1119 expand_channel_pattern_expression(EvCListY,ECListY,SrcSpan),
1120 Expanded = eaParallel(ECListX,X,ECListY,Y,SrcSpan),
1121 %we have expanded the channel synchronisation sets; avoid recomputing them every time
1122 % TO DO: investigate whether it also makes sense to precompute intersection
1123 cspm_trans(Expanded,A,NewState,WF).
1124 cspm_trans(eaParallel(_,omega,_,omega,SrcSpan), tick(SrcSpan), omega ,_WF).
1125 cspm_trans(eaParallel(ECListX,X,ECListY,Y,SrcSpan),A,eaParallel(ECListX,X2,ECListY,Y1,SrcSpan),WF) :-
1126 %trans_pre_compute(Y,Results),
1127 cspm_trans(X, AX, X1,WF),
1128 % print(apar_x(AX, from(X))),nl,
1129 ( X2=X1,Y1=Y,
1130 hidden_or_tau(AX,ECListX),
1131 not_hidden(AX,ECListY),
1132 shift_span_for_left_branch(SrcSpan,LSpan),
1133 merge_span_into_event(AX,LSpan,A)
1134 ;
1135 AX=tick(_TS), X2=omega,Y1=Y,
1136 shift_span_for_left_branch(SrcSpan,LSpan),
1137 merge_span_into_event(tau(AX),LSpan,A)
1138 ;
1139 AX=io(V1,Ch,Sp1), X2=X1, A = io(V,Ch,Span),
1140 % nl,print(try_apar_sync(V1,Ch)),nl,
1141 hidden(io(V1,Ch,Sp1),ECListX), % print(left_ok),nl, % do V1 instead of V ?
1142 hidden(io(V,Ch,Span),ECListY), % print(right_ok),nl, % V2 instead of V
1143 % Synchronisation possible
1144 unify_spans(Sp1,SrcSpan,SP1b),
1145 unify_values(V1,V2,V,Ch,SP1b), % try and also incorporate Sp2 Span, without compromising speed
1146 %print(trying(aparY(io(V2,Ch,Sp2)))),nl, %
1147 cspm_trans(Y, io(V2,Ch,Sp2), Y1,WF), /* <---- Y will be recomputed for every solution of X !!! */
1148 % trans_cont(Results,Y, io(V2,Ch,Sp2), Y1),
1149 % print(done(aparY(io(V2,Ch,Sp2)))),nl, %
1150 unify_spans(SP1b,Sp2,Span3),
1151 Span = span_info(sharing,Span3)
1152 ).
1153 cspm_trans(eaParallel(ECListX,X,ECListY,Y,SrcSpan),AS,eaParallel(ECListX,X,ECListY,Y2,SrcSpan),WF) :-
1154 cspm_trans(Y, AY, Y1,WF), /* To do: try and avoid recomputation of cspm_trans(Y) ?! */
1155 ( AY=A, Y2=Y1,
1156 hidden_or_tau(A,ECListY), not_hidden(A,ECListX)
1157 ;
1158 AY=tick(_TS), A = tau(AY), Y2=omega
1159 ),
1160 shift_span_for_right_branch(SrcSpan,RSpan),
1161 merge_span_into_event(A,RSpan,AS).
1162
1163 /* only used for outside xtl_interface ; not used internally anymore */
1164 cspm_trans(val_of(X,Span),A,NewExpr,WF) :- (symbol(RenamedX,X,_,_) -> cspm_trans(agent_call(Span,RenamedX,[]),A,NewExpr,WF);
1165 cspm_trans(X,A,NewExpr,WF)).
1166 cspm_trans(agent_call(Span,F,Par),NA,NNewExpr,WF) :-
1167 unfold_function_call_once(F,Par,Value,Span),
1168 cspm_trans(Value,A,NewExpr,WF),
1169 full_normalise_csp_process(NewExpr,NNewExpr),
1170 % print(merge_agcall(A,Span)),nl,
1171 merge_span_into_event(A,Span,NA).
1172
1173 % Par = [[x],[y]]
1174 cspm_trans(agent_call_curry(F,Par),NA,NNewExpr,WF) :-
1175 Span=no_loc_info_available,
1176 unfold_function_call_curry_once(F,Par,Value,Span),
1177 cspm_trans(Value,A,NewExpr,WF),
1178 full_normalise_csp_process(NewExpr,NNewExpr),
1179 % print(merge_agcall(A,Span)),nl,
1180 merge_span_into_event(A,Span,NA).
1181
1182 cspm_trans(builtin_call(X),Action,NewExpr,WF) :- % builtin_call is normally removed by precompilation; but can remain, e.g., for assertions
1183 cspm_trans(X,Action,NewExpr,WF).
1184 cspm_trans(head(X),Action,NewExpr,WF) :- force_evaluate_argument(X,EX),head_list(EX,Result),
1185 cspm_trans(Result,Action,NewExpr,WF).
1186
1187 /* hiding '\\' */
1188
1189 cspm_trans('\\'(Expr,CList,Span), A, Res ,WF) :-
1190 evaluate_argument(CList,EvCList),
1191 expand_channel_pattern_expression(EvCList,ECList,no_loc_info_available),
1192 % print(ehide(Expr,ECList,Span)),nl,
1193 cspm_trans(ehide(Expr,ECList,Span),A,Res,WF).
1194
1195 cspm_trans(ehide(Expr,CList,Span), A, Res ,WF) :-
1196 % (nonvar(A) -> ((A=io(_,_,_);A=tick(_)) -> ActionX=A ; A=tau(hide(ActionX)))
1197 % ; true),
1198 cspm_trans(Expr,ActionX,X,WF),
1199 cspm_hide_action(ActionX,X, CList,Span, A,Res).
1200
1201
1202 cspm_trans(exception(CList,X,Y,Span), A, Res ,WF) :-
1203 evaluate_argument(CList,EvCList),
1204 expand_channel_pattern_expression(EvCList,ECList,no_loc_info_available),
1205 %print(exception(ECList,X,Y)),nl,
1206 cspm_trans(eexception(ECList,X,Y,Span),A,Res,WF).
1207
1208 cspm_trans(eexception(CList,X,Y,Span),A,Res,WF) :- % expanded version of exception
1209 cspm_trans(X, ActionX, X1,WF),
1210 ( functor_dif(ActionX,tick), ActionX=A,
1211 Res = eexception(CList,X1,Y,Span),
1212 not_hidden(A,CList)
1213 ; merge_span_into_event(ActionX,Span,A),
1214 Res = Y,
1215 hidden(ActionX,CList)
1216 ; A=tick(TS), ActionX=tick(TS), Res=omega % is this correct ??
1217 ).
1218
1219
1220 /* timeout */
1221 cspm_trans('[>'(P,Q,SrcSpan),AS,Res,WF) :- cspm_trans(P,A,P1,WF),
1222 ( A=tau(_), Res='[>'(P1,Q,SrcSpan)
1223 ;
1224 top_level_dif(A,tau(_)), % a transition which can be removed by the tau below
1225 Res=P1 ),
1226 shift_span_for_left_branch(SrcSpan,LSpan),
1227 merge_span_into_event(A,LSpan,AS).
1228 cspm_trans('[>'(_P,Q,SrcSpan),tau(timeout(SrcSpan)),Q,_WF).
1229
1230
1231 /* interrupt */
1232
1233 cspm_trans('/\\'(X,Y,Span),NA,Res,WF) :-
1234 cspm_trans(X,A,X1,WF), %%print(interrupt_left(X,A,X1)),nl,
1235 shift_span_for_left_branch(Span,LSpan),
1236 merge_span_into_event(A,LSpan,NA),
1237 ( A=tick(_), Res=X1
1238 ; functor_dif(A,tick), tl_normalise('/\\'(X1,Y,Span),Res)
1239 ).
1240 cspm_trans('/\\'(X,Y,Span),NA,Res,WF) :-
1241 cspm_trans(Y,A,Y1,WF),
1242 shift_span_for_right_branch(Span,RSpan),
1243 merge_span_into_event(A,RSpan,NA),
1244 ( top_level_dif(A,tau(_)), Res=Y1
1245 ; A=tau(_), tl_normalise('/\\'(X,Y1,Span),Res)
1246 ).
1247
1248 /* renaming [[ old <- new,... | Generators ]] */
1249 cspm_trans(procRenamingComp(X,GeneratorList,RenameList),RA,Res,WF) :-
1250 % print(procCompRenaming(GeneratorList)),nl, %%
1251 % warning: does not have the rangeEnum wrapper expected
1252 expand_set_comprehension(rangeEnum(RenameList),GeneratorList,setValue(ExpandedRenames)),
1253 %print(exp(ExpandedRenames)),nl,
1254 cspm_trans(procRenaming(ExpandedRenames,X,no_loc_info_available),RA,Res,WF).
1255
1256 /* renaming [[ old <- new,... ]] */
1257 cspm_trans(procRenaming(RenameList,X,Span),RA,Res,WF) :- %print(procRename(RenameList)),nl,
1258 evaluate_rename_list(RenameList,ERenameList),
1259 cspm_trans(eprocRenaming(ERenameList,X,Span),RA,Res,WF).
1260 cspm_trans(eprocRenaming(RenameList,X,Span),RAS,Res,WF) :-
1261 %print('RENAME: '), translate:print_cspm_state(X),nl,
1262 cspm_trans(X,A,X2,WF),
1263 tl_normalise(eprocRenaming(RenameList,X2,Span),Res),
1264 %print(try_rename(A,RenameList,RA,Span)),nl, %%
1265 % it's still possible that A is non-ground term, i.e. there are a non-ground variables (c?x?y) in the sub-process,
1266 % which have to be unified before applying renaming on them.
1267 (ground(A) -> true; enumerate_action(A)),
1268 rename_action(A,RenameList,RA),
1269 %%% print(done_rename_action(A,RenameList,RA)),nl,
1270 merge_span_into_event(RA,Span,RAS).
1271 % print(merge_span(RA,Span,RAS)),nl,
1272
1273 /* if then else */
1274 cspm_trans(ifte(Test,Then,Else,S1,S2,S3),A,X1,WF) :-
1275 %nl,print(checking_if_test(Test,Then,Else)),nl,
1276 evaluate_boolean_expression(Test,Res),
1277 % print(if_evaluated_boolean_expression(Test,Res)),nl,nl,
1278 cspm_if_trans(Res,Then,Else,A,X1,S1,S2,S3,WF).
1279
1280 cspm_trans('&'(Test,Then),A,X1,WF) :- S=no_loc_info_available,
1281 cspm_trans(ifte(Test,Then,stop(S),S,S,S),A,X1,WF).
1282
1283
1284 cspm_trans(repChoice(GeneratorList,Body,Span), Action,X1,WF) :-
1285 %% nl,print(repChoice(GeneratorList,Body)),nl,
1286 replicate_expand_set_comprehension([Body],GeneratorList,setValue(Bodies)),
1287 %% print(bodies(Bodies)),nl,
1288 convert_into_choice(Bodies,Span,CHOICE),
1289 %% print(choice(CHOICE)),nl,
1290 cspm_trans(CHOICE,Action,X1,WF).
1291
1292 cspm_trans(repInternalChoice(GeneratorList,Body,Span), tau(rep_int_choice(Span)),Res,_WF) :-
1293 % print(repInternalChoice(GeneratorList,Span)),nl,
1294 replicate_expand_set_comprehension([Body],GeneratorList,Bodies),
1295 % print(bodies(Bodies)),nl,nl,
1296 (is_empty_set(Bodies,true)
1297 -> add_error(cspm_trans,'Empty set for replicated internal choice: ',Bodies,Span),fail
1298 ; is_member_set(Res,Bodies)).
1299
1300 cspm_trans(repInterleave(GeneratorList,Body,Span), A, X,WF) :-
1301 %% tools:print_bt_message(repInterleave(GeneratorList)), %%
1302 % multiplicity is relevant for |||, so add variables to Body below in case Variables are not used
1303 extract_variables_from_generator_list(GeneratorList,Variables),
1304 replicate_expand_set_comprehension([na_tuple([Body|Variables])],GeneratorList,setValue(Bodies)),
1305 convert_into_interleave(Bodies,Span,INTLV),
1306 %% tools:print_bt_message(intlv(INTLV)), %%
1307 cspm_trans(INTLV,A,X,WF). %, tools:print_bt_message(sol(A,X)).
1308
1309
1310 cspm_trans(repSequence(GeneratorList,Body,Span),A,X,WF) :-
1311 % print(repSequence(GeneratorList)),nl, %%
1312 expand_listcomprehension(rangeEnum([Body]),GeneratorList,list(Bodies)),
1313 % print(bodies(Bodies)),nl, %%
1314 convert_into_seqcomp(Bodies,Span,SEQ), %print(sequential(SEQ)),nl,
1315 cspm_trans(SEQ,A,X,WF).
1316
1317
1318 cspm_trans(procRepAParallel(GeneratorList,pair(SyncSet,Body),Span), A, X,WF) :-
1319 % multiplicity is relevant for sharing (it makes a difference if 1 or 2 copies are present), so add variables to Body below in case Variables are not used
1320 extract_variables_from_generator_list(GeneratorList,Variables),
1321 replicate_expand_set_comprehension([list([SyncSet,Body,Variables])],GeneratorList,setValue(Bodies)),
1322 convert_into_eaParallel(Bodies,Span,APAR,_ALPH),
1323 cspm_trans(APAR,A,X,WF).
1324
1325
1326 cspm_trans(procRepLinkParallel(SyncSet,GeneratorList,Body,Span), A, X,WF) :-
1327 expand_listcomprehension(rangeEnum([Body]),GeneratorList,list(Bodies)),
1328 convert_into_linkParallel(Bodies,SyncSet,Span,APAR,Body),
1329 %when((ground(APAR)),
1330 cspm_trans(APAR,A,X,WF).
1331
1332 cspm_trans(procRepSharing(SyncSet,GeneratorList,Body,Span), A, X,WF) :-
1333 % print(procRepSharing(GeneratorList)),nl,
1334 % multiplicity is relevant for sharing, so add variables to Body below in case Variables are not used
1335 extract_variables_from_generator_list(GeneratorList,Variables),
1336 replicate_expand_set_comprehension([na_tuple([Body|Variables])],GeneratorList,setValue(Bodies)),
1337 % print(bodies(Bodies)),nl,
1338 convert_into_Sharing(Bodies,SyncSet,Span,APAR), %print(repshare(APAR)),nl,
1339 cspm_trans(APAR,A,X,WF).
1340
1341 % ----------
1342
1343 cspm_hide_action(ActionX,X, CList,Span, ActionAfterHiding,ResultingCSPExpr) :-
1344 ( functor_dif(ActionX,tick), ActionX=ActionAfterHiding,
1345 tl_normalise(ehide(X,CList,Span),ResultingCSPExpr),
1346 not_hidden(ActionAfterHiding,CList)
1347 ; merge_span_into_event(ActionX,Span,NActionX),
1348 ActionAfterHiding=tau(hide(NActionX)),
1349 tl_normalise(ehide(X,CList,Span),ResultingCSPExpr),
1350 hidden(ActionX,CList)
1351 ; ActionAfterHiding=tick(TS), ActionX=tick(TS), ResultingCSPExpr=omega
1352 ).
1353
1354 :- block cspm_if_trans(-,?,?,?, ?,?,?,?,?).
1355 cspm_if_trans(true,Then,_Else,AS,X1,_S1,S2,_S3,WF) :- !, %print(ifte_true(Then)),nl,
1356 full_normalise_csp_process(Then,NThen),
1357 cspm_trans(NThen,A,X1,WF),
1358 merge_span_into_event(A,S2,AS).
1359 cspm_if_trans(false,_Then,Else,AS,X1,_S1,_S2,S3,WF) :- !, %print(ifte_false(Else)),nl,
1360 full_normalise_csp_process(Else,NElse), cspm_trans(NElse,A,X1,WF),
1361 merge_span_into_event(A,S3,AS).
1362 cspm_if_trans(Other,Then,Else,AS,X1,S1,S2,S3,WF) :-
1363 add_internal_error('Internal Error: Not a boolean value inside if-then-else: ',
1364 cspm_if_trans(Other,Then,Else,AS,X1,S1,S2,S3,WF)),
1365 fail.
1366
1367 :- block convert_into_interleave(-,-,?).
1368 convert_into_interleave([],Span,skip(Span)).
1369 convert_into_interleave([na_tuple([H|_])|T],Span,R) :- convert_into_interleave3(T,H,Span,R).
1370 :- block convert_into_interleave3(-,?,?,?).
1371 convert_into_interleave3([],X,_Span,X).
1372 convert_into_interleave3([na_tuple([H2|_])|T],H1,Span,'|||'(H1,Rest,Span)) :-
1373 convert_into_interleave3(T,H2,Span,Rest).
1374
1375
1376 :- block convert_into_choice(-,-,?).
1377 convert_into_choice([],Span,stop(Span)).
1378 convert_into_choice([H|T],Span,R) :- convert_into_choice3(T,H,Span,R).
1379 :- block convert_into_choice3(-,?,?,?).
1380 convert_into_choice3([],X,_Span,X).
1381 convert_into_choice3([H2|T],H1,Span,'[]'(H1,Rest,Span)) :- convert_into_choice3(T,H2,Span,Rest).
1382
1383 :- block convert_into_seqcomp(-,-,?).
1384 convert_into_seqcomp(Bodies,Span,Res) :- convert_into_seqcomp2(Bodies,Span,Res).
1385 convert_into_seqcomp2([],Span,skip(Span)) :- print(convert_into_seqcomp2([],Span,skip(Span))),nl.
1386 convert_into_seqcomp2([H|T],Span,R) :- convert_into_seqcomp3(T,H,Span,R).
1387 :- block convert_into_seqcomp3(-,?,?,?).
1388 convert_into_seqcomp3([],X,_Span,X).
1389 convert_into_seqcomp3([H2|T],H1,Span,';'(H1,Rest,Span)) :-
1390 convert_into_seqcomp2([H2|T],Span,Rest).
1391
1392
1393 :- block convert_into_eaParallel(-,-,?,?).
1394 convert_into_eaParallel([],Span,skip(Span),setValue([])).
1395 convert_into_eaParallel([H|T],Span,APAR,ALPH) :-
1396 when(nonvar(T),convert_into_eaParallel3([H|T],Span,APAR,ALPH)).
1397 convert_into_eaParallel3([list([Sync,X,_])],_Span,X,ESync) :- !, evaluate_argument(Sync,ESync).
1398 convert_into_eaParallel3([list([CListX,X,_]),L2|T], Span,AlphPar, Alphabet ) :-
1399 when(nonvar(T),(convert_into_eaParallel3([L2|T],Span, Rest,RestAlphabet),
1400 evaluate_argument(CListX,ECListX),
1401 evaluate_argument(union(RestAlphabet,ECListX),Alphabet),
1402 /* put more complicated process onto the left: better efficiency for cspm_trans */
1403 % TO DO: we could think about splitting the list in two
1404 AlphPar = aParallel(RestAlphabet,Rest,ECListX,X,Span))). % only aParallel
1405
1406
1407
1408 :- block convert_into_Sharing(-,?,-,?).
1409 convert_into_Sharing([],_,Span,skip(Span)).
1410 convert_into_Sharing([na_tuple([H|_])|T],SyncSet,Span,R) :- convert_into_Sharing3([H|T],SyncSet,Span,R).
1411 :- block convert_into_Sharing3(-,?,?,?).
1412 convert_into_Sharing3([X],_Sync,_Span,Res) :- !, Res=X.
1413 convert_into_Sharing3([X|T],CListX,Span,sharing(CListX,Rest,X,Span) ) :-
1414 /* put more complicated process onto the left: better efficiency for cspm_trans */
1415 convert_into_Sharing(T,CListX,Span,Rest).
1416
1417 :- block convert_into_linkParallel(-,?,?,?,?).
1418 convert_into_linkParallel([],_,Span,skip(Span),Body) :-
1419 add_error(haskell_csp,'Empty Set in Replicated Linked Parallel: ',Body,Span).
1420 convert_into_linkParallel([H|T],SyncSet,Span,APAR,Body) :-
1421 convert_into_linkParallel3([H|T],SyncSet,Span,APAR,Body).
1422 :- block convert_into_linkParallel3(-,?,?,?,?).
1423 convert_into_linkParallel3([X],_Sync,_Span,Res,_) :- !, Res=X.
1424 convert_into_linkParallel3([X|T],CListX,Span,lParallel(CListX,X,Rest,Span),Body ) :-
1425 /* in contrast to convert_into_Sharing3: we cannot put more complicated process onto the left: order matters for linked parallel */
1426 convert_into_linkParallel(T,CListX,Span,Rest,Body).
1427
1428 /* ------------------------------------- */
1429
1430 /* top_level_normalise */
1431 /* Just check the top-level of the csp expression to see if it can
1432 be simplified/normalised */
1433 tl_normalise('[]'(X,Y,Span),R) :- !, %print(tl(X)),nl,print(t2(Y)),nl,nl,
1434 (X=Y -> R=X
1435 ; is_stop(X,_) -> R=Y
1436 ; is_stop(Y,_) -> R=X
1437 ; Y='[]'(X,Y2,_) -> tl_normalise('[]'(X,Y2,Span),R) % X [] X [] Y == X [] Y ; relevant e.g. for ASTD library example
1438 ; Y='[]'(Y2,X,_) -> tl_normalise('[]'(X,Y2,Span),R)
1439 ; X='[]'(Y,X2,_) -> tl_normalise('[]'(Y,X2,Span),R)
1440 ; X='[]'(X2,Y,_) -> tl_normalise('[]'(Y,X2,Span),R)
1441 ; R='[]'(X,Y,Span)
1442 ). /* TO DO: also sort X,Y !? */
1443 tl_normalise('|||'(X,Y,Span),R) :- !,
1444 (is_stop(X,S),is_stop(Y,_)
1445 -> R=stop(S)
1446 ; ((X==omega;is_skip(X)) -> R=Y /* law 6.16 on page 142 of Roscoe's book */
1447 ; ((Y==omega;is_skip(Y)) -> R=X /* same law, for RHS */
1448 ; % this leads to performance loss: tl_normalise should only do top-level normalisation full_normalise_csp_process(X,XR), full_normalise_csp_process(Y,YR),
1449 ((preference(cspm_detailed_animation,true);X @=<Y)
1450 -> R='|||'(X,Y,Span)
1451 ; R='|||'(Y,X,Span)) %% Warning: this can invalidate left-right Span information
1452 )
1453 )
1454 ). % we could replace skip|||P by P
1455 % (X==stop -> R=Y ; (Y==stop -> R=X ; R='|||'(X,Y))). P ||| stop not equal to stop (because of omega)
1456 tl_normalise(ehide(X,CList,Span),R) :- !,
1457 (is_stop(X,S) -> R=stop(S) % Concealement law L4
1458 ; is_skip(X,S) -> R=skip(S) % Concealement law L5
1459 ; CList == [] -> R=X % Concealement law L1
1460 ; try_tl_normalise(X,NX),R=ehide(NX,CList,Span)).
1461 tl_normalise(eprocRenaming(RL,X,Span),R) :- !,
1462 (is_stop(X,S) -> R=stop(S)
1463 ; is_skip(X,S) -> R=skip(S)
1464 ; try_tl_normalise(X,NX),R=eprocRenaming(RL,NX,Span)).
1465 tl_normalise(';'(X,Y,SPAN),R) :- !,
1466 (is_skip(X) -> R=Y /* Law on page 140 of Roscoe */
1467 ; is_stop(X,S) -> R=stop(S)
1468 ; is_skip(Y) -> R=X
1469 ; R = ';'(X,Y,SPAN) ).
1470 tl_normalise('/\\'(X,Y,Span),R) :- !,
1471 (is_stop(X,_) -> R=Y ; (is_stop(Y,_) -> R=X ; R='/\\'(X,Y,Span))).
1472 tl_normalise(ifte(A,B,C,_,_,_),R) :- !, % print(norm_ifte(A)),nl,
1473 evaluate_boolean_expression(A,ARes),
1474 % print(res(ARes)),nl,
1475 tl_normalise_ifte(ARes,B,C,R).
1476
1477 is_stop(X,S) :- nonvar(X),X=stop(S).
1478
1479 :- block tl_normalise_ifte(-,?,?,?).
1480 tl_normalise_ifte(true,B,_C,R) :- !,full_normalise_csp_process(B,R).
1481 tl_normalise_ifte(false,_,C,R) :- !, full_normalise_csp_process(C,R).
1482 % evaluate_boolean_expression/2 will always throw an exception if A is not a boolean test
1483 % probably this case will never occur
1484 % tl_normalise_ifte(A,B,C,_R) :- add_error(tl_normalise,'Not a boolean test: ',A:B:C).
1485
1486 try_tl_normalise(A,R) :- (tl_normalise(A,B) -> R=B ; R=A).
1487
1488 is_skip(X) :- nonvar(X), X=skip(_).
1489 is_skip(X,Y) :- nonvar(X), X=skip(Y).
1490 % TO DO: add rules esharing(_,stop(S),stop(_),_) -> stop(S),
1491
1492 % P [] STOP = P
1493 :- assert_must_succeed((
1494 P='[]'(skip(_),stop(span1),span2),
1495 haskell_csp: full_normalise_csp_process(P,NormP),
1496 NormP=skip(_))).
1497 % P [] P = P
1498 :- assert_must_succeed((
1499 P='[]'(skip(span1),skip(span1),span3),
1500 haskell_csp: full_normalise_csp_process(P,NormP),
1501 NormP=skip(span1))).
1502 % P ||| STOP = STOP
1503 :- assert_must_succeed((
1504 P='|||'(skip(_),stop(span1),span2),
1505 haskell_csp: full_normalise_csp_process(P,NormP),
1506 NormP=stop(span1))).
1507 % SKIP; (P [] STOP) = P
1508 :- assert_must_succeed((
1509 P=';'(skip(_),'[]'(skip(span1),stop(span3),span4),span2),
1510 haskell_csp: full_normalise_csp_process(P,NormP),
1511 NormP='[]'(skip(span1),stop(span3),span4))).
1512 % P; SKIP = P
1513 :- assert_must_succeed((
1514 P=';'(stop(_),skip(span1),span2),
1515 haskell_csp: full_normalise_csp_process(P,NormP),
1516 NormP=stop(_))).
1517
1518 /* ------------------------------------- */
1519 %full_normalise_csp_process(P,_) :- print(full_normalise_csp_process(P)),nl,fail.
1520 /* TO DO: add other procRep,... intermediate operators */
1521 ?full_normalise_csp_process(P,NormP) :- full_normalise_csp_process(P,NormP,outer).
1522 :- block full_normalise_csp_process(-,?,?).
1523 full_normalise_csp_process('|||'(X,Y,Span),Res,_) :- !,
1524 %full_normalise_csp_process(X,NX,inner), full_normalise_csp_process(Y,NY,inner),
1525 ? full_normalise_csp_process(X,NX,outer), full_normalise_csp_process(Y,NY,outer),
1526 tl_normalise('|||'(NX,NY,Span),Res).
1527 % both clausels below will be probably never executed. procRenamingComp/3 and procRepAParallel/3 as
1528 % replicated process expressions will be translated to agent_calls in the compiling/analyzing stage
1529 % of loading the respective CSP model. DEAD CODE:
1530 /*full_normalise_csp_process(procRenamingComp(X,GeneratorList,RenameList),Res,_) :- !,
1531 %print(normalise_procCompRenaming(GeneratorList)),nl,
1532 replicate_expand_set_comprehension(RenameList,GeneratorList,setValue(ExpandedRenames)),
1533 %print(exp(ExpandedRenames)),nl,
1534 Res = procRenaming(ExpandedRenames,X,no_loc_info_available).
1535 full_normalise_csp_process(procRepAParallel(GeneratorList,pair(SyncSet,Body),Span), Res,_) :- !,
1536 %print(procRepAParallel(GeneratorList,SyncSet)),nl,
1537 extract_variables_from_generator_list(GeneratorList,Variables),
1538 replicate_expand_set_comprehension([list([SyncSet,Body,Variables])],GeneratorList,setValue(Bodies)),
1539 %print(bodies(Bodies)),nl,
1540 convert_into_eaParallel(Bodies,Span,APAR,_ALPH), %print(apar(APAR,_ALPH)),nl,
1541 full_normalise_csp_process(APAR,Res,inner). */
1542 full_normalise_csp_process(repInterleave(GeneratorList,Body,Span),Res,_) :- !,
1543 extract_variables_from_generator_list(GeneratorList,Variables),
1544 replicate_expand_set_comprehension([na_tuple([Body|Variables])],GeneratorList,setValue(Bodies)),
1545 convert_into_interleave(Bodies,Span,Res).
1546 full_normalise_csp_process(sharing(CList,X,Y,SrcSpan),Res,_) :- !,
1547 evaluate_argument(CList,EvCList),
1548 expand_channel_pattern_expression(EvCList,ECList,SrcSpan),
1549 full_normalise_csp_process(X,NX,outer),
1550 full_normalise_csp_process(Y,NY,outer),
1551 Res = esharing(ECList,NX,NY,SrcSpan).
1552 full_normalise_csp_process(aParallel(CListX,X,CListY,Y,SrcSpan),Res,_) :- !,
1553 evaluate_argument(CListX,EvCListX),
1554 expand_channel_pattern_expression(EvCListX,ECListX,SrcSpan),
1555 evaluate_argument(CListY,EvCListY),
1556 expand_channel_pattern_expression(EvCListY,ECListY,SrcSpan),
1557 full_normalise_csp_process(X,NX,outer),
1558 full_normalise_csp_process(Y,NY,outer),
1559 %print(eaParallel(ECListX,NX,ECListY,NY,SrcSpan)),nl,
1560 Res = eaParallel(ECListX,NX,ECListY,NY,SrcSpan).
1561 /* Unfold if Par ground and unfolded value ground ?? */
1562 full_normalise_csp_process(agent_call(Span,F,Par),Res,outer) :- % only allow outer agent_calls to be unfolded to avoid infinite expansion for e.g. P(1) = P(1) ||| P(1)
1563 preference(cspm_detailed_animation,false),
1564 %% fail, %% fail: agent_calls are not expanded here, which means better source location feedback in animator
1565 %% WE COULD MAKE THIS AN OPTION IN THE PREFERENCES; I am not sure what the performance impact is
1566 %% for scheduler this leads to a substantial increase in the number of states
1567 !,
1568 ((ground(Par),unfold_function_call_once(F,Par,Value,Span),
1569 (ground(Value) ;
1570 agent_can_be_unfolded(Value)
1571 )
1572 )
1573 -> full_normalise_csp_process(Value,Res,outer)
1574 ; Res = agent_call(Span,F,Par)
1575 ).
1576 full_normalise_csp_process(val_of(RenamedX,Span),NormState,_) :- !,
1577 (symbol(RenamedX,_X,_,_) ->
1578 full_normalise_csp_process(agent_call(Span,RenamedX,[]),NormState,_)
1579 ;
1580 % does this occur in some case (see coverage info)
1581 full_normalise_csp_process(RenamedX,NormState,_)
1582 ).
1583 full_normalise_csp_process(ifte(Test,Then,Else,S1,S2,S3),R,_) :-
1584 ground(Test),!,
1585 evaluate_boolean_expression(Test,Res),
1586 (Res == true ->
1587 full_normalise_csp_process(Then,R)
1588 ; Res == false ->
1589 full_normalise_csp_process(Else,R)
1590 ;
1591 add_internal_error('Internal Error: Not a boolean value inside if-then-else: ',
1592 full_normalise_csp_process(ifte(Test,Then,Else,S1,S2,S3),R,_)),fail
1593 ).
1594 full_normalise_csp_process(ifte(Test,Then,Else,S1,S2,S3),R,_) :- !,
1595 R = ifte(Test,Then,Else,S1,S2,S3). % test could be false or true; top-level test could be evaluated ?!
1596 full_normalise_csp_process('&'(Test,Then),R,_) :- !, R = '&'(Test,Then). % test could be false; don't unfold agent_calls inside Then
1597 full_normalise_csp_process(';'(P,Q,SPAN),R,Scope) :- !,
1598 ? full_normalise_csp_process(P,NP,Scope),
1599 tl_normalise(';'(NP,Q,SPAN),R).
1600 full_normalise_csp_process(prefix(SPAN,Values,ChannelExpr,CSP,SPAN2),R,_) :- !,
1601 (empty_inGuard_set(Values) ->
1602 R=stop(SPAN) % (STOP-step) ?x:{} -> P = STOP (law 1.15)
1603 ;
1604 R = prefix(SPAN,Values,ChannelExpr,CSP,SPAN2)
1605 ).
1606 full_normalise_csp_process(head(List),R,_) :- !, R=head(List). % should we evaluate ??
1607 full_normalise_csp_process(agent_call(Span,A,Par),R,_) :- !, R=agent_call(Span,A,Par).
1608 % DEAD CODE!!! agent_call_curry/2 will be translated into nested agent_call in the precompiling phase.
1609 %full_normalise_csp_process(agent_call_curry(A,Par),R,_) :- !, print(agent_call_curry(A,Par)),nl,R=agent_call_curry(A,Par).
1610 full_normalise_csp_process(ehide(X,CList,Span),R,_) :- !,
1611 full_normalise_csp_process(X,NX,inner),
1612 tl_normalise(ehide(NX,CList,Span),R).
1613 full_normalise_csp_process(eprocRenaming(RL,X,Span),R,_) :- !,
1614 full_normalise_csp_process(X,NX,inner),
1615 tl_normalise(eprocRenaming(RL,NX,Span),R).
1616 full_normalise_csp_process(Proc,Res,_) :-
1617 binary_top_level_process_operator_possible_to_be_normalised(Proc,F,X,Y,Span),!,
1618 ? full_normalise_csp_process(X,NX,inner),
1619 ? full_normalise_csp_process(Y,NY,inner),
1620 functor(NTerm,F,3),arg(1,NTerm,NX),arg(2,NTerm,NY),arg(3,NTerm,Span),
1621 tl_normalise(NTerm,Res).
1622 ?full_normalise_csp_process(Proc,Res,_) :- definite_cspm_process_construct(Proc,Spans,Rest,RecCSP), !,
1623 functor(Proc,F,N), functor(Res,F,N),
1624 maplist(full_normalise_csp_process_inner(inner),RecCSP,NormRecCSP),
1625 ? definite_cspm_process_construct(Res,Spans,Rest,NormRecCSP).
1626 full_normalise_csp_process(P,R,_) :- !,
1627 add_warning(full_normalise_csp_process,'Could not normalise: ',P),R=P.
1628
1629 full_normalise_csp_process_inner(ProcLabel,Proc,NProc) :-
1630 full_normalise_csp_process(Proc,NProc,ProcLabel).
1631
1632 binary_top_level_process_operator_possible_to_be_normalised(ProcessTerm,F,X,Y,Span) :-
1633 functor(ProcessTerm,F,3),
1634 memberchk(F,['|||','[]','/\\']),
1635 arg(1,ProcessTerm,X),arg(2,ProcessTerm,Y),arg(3,ProcessTerm,Span).
1636
1637 empty_inGuard_set(Values) :-
1638 member(inGuard(_X,Set),Values),
1639 is_empty_set(Set,true),!.
1640
1641 normalise_cspm_state(State,NormState) :-
1642 full_normalise_csp_process(State,NormState).
1643
1644 %% Probably DEAD CODE !!! (wait for the next coverage release to prove this assumption)
1645 :- assert_must_succeed((agent_can_be_unfolded(X), X=procRenamingComp(_,_,_))).
1646 :- assert_must_succeed((agent_can_be_unfolded(X), X=aParallel(_,_,_,_,_))).
1647 agent_can_be_unfolded(procRenamingComp(_,_,_)).
1648 agent_can_be_unfolded(aParallel(_,_,_,_,_)).
1649 agent_can_be_unfolded(repInterleave(_,_,_)).
1650
1651 /* ------------------------------------- */
1652
1653
1654 /* EVALUATING Agent Call arguments */
1655
1656 evaluate_agent_call_parameters(AgentName,Par,_,_) :- var(AgentName),!,
1657 add_internal_error('Internal Error: Trying to call VARIABLE function: ',evaluate_agent_call_parameters(AgentName,Par,_,_)),fail.
1658 evaluate_agent_call_parameters(AgentName,Par,_,_) :- var(Par),!,
1659 add_internal_error('Internal Error: Trying to call VARIABLE parameters: ',evaluate_agent_call_parameters(AgentName,Par,_,_)),fail.
1660 %evaluate_agent_call_parameters(agent_call(AName,[]),Par,EAgentCall) :- atomic(AName),!,
1661 % /* then AName must represent a lambda function which has been compiled ?!!? */
1662 % l_evaluate_arguments(Par,EPar),
1663 % EAgentCall =.. [AName|EPar].
1664 evaluate_agent_call_parameters(_Call,Par,EPar,_) :- Par==[],!, EPar=[]. % nothing to evaluate
1665 evaluate_agent_call_parameters(AgentNameExpr,Par,_EAgentCall,Span) :- \+ atomic(AgentNameExpr),!,
1666 add_error(haskell_csp,'Trying to call non-atomic function: ',agent_call(AgentNameExpr,Par),Span),fail.
1667 evaluate_agent_call_parameters(AName,Par,EPar,Span) :-
1668 length(Par,Arity),
1669 (agent_parameters(AName,Arity,LazyStrictList)
1670 -> true
1671 ; add_error(evaluate_agent_call_parameters,'Unknown function call: ',(AName/Arity),Span)
1672 ),
1673 l_evaluate_arguments(Par,LazyStrictList,EPar).
1674 % EAgentCall =.. [AName|EPar].
1675
1676
1677 l_evaluate_arguments([],[],[]).
1678 l_evaluate_arguments([A|T],[Lazy|TL],[EA|ET]) :-
1679 %% print(eval_arg(A,Lazy)),nl, %%
1680 (Lazy=lazy -> evaluate_argument(A,EA)
1681 ; force_evaluate_argument(A,EA)
1682 ),
1683 %% print(arg_res(A,EA)),nl, %%
1684 l_evaluate_arguments(T,TL,ET).
1685
1686
1687 evaluate_lambda_arguments([],[],[]).
1688 evaluate_lambda_arguments([A|T],[FormalPar|FT],[EA|ET]) :-
1689 %% print(eval_arg(A,Lazy)),nl,
1690 (var(FormalPar) -> A=EA % will be copied into lambda body and evaluated then evaluate_argument(A,EA)
1691 ; force_evaluate_argument(A,EA) % it is a pattern; we need to evaluate argument
1692 ),
1693 %% print(arg_res(A,EA)),nl,
1694 evaluate_lambda_arguments(T,FT,ET).
1695 /* ------------------------------------- */
1696
1697 /* EVALUATING Channel arguments */
1698
1699 setup_skel(_,in(_)).
1700
1701 setup_channel_skeleton(io(V,Ch,_)) :-
1702 channel_type_list(Ch,ChannelTypes),
1703 maplist(setup_skel,ChannelTypes,V).
1704
1705 /* ------------------------------------- */
1706
1707 /* enumerate_action(A) : if part of the inputs of A are not determined: enumerate
1708 possible values */
1709
1710 cspm_trans_enum(E,A,E2) :-
1711 init_wait_flags(WF),
1712 cspm_trans(E,A,E2,WF),
1713 % tools:print_bt_message(grounding_waitflags(A)), %%
1714 ground_wait_flags(WF),
1715 % TO DO: we could also add enumerate_action to the WF store: in principle sets inGuards should be smaller
1716 % tools:print_bt_message(enumerate_action(E,A)), %%
1717 enumerate_action(A)
1718 % ,tools:print_bt_message(finished_enumerate_action(A)),nl %%
1719 .
1720
1721
1722 /* TO DO: add enumeration to hide + removed values by rename; use tau(V,Ch) ?? */
1723
1724 enumerate_action(X) :- X \= tick(_), X\=tau(_), X\= io(_,_,_), !,
1725 add_internal_error('Internal error: Unknown CSP event: ', enumerate_action(X)).
1726 enumerate_action(tick(_)).
1727 enumerate_action(tau(X)) :- (nonvar(X) -> enumerate_tau_argument(X) ; true).
1728 enumerate_action(io(Vals,Channel,Span)) :-
1729 if((channel_type_list(Channel,ChannelTypes)),
1730 (enume_ch_vals(ChannelTypes,Vals,Channel,Span,io(Vals,Channel,Span))),
1731 add_error(enumerate_action,'Channel not declared: ',Channel,Span)).
1732
1733 enumerate_tau_argument(io(V,C,S)) :- !,enumerate_action(io(V,C,S)).
1734 enumerate_tau_argument(hide(X)) :- !,enumerate_action(X).
1735 enumerate_tau_argument(link(_AX,AY)) :- !,enumerate_action(AY).
1736 enumerate_tau_argument(_).
1737
1738 :- use_module(probsrc(translate),[translate_event/2]).
1739 %% enume_ch_vals(T,V,C,_Span,FullEvent) :- print(enume_ch_vals(T,V,C)),nl,fail. %%
1740 enume_ch_vals([],[],_,_Span,_) :- !.
1741 enume_ch_vals([],Vals,_Channel,Span,FullEvent) :- !,
1742 (Vals = [in(V)]
1743 -> empty_tuple(V) /* the empty dotTuple */
1744 ; translate_event(FullEvent,ES),
1745 add_error(enumerate_action,'Too many output values on channel: ',ES:Vals, Span)
1746 ).
1747 enume_ch_vals([Type|RestTypes],Vals,Channel,Span,FullEvent) :- % T \= [],
1748 enume_ch_vals2(Vals,Type,RestTypes,Channel,Span,FullEvent).
1749
1750 enume_ch_vals2(X,Type,_RestTypes,_Channel,Span,FullEvent) :- % print(ecv2(X,Type,RestTypes,Channel)),nl,
1751 var(X),!,
1752 translate_event(FullEvent,ES),
1753 add_error(haskell_csp,'Variable value list on channel: ',ES:X:Type,Span),fail.
1754 enume_ch_vals2([],Type,RestTypes,_Channel,Span,FullEvent) :- !,
1755 translate_event(FullEvent,ES),
1756 add_error(enumerate_action,'Too few output values on channel: ',ES:[Type:RestTypes], Span).
1757 enume_ch_vals2([in(V)|TAIL],Type,RestTypes,Channel,Span,FullEvent) :- nonvar(V),
1758 V=tuple(X),nonvar(X),X=[H|T], \+ csp_constructor(H,_,_),
1759 !, % sometimes an in contains dot tuples; test above not very elegant; can we simplify this ??
1760 (T==[] ->
1761 enume_ch_vals2([in(H)|TAIL],Type,RestTypes,Channel,Span,FullEvent)
1762 ; enume_ch_vals2([in(H),in(tuple(T))|TAIL],Type,RestTypes,Channel,Span,FullEvent)).
1763 enume_ch_vals2([in(V)|TAIL],Type,RestTypes,Channel,Span,_FullEvent) :-
1764 TAIL==[],!, /* only treat it as a tail_in(X) if it is definitely at the end of the list
1765 see example LetTestChannel -> TEST(2) process for complication if we do
1766 not check that TAIL==[] */
1767 (RestTypes=[]
1768 -> enumerate_channel_input_value(Type,V,Channel,Span)
1769 ; enumerate_channel_input_value('dotTupleType'([Type|RestTypes]),V,Channel,Span)
1770 ).
1771 enume_ch_vals2([IODVal|TV],Type,RestTypes,Channel,Span,FullEvent) :- !,
1772 enumerate_channel_value_type(IODVal,Type,Channel,Span),
1773 enume_ch_vals(RestTypes,TV,Channel,Span,FullEvent).
1774
1775
1776 enumerate_channel_value_type(IOD,Type,Channel,Span) :-
1777 %print(enumerate_channel_value_type(IOD,Type,Channel,Span)),nl,
1778 (IOD=in(HX) %; IOD=dot(HX))
1779 -> enumerate_channel_input_value(Type,HX,Channel,Span)
1780 ; (ground(IOD)
1781 -> check_channel_input_output_value(IOD,Type,Channel,Span,'Type error in channel input: ')
1782 ; enumerate_channel_input_value(Type,IOD,Channel,Span)
1783 )
1784 ).
1785
1786 check_channel_input_output_value(X,Type,Ch,Span,ErrMsg) :-
1787 when(ground(X), ((peel_in(X,PX),is_member_set_alsoPat(PX,Type)) -> true
1788 ; add_error(check_channel_output_value,ErrMsg,(Ch:(val(X):type(Type))),Span))).
1789
1790 /* peel input values which may lurk inside datavalues, especially records */
1791 peel_in(in(X),R) :- !, R=X.
1792 peel_in(record(F,L),R) :- !,
1793 R=record(F,PL),
1794 maplist(peel_in,L,PL).
1795 peel_in(X,X).
1796
1797 :- assert_must_succeed(( haskell_csp:enumerate_channel_input_value(setFromTo(1,3),R,c,unknown),
1798 R==int(2) )).
1799
1800 enumerate_channel_input_value(Type,Val,Ch,Span) :-
1801 MAXRECURSIONDEPTH = 2,
1802 ? enumerate_channel_input_value(Type,Val,Ch,MAXRECURSIONDEPTH,Span).
1803
1804
1805 enumerate_channel_input_value(Type,Val,Ch,MaxRec,Span) :-
1806 (ground(Val)
1807 -> check_channel_input_output_value(Val,Type,Ch,Span,'Type error in channel output: ')
1808 ? ; enumerate_channel_input_value1(Type,Val,Ch,MaxRec,Span)
1809 ).
1810
1811 enumerate_channel_input_value1(Type,Val,Ch,MaxRec,Span) :-
1812 ((nonvar(Val),Val=in(VX)) /* can happen when question marks occur inside records, ... */
1813 -> enumerate_channel_input_value1_1(Type,VX,Ch,MaxRec,Span)
1814 ? ; enumerate_channel_input_value1_1(Type,Val,Ch,MaxRec,Span)
1815 ).
1816
1817 enumerate_channel_input_value1_1(Type,Val,Ch,MaxRec,Span) :-
1818 ( (nonvar(Val),Val=alsoPat(X,Y)) ->
1819 enumerate_channel_input_value2(Type,X,Ch,MaxRec,Span),
1820 %enumerate_channel_input_value2(Type,Y,Ch,MaxRec,Span),
1821 unify_also_patterns(X,Y,_R)
1822 ; (nonvar(Val),Val=appendPat(X,FunHead)) ->
1823 agent_compiled(FunHead,_Value,_SRCSPAN),
1824 enumerate_channel_input_value2(Type,X,Ch,MaxRec,Span)
1825 ? ; enumerate_channel_input_value2(Type,Val,Ch,MaxRec,Span)
1826 ).
1827
1828 :- dynamic ignore_infinite_datatypes/0. % set from refinement_checker; very HACKY
1829
1830 %enumerate_channel_input_value2(T,V,Ch,_MaxRec) :- print(enumerate_channel_input_value(T,V,Ch)),nl,fail.
1831 :- assert_must_succeed((findall(Res, enumerate_channel_input_value2('Set'(setValue([int(1),int(2)])),Res,_Ch,_MaxRec,_Span),L),
1832 L == [setValue([int(1),int(2)]),setValue([int(1)]),setValue([int(2)]),setValue([])])).
1833
1834 enumerate_channel_input_value2(intType,X,Ch,_MaxRec,_Span) :- !,
1835 enumerate_basic_type(X,integer,trigger_true(Ch)). % NOTE : this uses MAXINT preference value!
1836 enumerate_channel_input_value2(boolType,X,_Ch,_MaxRec,_Span) :- !,(X=true ; X=false).
1837 enumerate_channel_input_value2(setFromTo(Low,Up),Res,Ch,_MaxRec,Span) :- !,
1838 set_enumeration_result(Res,int(X),Ch,setFromTo(Low,Up),Span),
1839 ? enumerate_csp_int(X,Low,Up).
1840 /*(preference(use_clpfd_solver,true),clpfd_interface: fd_var(Res) ->
1841 clpfd_interface: csp_clpfd_labeling([ffc,enum],[Res])
1842 ; set_enumeration_result(Res,int(X),Ch,setFromTo(Low,Up),Span),
1843 enumerate_csp_int(X,Low,Up)
1844 ).*/
1845 enumerate_channel_input_value2(setFrom(Low),V,Ch,_MaxRec,Span) :- !,
1846 add_symbol_span(Ch,Span,CSpan),
1847 add_error(enumerate_channel_input_value,'Cannot enumerate infinite Type: ',(Ch,(setFrom(Low),V)),CSpan).
1848 enumerate_channel_input_value2('Set'(X),Res,_Ch,_MaxRec,_Span) :- !, /* Probably DEAD CODE */
1849 ? enum_subset(X,Res).
1850 enumerate_channel_input_value2('dotTupleType'(List),Res,Ch,MaxRec,Span) :- !,
1851 set_enumeration_tuple_result(Res,RR,Ch,'dotTupleType'(List),Span),
1852 l_enumerate_channel_input_value2(List,RR,Ch,dot_tuple,MaxRec,Span).
1853 enumerate_channel_input_value2('typeTuple'(List),Res,Ch,MaxRec,Span) :- !,
1854 set_enumeration_result(Res,na_tuple(RR),Ch,'typeTuple'(List),Span),
1855 % print(enum_tuple('typeTuple'(List),Res,Ch)),nl,
1856 l_enumerate_channel_input_value2(List,RR,Ch,type_tuple,MaxRec,Span).
1857 enumerate_channel_input_value2(setValue(L),R,_Ch,_MaxRec,_Span) :- !,member(R,L). /* R should be list skeleton at least */
1858 enumerate_channel_input_value2(dataType(DT),C,Channel,MaxRec,Span) :- is_a_datatype(DT,_), !,
1859 enumerate_datatype_el(DT,C,Channel,MaxRec,Span).
1860 % TO DO: add all other types supported by is_member_set
1861 enumerate_channel_input_value2('Seq'(setValue([])),V,_Ch,_MaxRec,_Span) :- !, V= list([]).
1862 enumerate_channel_input_value2('Seq'(Type),V,Ch,_MaxRec,Span) :- !,
1863 (ignore_infinite_datatypes -> V=sequence % needed for the Trace Debugger in Tcl/Tk
1864 ; add_symbol_span(Ch,Span,CSpan),
1865 add_error(enumerate_channel_input_value,'Cannot enumerate infinite Seq Type: ',(Ch,('Seq'(Type),V)),CSpan)).
1866 enumerate_channel_input_value2(agent_call(_Src, Name,Patterns),Val,Ch,_MaxRec,Span) :- !,
1867 unfold_function_call_once(Name,Patterns,Res,Span),
1868 evaluate_argument(Res,Res1),
1869 enumerate_channel_input_value(Res1,Val,Ch,Span).
1870 enumerate_channel_input_value2(Type,V,Ch,_MaxRec,Span) :-
1871 add_symbol_span(Ch,Span,CSpan),
1872 add_error(enumerate_channel_input_value,'Illegal type for channel: ',(Ch,(Type,V)),CSpan).
1873
1874 :- dynamic enum_warning_occured/3.
1875 :- use_module(probsrc(tools_strings),[ajoin/2]).
1876
1877 enumerate_datatype_el(DT,C,Channel,_MaxRec,Span) :-
1878 if(csp_constant(C,DT),true,
1879 (nonvar(C),C \= record(_,_),
1880 add_error(enumerate_datatype_el,'Type error for channel input variable: ', Channel:(C,type(DT)),Span),
1881 fail)).
1882 enumerate_datatype_el(DT,C,Channel,MaxRec,Span) :-
1883 ((MaxRec>0 ; nonvar(C))
1884 ->((nonvar(C) -> M1 = MaxRec ; M1 is MaxRec-1),
1885 C=record(Cons,Fields),
1886 csp_constructor(Cons,DT,ArgSubTypes),
1887 % print(recurse_enum_rec(Cons,DT,ArgSubTypes,Fields)),nl,
1888 l_enumerate_channel_input_value2(ArgSubTypes,Fields,Channel,dot_tuple,M1,Span))
1889 ; enum_warning_occured(DT,Channel,Span) -> fail
1890 ; ajoin(['Maximum recursion depth reached on channel "',Channel,
1891 '" for enumeration of datatype : '],Msg),
1892 add_message(csp,Msg,DT,Span),
1893 assertz(enum_warning_occured(DT,Channel,Span)),
1894 % THIS used to return a variable when ignore_infinite_datatypes true, but causes problems for test 2349
1895 fail
1896 ).
1897
1898 % ensure that ResVar is a tuple and flatten the tuple
1899 set_enumeration_tuple_result(ResVar,ResultTerm,Channel,ExpectedType,Span) :-
1900 ((tuple(TL)=ResVar;dotTuple(TL)=ResVar) ->
1901 %print(flattening(ResVar)),nl,
1902 flatten_tuple_value(TL,ResultTerm) /* ok, no type error */
1903 ; add_symbol_span(Channel,Span,CSpan),
1904 add_error(set_enumeration_tuple_result,'Type error for instantiated channel input variable: ',Channel:(ResVar,type(ExpectedType)),CSpan),
1905 fail).
1906
1907 %%%%%%%%%%%%%%%%%%%%% UNIT TESTS FOR flatten_tuple_value/2, flatten_inner_tuple_value/2 and flatten2/3 %%%%%%%%%%%%%%%%%%%%%%%%%%
1908 :- assert_must_succeed((haskell_csp: flatten_tuple_value(X,R), R == X)).
1909 :- assert_must_succeed((haskell_csp: flatten_tuple_value([],R), R == [])).
1910 :- assert_must_succeed((haskell_csp: flatten_tuple_value([X,tuple([int(1),int(2)])],R), R == [X,int(1),int(2)])).
1911 :- assert_must_succeed((haskell_csp: flatten_tuple_value([tuple([]),tuple([int(1),int(2)]),X,Y,tuple([int(10)])],R), R == [int(1),int(2),X,Y,int(10)])).
1912 :- assert_must_succeed((haskell_csp: flatten_tuple_value([X,tuple([int(1),Y,int(2),Z])],R), R == [X,int(1),Y,int(2),Z])).
1913 :- assert_must_succeed((haskell_csp: flatten_tuple_value([X,tuple([int(1),Y,int(2),Z]),int(3)],R), R == [X,int(1),Y,int(2),Z,int(3)])).
1914 :- assert_must_succeed((haskell_csp: flatten_tuple_value([],[]))).
1915 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1916
1917 flatten_tuple_value(X,R) :- var(X),!, R=X. % this can happen if we have a single in(X) representing ch?x
1918 flatten_tuple_value([],[]).
1919 flatten_tuple_value([H|T],R) :- flatten2(H,T,R).
1920
1921 flatten_inner_tuple_value(X,R) :- var(X),!, print(variable_inner_tuple(X)),nl, R=[X].
1922 flatten_inner_tuple_value([],[]).
1923 flatten_inner_tuple_value([H|T],R) :- flatten2(H,T,R).
1924
1925 flatten2(VAR,T,Res) :- var(VAR),!, Res=[VAR|TR],flatten_inner_tuple_value(T,TR).
1926 flatten2(tuple(LH),T,R) :- !, flatten_inner_tuple_value(LH,FLH),
1927 append(FLH,TR,R), flatten_inner_tuple_value(T,TR).
1928 flatten2(H,T,[H|TR]) :- flatten_inner_tuple_value(T,TR).
1929
1930 set_enumeration_result(ResVar,ResultTerm,Channel,ExpectedType,Span) :-
1931 (ResVar=ResultTerm -> true /* ok, no type error */
1932 ;
1933 add_symbol_span(Channel,Span,CSpan),
1934 add_error(set_enumeration_result,'Type error for instantiated channel input variable: ',Channel:(val(ResVar),type(ExpectedType)),CSpan),
1935 fail).
1936
1937 l_enumerate_channel_input_value2([],R,Ch,_SType,_MaxRec,Span) :- !,
1938 (var(R) -> R=[]
1939 ; R=[] -> true
1940 ; add_error(l_enumerate_channel_input_value,'Too many arguments on channel: ',(Ch,R),Span),fail).
1941 l_enumerate_channel_input_value2([HType|T],[HVal|TV],Ch,SType,MaxRec,Span) :- !,
1942 ((TV==[],SType=dot_tuple) -> % enume the rest of the channel types to HVal (only for dotTuple types)
1943 enume_ch_vals([HType|T],[in(HVal)],Ch,Span,io([],Ch)) % TO DO: full event
1944 ;
1945 enumerate_channel_input_value(HType,HVal,Ch,MaxRec,Span), %% <-- add Span
1946 l_enumerate_channel_input_value2(T,TV,Ch,SType,MaxRec,Span)
1947 ).
1948 l_enumerate_channel_input_value2([HType|T],[],Ch,_SType,_MaxRec,Span) :- !,
1949 add_error(l_enumerate_channel_input_value,'Not enough arguments on channel: ',(Ch,[HType|T]),Span),fail.
1950 l_enumerate_channel_input_value2(X,Y,Ch,SType,MR,Span) :-
1951 add_internal_error('Illegal arguments: ',l_enumerate_channel_input_value2(X,Y,Ch,SType,MR,Span)),fail.
1952
1953 get_symbol_span(S,SPAN) :- atomic(S),symbol(S,_,SPAN,_),!.
1954 get_symbol_span(S,SPAN) :- nonvar(S),functor(S,FS,_),symbol(FS,_,SPAN,_),!.
1955 get_symbol_span(_S,no_loc_info_available).
1956
1957
1958 add_symbol_error(Src,Msg,Term,Ch) :-
1959 get_symbol_span(Ch,Span),
1960 add_error(Src,Msg,Term,Span).
1961
1962 add_symbol_span(Ch,Span,OutSpan) :- get_symbol_span(Ch,SSpan),
1963 SSpan \= no_loc_info_available,
1964 !,
1965 unify_spans(Span,SSpan,OutSpan).
1966 add_symbol_span(_,S,S).
1967
1968 % just like above, but can also be called with ordinary spans
1969 add_error_with_span(Src,Msg,Term,Span) :-
1970 (Span=symbol(S) -> get_symbol_span(S,Span2) ; Span2=Span),
1971 add_error(Src,Msg,Term,Span2).
1972
1973 add_internal_error_with_span(Src,Msg,Term,Span) :-
1974 (Span=symbol(S) -> get_symbol_span(S,Span2) ; Span2 = Span),
1975 add_internal_error(Src,Msg,Term,Span2).
1976
1977 /* ------------------------------------- */
1978 /* BOOLEAN EXPRESSIONS */
1979 /* ------------------------------------- */
1980
1981 %%%%%%%% UNIT TESTS FOR TESTING check_boolean_expressions/1,cond_check_boolean_expression/2,ifte_check_boolean_expression/3 %%%%%%%
1982
1983 :- assert_must_succeed((haskell_csp: check_boolean_expression(true))).
1984 :- assert_must_fail((haskell_csp: check_boolean_expression(X), X = false)).
1985 :- assert_must_succeed((haskell_csp: check_boolean_expression(bool_not(false)))).
1986 :- assert_must_fail((haskell_csp: check_boolean_expression(X), X = false)).
1987 :- assert_must_succeed((haskell_csp: check_boolean_expression(bool_or(true,_X)))).
1988 :- assert_must_succeed((haskell_csp: check_boolean_expression(bool_not('<='(int(1),int(0)))))).
1989 :- assert_must_fail((haskell_csp: check_boolean_expression(bool_not('<='(int(1),int(10)))))).
1990 :- assert_must_succeed((haskell_csp: check_boolean_expression(bool_and('<='(int(1),int(10)), true)))).
1991 :- assert_must_fail((haskell_csp: check_boolean_expression(bool_and(false,'<='(int(1),int(10)))))).
1992 :- assert_must_succeed((haskell_csp: check_boolean_expression(bool_or('<='(int(1),int(0)), true)))).
1993 :- assert_must_fail((haskell_csp: check_boolean_expression(bool_or(false,'<='(int(1),int(0)))))).
1994 :- assert_must_succeed((haskell_csp: check_boolean_expression('<='(int(10),int(X))), X = 30)).
1995 :- assert_must_succeed((haskell_csp: check_boolean_expression('>='(int(10),int(X))), X = 3)).
1996 :- assert_must_succeed((haskell_csp: check_boolean_expression('<='(int(10),int(X))), X = 10)).
1997 :- assert_must_succeed((haskell_csp: check_boolean_expression('>='(int(10),int(X))), X = 10)).
1998 :- assert_must_succeed((haskell_csp: check_boolean_expression('<'(int(10),int(X))), X = 30)).
1999 :- assert_must_succeed((haskell_csp: check_boolean_expression('>'(int(10),int(X))), X = 3)).
2000 :- assert_must_fail((haskell_csp: check_boolean_expression('<'(int(10),int(X))), X = 10)).
2001 :- assert_must_fail((haskell_csp: check_boolean_expression('>'(int(10),int(X))), X = 10)).
2002 :- assert_must_succeed((haskell_csp: check_boolean_expression(ifte('<='(int(3),int(20)),'>='(int(2),int(1)),'<='(int(3),int(1)),span,span,span)))).
2003 :- assert_must_succeed((haskell_csp: check_boolean_expression(ifte('<='(int(3),int(2)),'>='(int(2),int(1)),'<='(int(3),int(10)),span,span,span)))).
2004 :- assert_must_succeed((haskell_csp: check_boolean_expression(ifte('<='(int(3),int(2)),'>='(int(2),int(1)),'<='(int(3),int(10)),span,span,span)))).
2005 :- assert_must_succeed((haskell_csp: check_boolean_expression(ifte(X,'>='(int(2),int(1)),'<='(int(3),int(1)),span,span,span)),
2006 X = head(listExp(rangeEnum(['<='(int(2),int(3)),'>'(int(2),int(3))]))))).
2007 :- assert_must_fail((haskell_csp: check_boolean_expression(ifte(X,'>='(int(2),int(1)),'<='(int(3),int(1)),span,span,span)),
2008 X = head(listExp(rangeEnum(['<='(int(2),int(1)),'>'(int(2),int(3))]))))).
2009 :- assert_must_succeed((haskell_csp: check_boolean_expression(head(listExp(rangeEnum(['<'(int(2),int(3)),'>'(int(2),int(3))])))))).
2010 :- assert_must_succeed((haskell_csp: check_boolean_expression(head(listExp(rangeEnum([true,false])))))).
2011 :- assert_must_fail((haskell_csp: check_boolean_expression(head(listExp(rangeEnum([false,false])))))).
2012 :- assert_must_fail((haskell_csp: check_boolean_expression(head(listExp(rangeEnum([false,true])))))).
2013 :- assert_must_fail((haskell_csp: check_boolean_expression((head(listExp(rangeEnum([null(listExp(rangeEnum([false,true])))]))))))).
2014 :- assert_must_fail((haskell_csp: check_boolean_expression((head(listExp(rangeEnum([empty(setValue([int(1),int(2)]))]))))))).
2015 :- assert_must_succeed((haskell_csp: check_boolean_expression(empty(setExp(rangeEnum([])))))).
2016 :- assert_must_succeed((haskell_csp: check_boolean_expression(head(listExp(rangeEnum([bool_not(false)])))))).
2017 :- assert_must_succeed((haskell_csp: check_boolean_expression(head(listExp(rangeEnum([bool_or(true,false)])))))).
2018 :- assert_must_succeed((haskell_csp: check_boolean_expression(head(listExp(rangeEnum(['<='(int(2),int(3)),'>'(int(2),int(3))])))))).
2019 :- assert_must_fail((haskell_csp: check_boolean_expression(head(listExp(rangeEnum(['<='(int(2),int(1)),'>'(int(2),int(3))])))))).
2020 :- assert_must_succeed((haskell_csp: check_boolean_expression(null(listExp(rangeEnum([])))))).
2021 :- assert_must_fail((haskell_csp: check_boolean_expression(null(listExp(rangeEnum([int(1),int(2),int(3)])))))).
2022 :- assert_must_succeed((haskell_csp: check_boolean_expression(empty(setExp(rangeEnum([])))))).
2023 :- assert_must_fail((haskell_csp: check_boolean_expression(empty(setExp(rangeEnum([int(1),int(2),int(3)])))))).
2024 :- assert_must_succeed((haskell_csp: is_boolean_expression(true), haskell_csp: is_boolean_expression(false))).
2025
2026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2027
2028 :- block check_boolean_expression(-).
2029
2030 %check_boolean_expression(E) :- %print(check_boolean_expression(E)),nl,
2031 % var(E),add_error(check_boolean_expression,'Variable boolean expression:',E),fail.
2032 check_boolean_expression(true) :- !.
2033 check_boolean_expression(false) :- !, fail.
2034 check_boolean_expression(bool_not(BExpr1)) :- !,
2035 evaluate_boolean_expression(BExpr1,false). /* provide custom check_not_... predicate ?? */
2036 check_boolean_expression(bool_and(BExpr1,BExpr2)) :- !,
2037 check_boolean_expression(BExpr1),
2038 check_boolean_expression(BExpr2).
2039 check_boolean_expression(bool_or(BExpr1,BExpr2)) :- !,
2040 evaluate_boolean_expression(BExpr1,R1),
2041 cond_check_boolean_expression(R1,BExpr2).
2042 check_boolean_expression(ifte(Test,Then,Else,_,_,_)) :- !,
2043 evaluate_boolean_expression(Test,TestRes), %print(check_bool_ifte(Test,TestRes)),nl,
2044 ifte_check_boolean_expression(TestRes,Then,Else).
2045 check_boolean_expression(head(X)) :- !, force_evaluate_argument(X,EX),head_list(EX,HResult),
2046 check_boolean_expression(HResult).
2047 check_boolean_expression(null(Arg1)) :- !, force_evaluate_argument(Arg1,EX), is_null_list(EX,true).
2048 check_boolean_expression(empty(Arg1)) :- !, force_evaluate_argument(Arg1,EX), is_empty_set(EX,true).
2049 check_boolean_expression(agent_call(Span,F,Par)) :- !, /* in this context we need the result of the function call */
2050 unfold_function_call_once(F,Par,Body,Span),
2051 %when(nonvar(Body),
2052 check_boolean_expression(Body).
2053 check_boolean_expression('member'(Arg1,Arg2)) :- !, % after bool_binary_op: there is a special rule for member there
2054 force_evaluate_argument(Arg1,EX),
2055 force_evaluate_argument_for_member_check(Arg2,EY), %print(lazy_member(EX,EY)),nl,
2056 % causes 10 % slowdown on basin_olderog_bank, but code is probably required similar to evaluate_boolean_expression below
2057 % when(ground(EX), (ground(EY) -> is_member_set(EX,EY)
2058 % ; /* exploring lazy expression */ force_evaluate_argument(EY,REY),is_member_set(EX,REY))).
2059 when((ground(EX),ground(EY)), is_member_set(EX,EY)).
2060 check_boolean_expression(BExpr) :- %covering all boolean expression with relational operators instead of '==' and '!='%
2061 relational_binary_op(BExpr,Arg1,Arg2,EX,EY,Call),!,
2062 evaluate_int_argument(Arg1,EX),
2063 evaluate_int_argument(Arg2,EY),
2064 Call.
2065 check_boolean_expression(BExpr) :-
2066 bool_binary_op(BExpr,Arg1,Arg2,EX,EY,Call), !,
2067 %print(bool_binary_op(Arg1,Arg2,Call)),nl, %
2068 force_evaluate_argument(Arg1,EX),
2069 force_evaluate_argument(Arg2,EY),
2070 when((ground(EX),ground(EY)), Call).
2071 check_boolean_expression(X) :-
2072 add_error(haskell_csp,'Not a boolean expression: ',X),
2073 fail.
2074
2075
2076 :- block cond_check_boolean_expression(-,?).
2077 cond_check_boolean_expression(true,_).
2078 cond_check_boolean_expression(false,BExpr2) :- check_boolean_expression(BExpr2).
2079
2080 :- block ifte_check_boolean_expression(-,?,?).
2081 ifte_check_boolean_expression(true,Then,_) :- !, check_boolean_expression(Then).
2082 ifte_check_boolean_expression(false,_,Else) :- !, check_boolean_expression(Else).
2083 % evaluate_boolean_expression/3 will raise an error if the boolean expression in the ifte-condition cannot be evaluated to true or false => Internal Error
2084 ifte_check_boolean_expression(Other,Then,Else) :- add_internal_error(/*ifte_check_boolean_expression,*/
2085 'Internal Error: Not a boolean inside if-then-else test: ',
2086 ifte_check_boolean_expression(Other,Then,Else)),fail.
2087
2088 :- block evaluate_boolean_expression(-,?).
2089 %evaluate_boolean_expression(E,_) :- %print(evaluate_boolean_expression(E)),nl,
2090 % var(E),add_error(evaluate_boolean_expression,'Variable boolean expression:',E),fail.
2091 evaluate_boolean_expression(true,R) :- !, R=true.
2092 evaluate_boolean_expression(false,R) :- !, R=false.
2093 evaluate_boolean_expression(bool_not(BExpr1),Res) :- !,
2094 evaluate_boolean_expression(BExpr1,R1),
2095 negate(R1,Res).
2096 evaluate_boolean_expression(bool_and(BExpr1,BExpr2),Res) :- !,
2097 evaluate_boolean_expression(BExpr1,R1),
2098 cond_evalf_boolean_expression(R1,BExpr2,Res).
2099 evaluate_boolean_expression(bool_or(BExpr1,BExpr2),Res) :- !,
2100 evaluate_boolean_expression(BExpr1,R1),
2101 cond_evalt_boolean_expression(R1,BExpr2,Res).
2102 % when(ground(R1),
2103 % (R1=true -> Res = true
2104 % ; evaluate_boolean_expression(BExpr2,Res))).
2105 evaluate_boolean_expression('<'(Arg1,Arg2),Res) :- !,
2106 evaluate_int_argument(Arg1,EX),evaluate_int_argument(Arg2,EY),safe_less_than(EX,EY,Res).
2107 evaluate_boolean_expression('>'(Arg1,Arg2),Res) :- !,
2108 evaluate_int_argument(Arg1,EX),evaluate_int_argument(Arg2,EY),safe_less_than(EY,EX,Res).
2109 evaluate_boolean_expression('<='(Arg1,Arg2),Res) :- !,
2110 evaluate_int_argument(Arg1,EX),evaluate_int_argument(Arg2,EY),safe_less_than_equal(EX,EY,Res).
2111 evaluate_boolean_expression('>='(Arg1,Arg2),Res) :- !,
2112 evaluate_int_argument(Arg1,EX),evaluate_int_argument(Arg2,EY),safe_less_than_equal(EY,EX,Res).
2113 evaluate_boolean_expression(ifte(Test,Then,Else,_,_,_),R) :- !,
2114 evaluate_boolean_expression(Test,TestRes),
2115 ifte_eval_boolean_expression(TestRes,Then,Else,R).
2116 evaluate_boolean_expression(head(X),R) :- !, force_evaluate_argument(X,EX),head_list(EX,HResult),
2117 evaluate_boolean_expression(HResult,R).
2118 evaluate_boolean_expression(agent_call(Span,F,Par),R) :- !, /* in this context we need the result of the function call */
2119 unfold_function_call_once(F,Par,Body,Span),
2120 %when(nonvar(Body),
2121 evaluate_boolean_expression(Body,R).
2122 evaluate_boolean_expression(prolog_constraint(C),Res) :- !, %% print(prolog_constraint(C)),nl,
2123 (call(C) -> Res = true ; Res = false).
2124 evaluate_boolean_expression(null(Arg1),Res) :- !, force_evaluate_argument(Arg1,EX), is_null_list(EX,Res).
2125 evaluate_boolean_expression(empty(Arg1),Res) :- !, force_evaluate_argument(Arg1,EX), is_empty_set(EX,Res).
2126 evaluate_boolean_expression(BExpr,Res) :-
2127 bool_binary_op(BExpr,Arg1,Arg2,EX,EY,Call), !, % print(binop(BExpr,Arg1,Arg2)),nl,
2128 force_evaluate_argument(Arg1,EX),
2129 force_evaluate_argument(Arg2,EY), %print(ebe(Call)),nl,
2130 when((ground(EX),ground(EY)),
2131 (Call -> Res = true ; Res = false)).
2132 evaluate_boolean_expression('member'(Arg1,Arg2),Res) :- !, % after bool_binary_op: there is a special rule for member there
2133 force_evaluate_argument(Arg1,EX),
2134 force_evaluate_argument_for_member_check(Arg2,EY), %print(lazy_member(EX,EY)),nl,
2135 when(ground(EX),
2136 (ground(EY) -> (is_member_set(EX,EY) -> Res = true ; Res = false)
2137 ; /* exploring lazy expression */ force_evaluate_argument(EY,REY),(is_member_set(EX,REY) -> Res = true ; Res = false))).
2138 evaluate_boolean_expression(builtin_call(X),Res) :- !, evaluate_boolean_expression(X,Res).
2139 evaluate_boolean_expression(X,_R) :-
2140 add_error(haskell_csp,'Not a boolean expression: ',X),
2141 fail.
2142
2143
2144 :- block negate(-,?).
2145 negate(true,false).
2146 negate(false,true).
2147
2148 :- block cond_evalt_boolean_expression(-,?,?).
2149 cond_evalt_boolean_expression(true,_,true).
2150 cond_evalt_boolean_expression(false,BExpr2,Res) :- evaluate_boolean_expression(BExpr2,Res).
2151
2152 :- block cond_evalf_boolean_expression(-,?,?).
2153 cond_evalf_boolean_expression(false,_,false).
2154 cond_evalf_boolean_expression(true,BExpr2,Res) :- evaluate_boolean_expression(BExpr2,Res).
2155
2156 :- block ifte_eval_boolean_expression(-,?,?,?).
2157 ifte_eval_boolean_expression(true,Then,_,Res) :- !, evaluate_boolean_expression(Then,Res).
2158 ifte_eval_boolean_expression(false,_,Else,Res) :- !, evaluate_boolean_expression(Else,Res).
2159 ifte_eval_boolean_expression(Other,Then,Else,Res) :- /* evaluate_boolean_expression/2 will catch the error if there
2160 is no boolean expression test, thus internal_error must be generated for this clause. */
2161 add_internal_error('Not a boolean inside if-then-else boolean expression test: ',
2162 ifte_eval_boolean_expression(Other,Then,Else,Res)),fail.
2163
2164 bool_binary_int_op('<'(X,Y),X,Y,EX,EY,'<'(EX,EY)).
2165 bool_binary_int_op('>'(X,Y),X,Y,EX,EY,'>'(EX,EY)).
2166 bool_binary_int_op('>='(X,Y),X,Y,EX,EY,'>='(EX,EY)).
2167 bool_binary_int_op('<='(X,Y),X,Y,EX,EY,'=<'(EX,EY)).
2168
2169 relational_binary_op('<'(X,Y),X,Y,EX,EY,safe_less_than(EX,EY)).
2170 relational_binary_op('>'(X,Y),X,Y,EX,EY,safe_less_than(EY,EX)).
2171 relational_binary_op('<='(X,Y),X,Y,EX,EY,safe_less_than_equal(EX,EY)).
2172 relational_binary_op('>='(X,Y),X,Y,EX,EY,safe_less_than_equal(EY,EX)).
2173
2174 bool_binary_op('elem'(X,Y),X,Y,EX,EY,is_elem_list(EX,EY)).
2175 %bool_binary_op('member'(X,Y),X,Y,EX,EY,is_member_set(EX,EY)) :- (X=setValue(_) -> false;true).
2176 bool_binary_op('member'(X,'Set'(Y)),X,Y,EX,EY,is_subset_of(EX,EY)) :-
2177 (X\=setValue(_) -> false; \+ground(X) -> false; true).
2178 bool_binary_op('=='(X,Y),X,Y,EX,EY,equal_element(EX,EY)).
2179 bool_binary_op('!='(X,Y),X,Y,EX,EY,not_equal_element(EX,EY)).
2180
2181 bool_binary_op_symbolic('member'(X,Y),X,Y,EX,EY,is_member_set(EX,EY)). % dealt with separately
2182
2183 unary_op(null(X),X,EX,is_null_list(EX)).
2184 unary_op(empty(X),X,EX,is_empty_set(EX,true)).
2185
2186 is_boolean_expression(true).
2187 is_boolean_expression(false).
2188 is_boolean_expression(bool_not(_)).
2189 is_boolean_expression(bool_and(_,_)).
2190 is_boolean_expression(bool_or(_,_)).
2191 is_boolean_expression(X) :-
2192 (unary_op(X,_,_,_) ; bool_binary_op(X,_,_,_,_,_) ; bool_binary_op_symbolic(X,_,_,_,_,_) ; bool_binary_int_op(X,_,_,_,_,_)).
2193
2194
2195 /* ------------------------------------- */
2196 /* SEQUENCES */
2197 /* ------------------------------------- */
2198
2199 :- use_module(probcspsrc(csp_sequences)).
2200
2201 /* ------------------------------------- */
2202 /* VALUE EXPRESSIONS */
2203 /* ------------------------------------- */
2204
2205 :- type channelio +--> (atomic ; dotTuple(list(atomic))).
2206
2207 :- type channel_set +--> (setValue(list(channelio)) ; closure(list(channelio))).
2208
2209 :- type cspm_expr +--> (type(cspm_arith_expr) ; type(channel_set) ; atomic ; agent_call(ground,nonvar,list(any)) ).
2210
2211 :- type cspm_arith_expr +--> (int(integer) ;
2212 '+'(cspm_arith_expr,cspm_arith_expr) ;
2213 '-'(cspm_arith_expr,cspm_arith_expr) ;
2214 '*'(cspm_arith_expr,cspm_arith_expr) ;
2215 '/'(cspm_arith_expr,cspm_arith_expr) ;
2216 '%'(cspm_arith_expr,cspm_arith_expr) ).
2217
2218 % forcing arguments in the context of a member check; will be used as second arg to is_member_set
2219 % This means that certain things do not need to be computed (Union for example)
2220 :- block force_evaluate_argument_for_member_check(-,?).
2221 force_evaluate_argument_for_member_check(agent_call(Span,F,Par),R) :- !,
2222 %print(unfold(F,Par,Body)),nl,
2223 unfold_function_call_once(F,Par,Body,Span),
2224 force_evaluate_argument_for_member_check(Body,R).
2225 % keep the following symbolic:
2226 force_evaluate_argument_for_member_check(setExp(rangeEnum(T),G),R) :- nonvar(T),T=[H|TT],TT==[], var(H), !,
2227 % if the tuples T have more than one element, we currently cannot check membership symbolically
2228 R=setExp(rangeEnum(T),G). % TO DO expand for rangeClosed,...
2229 force_evaluate_argument_for_member_check('Union'(L),R) :- !,
2230 force_evaluate_argument_for_member_check_into_list(L,LL), %print(evalUnion(L,LL)),nl,
2231 R='Union'(LL).
2232 force_evaluate_argument_for_member_check('Inter'(L),R) :- !,
2233 force_evaluate_argument_for_member_check_into_list(L,LL), R='Inter'(LL).
2234 force_evaluate_argument_for_member_check('Seq'(L),R) :- !, R='Seq'(L).
2235
2236 force_evaluate_argument_for_member_check(X,EX) :- force_evaluate_argument(X,EX).
2237
2238 % force evaluating a set into a list of elements; do not worry about checking duplicates in list
2239 :- block force_evaluate_argument_for_member_check_into_list(-,?).
2240 %force_evaluate_argument_for_member_check_into_list(A,R) :- print(force_evaluate_argument_for_member_check_into_list(A,R)),nl,fail.
2241 force_evaluate_argument_for_member_check_into_list(agent_call(Span,F,Par),R) :- !,
2242 /* in this context we need the result of the function call */
2243 unfold_function_call_once(F,Par,Body,Span),
2244 force_evaluate_argument_for_member_check_into_list(Body,R).
2245 force_evaluate_argument_for_member_check_into_list(setExp(rangeEnum(L)),R) :- !,
2246 force_evaluate_list_for_member_check(L,LL),R=setExp(rangeEnum(LL)).
2247 force_evaluate_argument_for_member_check_into_list(X,EX) :- force_evaluate_argument(X,EX).
2248
2249 :- block force_evaluate_list_for_member_check(-,?).
2250 force_evaluate_list_for_member_check([],R) :- !,R=[].
2251 force_evaluate_list_for_member_check([H|T],R) :- !, R=[EH|ET],
2252 force_evaluate_argument_for_member_check(H,EH),
2253 force_evaluate_list_for_member_check(T,ET).
2254 force_evaluate_list_for_member_check(X,R) :-
2255 add_internal_error('Iternal Error: Could not evaluate list: ',force_evaluate_list_for_member_check(X,R)),R=X.
2256
2257 %%%%%%%%%%%%%%%%%%%%%%%%%%%%% UNIT TESTS FOR force_evaluate_argument/2, evaluate_argument/2 and evaluate_expression/2 %%%%%%%%%%%%%%%%%%%%%%%
2258 :- assert_must_succeed((haskell_csp: force_evaluate_argument(listFromTo(1,3),R), R == list([int(1),int(2),int(3)]))).
2259 :- assert_must_succeed((haskell_csp: evaluate_argument(listFromTo(1,3),R), R == list([int(1),int(2),int(3)]))).
2260 :- assert_must_succeed((haskell_csp: evaluate_argument(listFrom(1),R), R == listFrom(1))).
2261 :- assert_must_succeed((haskell_csp: evaluate_argument(setFromTo(1,3),R), R == setFromTo(1,3))).
2262 :- assert_must_succeed((haskell_csp: evaluate_argument(list([int(1),int(2)]),R), R == list([int(1),int(2)]))).
2263 :- assert_must_succeed((haskell_csp: force_evaluate_argument(listPat([int(1),int(2)]),R), R == list([int(1),int(2)]))).
2264 :- assert_must_succeed((haskell_csp: evaluate_argument(ifte('<='(int(3),int(20)),'>='(int(2),int(1)),'<='(int(3),int(1)),span,span,span),R) ,R == true)).
2265 :- assert_must_succeed((
2266 haskell_csp: evaluate_argument(ifte('<='(int(3),int(2)),'>='(int(2),int(1)),'<='(int(3),int(1)),span,span,span),R), R ==false)).
2267 :- assert_must_succeed((haskell_csp: evaluate_argument(ifte('<='(int(3),int(2)),int(1),int(2),span,span,span),R), R == int(2))).
2268 :- assert_must_succeed((haskell_csp: evaluate_argument(dataType('FRUIT'),R), R == dataType('FRUIT'))).
2269 :- assert_must_succeed((haskell_csp: evaluate_argument(concat(listExp(rangeEnum([listFromTo(1,3),listExp(rangeEnum([int(4)]))]))),R),
2270 R == list([int(1),int(2),int(3),int(4)]))).
2271 :- assert_must_succeed((haskell_csp: evaluate_argument(listPat([int(1),int(2)]),R), R == list([int(1),int(2)]))).
2272 :- assert_must_succeed((haskell_csp: evaluate_argument(tuplePat([int(1),int(2)]),R), R == na_tuple([int(1),int(2)]))).
2273 :- assert_must_succeed((haskell_csp: evaluate_expression(setExp(rangeEnum([int(1),int(2)])),R), R == setValue([int(1),int(2)]))).
2274 :- assert_must_succeed((haskell_csp: evaluate_expression(setFromTo(1,3),R), R == setValue([int(1),int(2),int(3)]))).
2275 :- assert_must_succeed((haskell_csp: evaluate_expression(stop(src),R), R == 'Typed expression is a process construct.')).
2276 :- assert_must_succeed((haskell_csp: evaluate_expression(left,R), R == 'Typed expression is a channel name.')).
2277 :- assert_must_succeed((haskell_csp: evaluate_expression('Msg1',R), R == setValue(['A','B']))).
2278 :- assert_must_succeed((haskell_csp: evaluate_expression('Msg1',R), R == setValue(['A','B']))).
2279 :- assert_must_succeed((haskell_csp: evaluate_expression(builtin_call(set(listExp(rangeEnum([int(1),int(1)])))),R), R == setValue([int(1)]))).
2280 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2281
2282 evaluate_expression(X,R) :- var(X),!,
2283 add_internal_error('Internal Error: Variable expression to evaluate: ',evaluate_expression(X,R)),
2284 fail.
2285 evaluate_expression('Events',R) :- !,
2286 findall(Channel,is_a_channel_name(Channel),CL),
2287 evaluate_list(CL,CLL), closure_expand(CLL,R).
2288 evaluate_expression(closure(X),R) :- !,
2289 evaluate_list(X,XL), closure_expand(XL,R).
2290 evaluate_expression(builtin_call(X),R) :- !, evaluate_expression(X,R).
2291 evaluate_expression(setExp(X),R) :- !, evaluate_set_expression(X,EX),expand_symbolic_set(EX,R,evaluate_expression).
2292 evaluate_expression(setFromTo(Low,Up),R) :- !, expand_symbolic_set(setFromTo(Low,Up),R,evaluate_expression).
2293 evaluate_expression(val_of(X,Src),R) :- !, evaluate_argument2(val_of(X,Src),R).
2294 ?evaluate_expression(DT,R) :- is_a_datatype(DT,_),!,
2295 expand_symbolic_set(dataType(DT),R,eval).
2296 ?evaluate_expression(Proc,R) :- definite_cspm_process_expression(Proc),!, R='Typed expression is a process construct.'.
2297 evaluate_expression(Ch,R) :- is_a_channel_name(Ch),!, R='Typed expression is a channel name.'.
2298 evaluate_expression(E,R) :- force_evaluate_argument(E,R).
2299
2300 :- block force_evaluate_argument(-,?).
2301 force_evaluate_argument(Num,R) :- number(Num),!,R=int(Num).
2302 force_evaluate_argument(agent_call(Span,F,Par),R) :- !, /* in this context we need the result of the function call */
2303 unfold_function_call_once(F,Par,Body,Span),
2304 force_evaluate_argument(Body,R).
2305 force_evaluate_argument(setExp(RangeExpr,Generators),R) :- !,
2306 expand_set_comprehension(RangeExpr,Generators,R).
2307 %force_evaluate_argument(comprehensionGenerator(Var,Set),R) :- !,
2308 % R = comprehensionGenerator(Var,ESet),
2309 % force_evaluate_argument(Set,ESet).
2310 force_evaluate_argument(ifte(Test,Then,Else,_S1,_S2,_S3),R) :- !,
2311 evaluate_boolean_expression(Test,TestRes), % print(force_ifte(Test,TestRes)),nl,
2312 ifte_force_evaluate_argument(TestRes,Then,Else,R).
2313 force_evaluate_argument(list(X),R) :- !, %print(eval_list(X)),nl,
2314 force_evaluate_list(X,EX), % use force_evaluate_list_skel ??; perf. problem in misusing_lists
2315 R=list(EX).
2316 force_evaluate_argument(listPat(X),R) :- !, %print(eval_list(X)),nl,
2317 force_evaluate_list(X,EX), % use force_evaluate_list_skel ??; perf. problem in misusing_lists
2318 R=list(EX).
2319 force_evaluate_argument(listFromTo(X,Y),Res) :- !, expand_sequence(listFromTo(X,Y),Res).
2320 force_evaluate_argument(listExp(S),ERes) :- !, evaluate_list_expression(S,Res), expand_sequence(Res,ERes).
2321 %force_evaluate_argument(setValue(X),R) :- !, force_evaluate_set(X,R), print(fes(X,R)),nl.
2322 % Maybe we should ensure that setValues are always force evaluated: we only need to
2323 % take care when using set operations for replicated operators
2324 force_evaluate_argument(Destr,Result) :- destructor(Destr),!, % we may need to further evaluate result
2325 evaluate_argument2(Destr,EX), % do ordinary evaluation
2326 force_evaluate_argument(EX,Result).
2327 force_evaluate_argument(E,R) :- evaluate_argument2(E,R). /* could there be lazy constructs lurking deep inside E ??? */
2328
2329 destructor(head(_)).
2330 destructor(na_tuple_projection(_,_,_)).
2331 destructor(tuple_projection(_,_,_)).
2332 %destructor(record(_,_)).
2333 % records ?
2334
2335
2336 :- block ifte_force_evaluate_argument(-,?,?,?).
2337 ifte_force_evaluate_argument(true,Then,_,Res) :- !, force_evaluate_argument(Then,Res).
2338 ifte_force_evaluate_argument(false,_,Else,Res) :- !, force_evaluate_argument(Else,Res).
2339 /* See comment for the error clause of the ifte_evaluate_argument/4 predicate. Same argument as below
2340 for assuming the error clause as caused by internal call only. */
2341 ifte_force_evaluate_argument(Other,Then,Else,Res) :-
2342 add_internal_error('Internal Error: Not a boolean inside if-then-else test: ',
2343 ifte_force_evaluate_argument(Other,Then,Else,Res) ),fail.
2344
2345 :- block ifte_evaluate_argument(-,?,?,?).
2346 ifte_evaluate_argument(true,Then,_,Res) :- !, evaluate_argument(Then,Res).
2347 ifte_evaluate_argument(false,_,Else,Res) :- !, evaluate_argument(Else,Res).
2348 /* evaluate_boolean_expression/2 predicate is called before ifte_evaluate_argument/4.
2349 evaluate_boolean_expression/2 provides as result either true or false, that's why only internal call can
2350 raise error for this predicate. */
2351 ifte_evaluate_argument(Other,Then,Else,Res) :-
2352 add_internal_error('Internal Error: Not a boolean inside if-then-else test: ',
2353 ifte_evaluate_argument(Other,Then,Else,Res)),fail.
2354
2355 %evaluate_argument(E,R) :- print(evaluate_argument(E,R)),nl,
2356 %(nonvar(R) -> true ; when(nonvar(R),(print(inst_eval(E,R)),nl,trace))), evaluate_argument1(E,R).
2357 :- block evaluate_argument(-,?).
2358 evaluate_argument(Expr,Res) :- evaluate_argument2(Expr,Res).
2359
2360 evaluate_argument2(ifte(Test,Then,Else,_S1,_S2,_S3),R) :- !,
2361 evaluate_boolean_expression(Test,TestRes), %print(ifte(Test,TestRes)),nl,
2362 ifte_evaluate_argument(TestRes,Then,Else,R).
2363 % when(ground(TestRes),(TestRes=true -> evaluate_argument(Then,R) ; evaluate_argument(Else,R))).
2364 evaluate_argument2(int(X),R) :- !,R=int(X).
2365 % case should be added because of the clpfd-library
2366 evaluate_argument2(Num,R) :- number(Num),!,R=int(Num).
2367 evaluate_argument2(true,R) :- !,R=true.
2368 evaluate_argument2(false,R) :- !,R=false.
2369 evaluate_argument2(negate(X),Result) :- !, Result = int(Res),
2370 evaluate_int_argument(X,EX),
2371 safe_is(Res,-(EX)).
2372 evaluate_argument2('+'(X,Y),Result) :- !, Result = int(Res),
2373 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2374 safe_is(Res,EX+EY).
2375 evaluate_argument2('-'(X,Y),Result) :- !, Result = int(Res),
2376 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2377 safe_is(Res,EX-EY).
2378 evaluate_argument2('*'(X,Y),Result) :- !, Result = int(Res),
2379 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2380 safe_is(Res,EX * EY).
2381 evaluate_argument2('/'(X,Y),Result) :- !, Result = int(Res),
2382 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2383 safe_is(Res,EX // EY).
2384 evaluate_argument2('%'(X,Y),Result) :- !, Result = int(Res),
2385 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2386 safe_is(Res,EX mod EY).
2387 evaluate_argument2(length(X),Result) :- !, force_evaluate_argument(X,EX),length_list(EX,Result).
2388 evaluate_argument2('#'(X),Result) :- !, force_evaluate_argument(X,EX),length_list(EX,Result).
2389 evaluate_argument2(head(X),Result) :- !, force_evaluate_argument(X,EX),
2390 head_list(EX,Result).
2391 evaluate_argument2(tail(X),Result) :- !, force_evaluate_argument(X,EX),tail_list(EX,Result).
2392 evaluate_argument2('^'(X,Y),Result) :- !,
2393 force_evaluate_argument(X,EX),force_evaluate_argument(Y,EY),
2394 %print('^'(X,EX,Y,EY)),nl,
2395 append_list(EX,EY,Result). %, print(append_list(EX,EY,Result)),nl.
2396 evaluate_argument2(concat(X),Result) :- !, force_evaluate_argument(X,EX),
2397 concat_lists(EX,Result).
2398 evaluate_argument2(listFromTo(X,Y),Res) :- !,
2399 %evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2400 expand_sequence(listFromTo(X,Y),Res).
2401 evaluate_argument2(listFrom(X),Res) :- !, Res = listFrom(X). % already evaluated
2402 evaluate_argument2(listExp(S),Res) :- !, evaluate_list_expression(S,Res).
2403 evaluate_argument2(listExp(RangeExpr,Generators),R) :- !, %print(listExp(Generators,RangeExpr)),nl,
2404 expand_listcomprehension(RangeExpr,Generators,R). %, print(res(R)),nl.
2405 %evaluate_argument2(listComp(Generators,Tuples),R) :- !, %force_evaluate_list(Generators,EGen),
2406 % expand_sequence(listComp(Generators,Tuples),R).
2407 evaluate_argument2(set(X),Res) :- !, evaluate_argument2(seq_to_set(X),Res).
2408 evaluate_argument2(seq(X),Res) :- !, evaluate_argument2(set_to_seq(X),Res).
2409 evaluate_argument2(set_to_seq(X),Res) :- !,
2410 force_evaluate_argument(X,EX),
2411 convert_set_to_seq(EX,Res).
2412 evaluate_argument2(seq_to_set(X),Res) :- !,
2413 force_evaluate_argument(X,EX),
2414 convert_seq_to_set(EX,Res).
2415 evaluate_argument2(setFromTo(X,Y),Res) :- !, Res = setFromTo(X,Y). % already computed set expression
2416 evaluate_argument2(setExp(S),Res) :- !, evaluate_set_expression(S,Res).
2417 evaluate_argument2(setExp(RangeExpr,Generators),R) :- !, %print(setExp(Generators,RangeExpr)),nl,
2418 expand_set_comprehension(RangeExpr,Generators,R).
2419 evaluate_argument2(setValue(X),R) :- !, evaluate_argument2(X,EX), R=setValue(EX).
2420 evaluate_argument2(singleSetPatValue(X,Span),R) :- !, force_evaluate_argument(X,EX),
2421 %print(singleSetPatValue(X,EX,R)),nl,
2422 singleSetElement(EX,R,Span).
2423 evaluate_argument2('Seq'(X),R) :- !, evaluate_argument(X,EX),R='Seq'(EX).
2424 evaluate_argument2(intType,R) :- !, R=intType.
2425 evaluate_argument2(boolType,R) :- !, R=boolType.
2426 %evaluate_argument2(setEnum(X),R) :- !, evaluate_list(X,XL), evaluate_set(XL,R).
2427
2428 evaluate_argument2(closureComp(Generators,Tuples),R) :- !,
2429 % print(closureComp(Generators,Tuples)),nl,
2430 expand_symbolic_set(setExp(rangeEnum(Tuples),Generators),setValue(List),evaluate_argument_closureComp),
2431 % print(closureset(List)),nl,
2432 evaluate_argument2(closure(List),R). %print(doneclosureComp(R)),nl.
2433 evaluate_argument2(closure(X),R) :- !, %print(eval(closure(X))),nl,
2434 evaluate_list(X,XL), % print(evaluate_closure(XL,R)),nl,
2435 evaluate_closure(XL,R).
2436 %expand_channel_pattern_expression(closure(X),R,no_loc_info_available).
2437 evaluate_argument2('Events',R) :- !,
2438 findall(Channel,is_a_channel_name(Channel),CL),
2439 evaluate_argument2(closure(CL),R).
2440 evaluate_argument2(union(X,Y),Result) :- !, force_evaluate_argument(X,EX), force_evaluate_argument(Y,EY),
2441 union_set(EX,EY,Result).
2442 evaluate_argument2('Union'(X),Result) :- !, force_evaluate_argument(X,EX),
2443 big_union(EX,Result).
2444 evaluate_argument2('Inter'(X),Result) :- !, force_evaluate_argument(X,EX),
2445 big_inter(EX,Result).
2446 evaluate_argument2(diff(X,Y),Result) :- !, force_evaluate_argument(X,EX), force_evaluate_argument(Y,EY),
2447 %print(diff_set(X,EX,Y,EY)),nl,
2448 diff_set(EX,EY,Result).
2449 evaluate_argument2(inter(X,Y),Result) :- !, force_evaluate_argument(X,EX), force_evaluate_argument(Y,EY),
2450 inter_set(EX,EY,Result).
2451 evaluate_argument2(card(X),Result) :- !, force_evaluate_argument(X,EX),
2452 cardinality(EX,Result).
2453 evaluate_argument2('Set'(X),Result) :- !, %print(subsets(X)),nl,
2454 evaluate_argument(X,EX),
2455 %print(calling_subsets(EX)),nl,
2456 subsets(EX,Result). %, print(subset_result(Result)),nl.
2457 evaluate_argument2(agent_call(Span,F,Par),R) :- !,
2458 evaluate_agent_call(F,Par,R,Span).
2459 evaluate_argument2(agent_call_curry(F,Par),R) :- !,
2460 Span=no_loc_info_available,
2461 unfold_function_call_curry_once(F,Par,Value,Span),
2462 evaluate_argument(Value,R).
2463 evaluate_argument2(val_of(VAR,Span),R) :- !, /* this can only happen inside channel type expressions;
2464 other val_of's are compiled away by haskell_csp_analyzer */
2465 unfold_function_call_once(VAR,[],Body,Span),
2466 evaluate_argument(Body,R).
2467 evaluate_argument2([],R) :- !,R=[].
2468 evaluate_argument2([H|T],R) :- !,R=[H|T]. /* list of channel outputs */
2469 evaluate_argument2(builtin_call(X),R) :- !, evaluate_argument(X,R).
2470 evaluate_argument2(dotTuple(X),R) :- !, evaluate_dot_tuple(X,R).
2471 evaluate_argument2(dotTupleType(TupleArgs),R) :- !,
2472 evaluate_list(TupleArgs,ETupleArgs), R = dotTupleType(ETupleArgs).
2473 evaluate_argument2(dotpat(X),R) :- !, evaluate_dot_tuple(X,R).
2474 evaluate_argument2(tuple(F),R) :- !, R=tuple(F).
2475 evaluate_argument2(alsoPat(X,Y),R) :- !,
2476 evaluate_argument2(X,EX),
2477 evaluate_argument2(Y,EY),
2478 R=alsoPat(EX,EY).
2479 evaluate_argument2(lambda(A,B),R) :- !, %print(eval(lambda(A,B))),nl,
2480 R=lambda(A,B),
2481 (ground(A) -> true ;
2482 mynumbervars(A)). /* numbervars to avoid nonvar states for ProB (slows down hashing,...) */
2483 evaluate_argument2(tuplePat(TupleArgs),R) :- !, /* a non-associative tuple */
2484 R = na_tuple(EA),force_evaluate_list(TupleArgs,EA).
2485 evaluate_argument2(tupleExp(TupleArgs),R) :- !, /* a non-associative tuple; same as tuplePat but not in pattern position */
2486 R = na_tuple(EA),force_evaluate_list(TupleArgs,EA).
2487 evaluate_argument2(typeTuple(TupleArgs),R) :- !,
2488 evaluate_list(TupleArgs,ETupleArgs), R = typeTuple(ETupleArgs).
2489 evaluate_argument2(na_tuple(F),R) :- !, R=na_tuple(F). /* non-associative tuple */
2490 evaluate_argument2(na_tuple_projection(Nr,Tuple,Span),R) :- !,
2491 evaluate_int_argument(Nr,ENr,Span),
2492 force_evaluate_argument(Tuple,ETuple),
2493 na_tuple_projection(ENr,ETuple,R,Span).
2494 evaluate_argument2(list_projection(Nr,Len,List,Span),R) :- !,
2495 evaluate_int_argument(Nr,ENr,Span),
2496 evaluate_int_argument(Len,ELen,Span),
2497 force_evaluate_argument(List,EList),
2498 list_projection(ENr,ELen,EList,R,Span).
2499 evaluate_argument2(tuple_projection(Nr,Tuple,Span),R) :- !,
2500 evaluate_int_argument(Nr,ENr,Span),
2501 force_evaluate_argument(Tuple,ETuple),
2502 tuple_projection(ENr,ETuple,R,Span).
2503 evaluate_argument2(record(C,F),R) :- !, R=record(C,F).
2504 evaluate_argument2(list(X),R) :- !, %print(eval_list(X)),nl,
2505 %evaluate_list(X,EX),
2506 R=list(X). % TO DO: check if we also need listPat
2507 evaluate_argument2(listPat(X),R) :- !,
2508 evaluate_list(X,EX), R=list(EX).
2509 evaluate_argument2(rename(X,Y),R) :- !,
2510 evaluate_rename_channel_expression(X,RX), /* should we evaluate ??? */
2511 evaluate_rename_channel_expression(Y,RY),
2512 R=rename(RX,RY).
2513 evaluate_argument2(link(X,Y),R) :- !,
2514 evaluate_rename_channel_expression(X,RX), /* should we evaluate ??? */
2515 evaluate_rename_channel_expression(Y,RY),
2516 R=link(RX,RY).
2517 evaluate_argument2(dataType(DT),R) :- !, R=dataType(DT).
2518 evaluate_argument2(Channel,R) :-
2519 atomic(Channel),is_a_channel_name(Channel),!,R=tuple([Channel]).
2520 evaluate_argument2(DT,R) :- name_type(DT,DT_Def), !, R=DT_Def.
2521 evaluate_argument2(DT,R) :- dataTypeDef(DT,_), !, R=dataType(DT).
2522 evaluate_argument2(DT,R) :- subTypeDef(DT,_), !, R=dataType(DT).
2523 evaluate_argument2(X,R) :- valid_constant(X),!,R=X.
2524 evaluate_argument2(X,R) :- agent_functor(X,_),!,R=X. /* when a function name is passed */
2525 evaluate_argument2(X,R) :-
2526 is_csp_constructor(X),!,R=X. /* FDR does not allow this as a valid value; but can be fed into closure */
2527 evaluate_argument2(X,R) :-
2528 (undefined_process_construct(X) ->
2529 ? (is_boolean_expression(X) -> evaluate_boolean_expression(X,R)
2530 /* we have a boolean value; we could also decide not to evaluate the argument and put R=X*/
2531 ; add_error(evaluate_argument2,'Cannot evaluate expression: ',X), R=X
2532 )
2533 ; R=X /* we have a process description which is simply kept as is */
2534 ).
2535
2536 % setExp(.); performs forced evaluation of set elements
2537 evaluate_set_expression(rangeEnum(List),Res) :- !, %evaluate_list(List,XL),
2538 force_evaluate_set(List,Res).%evaluate_set(List,Res,evaluate_argument).
2539 evaluate_set_expression(rangeClosed(X,Y),Res) :- !,
2540 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2541 ((number(X),number(Y),X>Y) -> Res= setValue([]) ; Res = setFromTo(EX,EY)).
2542 evaluate_set_expression(rangeOpen(X),Res) :- !,Res = setFrom(EX),
2543 evaluate_int_argument(X,EX).
2544 evaluate_set_expression(A,Res) :-
2545 add_internal_error('Internal Error: Unknown setExp: ',evaluate_set_expression(A,Res)),Res=[].
2546
2547 % listExp(.)
2548 evaluate_list_expression(rangeEnum(List),Res) :- !, Res=list(LR), evaluate_list(List,LR).
2549 evaluate_list_expression(rangeClosed(X,Y),Res) :- !, % print(evaluate_rangeClosed(X,Y)),nl,
2550 evaluate_int_argument(X,EX),evaluate_int_argument(Y,EY),
2551 ((number(X),number(Y),X>Y) -> Res= list([]) ; Res = listFromTo(EX,EY)).
2552 evaluate_list_expression(rangeOpen(X),Res) :- !,Res = listFrom(EX),
2553 evaluate_int_argument(X,EX).
2554 evaluate_list_expression(A,Res) :- /* CSP-M Parser cannot generate list expression,
2555 which is not of the type rangeEnum/1, rangeClosed/2, rangeOpen/1.
2556 That's why we can assume that in this case we have internal error. */
2557 add_internal_error('Internal Error: Unknown listExp: ',evaluate_list_expression(A,Res)),Res=[].
2558
2559
2560
2561 evaluate_function_name(F,EF) :-
2562 (atomic(F) -> EF=F ; force_evaluate_argument(F,EF)).
2563
2564 evaluate_agent_call(F,Par,Res,Span) :- % print(eval_agent_call(F,Par)),nl,
2565 evaluate_function_name(F,EF),evaluate_agent_call2(EF,Par,Res,Span).
2566
2567 evaluate_agent_call2(lambda(Args,Body),Par,R,Span) :- !,
2568 unfold_function_call_once2(lambda(Args,Body),Par,NBody,Span),
2569 evaluate_argument(NBody,R).
2570 evaluate_agent_call2(F,Par,R,Span) :- !,
2571 (atomic(F) -> true
2572 ; add_error(evaluate_argument,'Illegal function name for function application: ',agent_call(F,Par),Span),fail),
2573 X =.. [F|Par],
2574 ((is_csp_process(X) ; is_possible_csp_process(X)) % ATTENTION: the parameter in is_possible_csp_process/1 can be a function call, which can be missunderstood as process
2575 % a reimplementation of the is_possible_csp_process/1 is needed.
2576 -> R=agent_call(Span,F,Par) %%%, print(keeping(X)),nl)
2577 /* keep agent_calls lazily; they are processes. If we unfold then the variables will be
2578 propagated into the term; causing problems by instantiation (see e.g. Repeat(Proc) = Proc ; Repeat(Proc)) */
2579 /* QUESTION: what about is_possible_csp_process ??? */
2580 ; unfold_function_call_once2(F,Par,Body,Span),
2581 evaluate_argument(Body,R) /* TO DO: avoid re-checking when(nonvar ... for recursive calls ?*/
2582 % force_evaluate_argument(Body,R)
2583 ).
2584
2585 % --------------------------------------------------------
2586 % integer expressions
2587 % --------------------------------------------------------
2588
2589 % --------------------------------------------------------
2590
2591 evaluate_int_argument(A,Res) :- evaluate_int_argument(A,Res,no_loc_info_available).
2592
2593 :- block evaluate_int_argument(-,?,?).
2594
2595 evaluate_int_argument(int(X),R,_) :- !, R=X.
2596 evaluate_int_argument(agent_call(Span,F,Par),R,Span) :- !, /* in this context we need the result of the function call */
2597 unfold_function_call_once(F,Par,Body,Span),
2598 %print(unfolded(F,Par,Body)),nl,
2599 evaluate_int_argument(Body,R,Span).
2600 evaluate_int_argument(Expr,IntRes,Span) :-
2601 force_evaluate_argument(Expr,Res), % because we need an integer, i.e., agent_calls need to be unfolded
2602 (Res = int(IntRes) -> true
2603 ; (Res \= int(_), add_error(haskell_csp,'Expression does not evaluate to integer: ','='(Expr,Res),Span),
2604 fail)
2605 ).
2606
2607 :- block evaluate_list(-,?).
2608 evaluate_list([],R) :- !,R=[].
2609 evaluate_list([H|T],R) :- !, R=[EH|ET],evaluate_argument(H,EH), evaluate_list(T,ET).
2610 evaluate_list(X,R) :- add_internal_error('Internal Error: Could not evaluate: ',evaluate_list(X,R)),R=X.
2611
2612 :- block evaluate_type_list(-,?).
2613 evaluate_type_list([],R) :- !,R=[].
2614 evaluate_type_list([H|T],R) :- !, R=[EH|ET],
2615 translate_to_type_expr(H,TypeH),
2616 evaluate_argument(TypeH,EH),
2617 evaluate_type_list(T,ET).
2618 evaluate_type_list(X,R) :-
2619 add_internal_error('Internal Error: Could not evaluate: ',evaluate_type_list(X,R)),R=X.
2620
2621 translate_to_type_expr(tupleExp(TupleArgs),R) :- !,
2622 R = typeTuple(TupleArgsRes),
2623 compile_tuple_args(TupleArgs,TupleArgsRes).
2624 translate_to_type_expr(dotTuple(TupleArgs),R) :- !,
2625 R = dotTupleType(TupleArgsRes),
2626 compile_tuple_args(TupleArgs,TupleArgsRes).
2627 translate_to_type_expr(X,CX) :-
2628 haskell_csp_analyzer:compile_body(X,'compile_tuple_args',[],[],CX).
2629
2630 compile_tuple_args([],R) :- !,R=[].
2631 compile_tuple_args([H|T],R) :- !,
2632 R=[CH|RH],
2633 haskell_csp_analyzer:compile_body(H,'compile_tuple_args',[],[],CH),
2634 compile_tuple_args(T,RH).
2635
2636 % -----------------------------------------------------
2637
2638
2639
2640
2641 force_evaluate_list(L,_EL) :- %print(force_evaluate_list(L,_EL)),nl,
2642 var(L),!, add_error(haskell_csp,'Trying to force evaluation of variable: ',L),fail.
2643 force_evaluate_list([],R) :- !,R=[].
2644 force_evaluate_list([H|T],R) :- !, R=[EH|ET],
2645 force_evaluate_argument(H,EH), %force_evaluate_argument(H,EH),
2646 force_evaluate_list(T,ET).
2647 force_evaluate_list(X,R) :-
2648 add_internal_error('Could not (force) evaluate list: ',force_evaluate_list(X,R)),R=X.
2649
2650 unfold_function_call_curry_once(F,[],F,_Span).
2651 unfold_function_call_curry_once(F,[Args|As],Value,Span) :-
2652 unfold_function_call_once(F,Args,Val,Span),!,
2653 % Val is a lambda-function
2654 unfold_function_call_curry_once(Val,As,Value,Span).
2655
2656 unfold_function_call_once(F,Par,Res,Span) :-
2657 evaluate_function_name(F,EF),
2658 unfold_function_call_once2(EF,Par,Res,Span).
2659
2660 unfold_function_call_once2(lambda(Args,Body),Parameters,R,Span) :- !,
2661 %print(unfold_lambda(Args,Parameters,Body,R)),nl,
2662 % varnumbers(lambda(Args,Body),lambda(CA,CB)), /* lift the frozen parameter-vars back to real-variables; we should only lift variables in Args ! */
2663 lift(Args,CA,Body,CB),
2664 % print(lifted_lambda(CA,CB)),nl,
2665 evaluate_lambda_arguments(Parameters,CA,EvalParas),
2666 (CA=EvalParas -> R = CB
2667 ; add_error(cspm_trans,'Could not unify lambda args: ', lambda(CA,Parameters,body(Body)),Span),fail).
2668 unfold_function_call_once2(FunName,Parameters,R,Span) :- %print(unfold(FunName,Parameters)),nl,
2669 evaluate_agent_call_parameters(FunName,Parameters,EvalParas,Span),
2670 %%print(call_agent_compiled(FunName,Parameters,EX)),nl,
2671 call_agent_compiled(FunName,Parameters,EvalParas,R,Span).
2672
2673 :- block call_agent_compiled(-,?,?,?,?),call_agent_compiled(?,?,-,?,?).
2674 call_agent_compiled(FunCall,_,[],Res,Span) :- !, % no parameters
2675 call_agent_compiled2(FunCall,Res,Span).
2676 call_agent_compiled(FunName,_Parameters,EvalParas,Res,Span) :-
2677 EX =.. [FunName|EvalParas],
2678 (ground(EvalParas) -> call_agent_compiled2(EX,Res,Span)
2679 ; %print(not_ground_call(FunName,Parameters,EvalParas)),nl, %typechecker:debug_non_ground_term(EX),
2680 is_nonvar_list_skel(EvalParas,OK), % was when(ground(EX),...)
2681 call_agent_compiled1(EX,Res,OK,Span)
2682 ).
2683 :- block is_nonvar_list_skel(-,?).
2684 %is_nonvar_list_skel([],true). % clause not coverable, [] is always ground (see ground(EvalParas) -> .. in the body of last clause of call_agent_compiled/5)
2685 is_nonvar_list_skel([H|T],R) :- is_nonvar_list_skel(T,H,R).
2686 :- block is_nonvar_list_skel(-,?,?),is_nonvar_list_skel(?,-,?).
2687 is_nonvar_list_skel([],_,true).
2688 is_nonvar_list_skel([H|T],_,R) :- is_nonvar_list_skel(T,H,R).
2689
2690 :- block call_agent_compiled1(?,?,-,?).
2691 call_agent_compiled1(EX,Res,_,Span) :- call_agent_compiled2(EX,Res,Span).
2692
2693 call_agent_compiled2(EX,Res,Span) :-
2694 (agent_compiled(EX,Value,_SRCSPAN)
2695 -> %print(unfolded(Value,Res,EX)),nl,
2696 %(EX='OZS@__25'(_,_) -> trace ; true),
2697 Res=Value /* local cut imposes functional interpetation */
2698 ; functor(EX,F,N), functor(Skel,F,N),
2699 (is_defined_agent(Skel) -> add_cspm_error(cspm_trans,'No matching case for function call: ',EX,Span)
2700 ; add_cspm_error(cspm_trans,'Trying to apply undefined process/function: ',EX,Span)),
2701 fail
2702 ).
2703
2704 safe_is(X,Expr) :- when(ground(Expr), X is Expr).
2705
2706 add_cspm_error(Source,Msg,CSPE,Span) :-
2707 (translate_cspm_state(CSPE,Transl) -> true ; Transl=CSPE),
2708 add_error(Source,Msg,Transl,Span).
2709
2710 /* ------------------------------------- */
2711 /* Renaming related predicates */
2712 /* ------------------------------------- */
2713
2714
2715 :- assert_must_succeed((
2716 retractall(csp_full_type_constructor(_,_,_)),
2717 haskell_csp:rename_action(io([int(1)],left,unknown(test)),[rename(right,left),rename(left,mid)],Res),
2718 Res== io([int(1)],mid,unknown(test)) )).
2719 :- assert_must_succeed((
2720 retractall(csp_full_type_constructor(_,_,_)),
2721 haskell_csp:rename_action(io([int(1)],ack,unknown(test)),[rename(right,left),rename(left,mid)],Res),
2722 Res== io([int(1)],ack,unknown(test)) )).
2723 :- assert_must_succeed((
2724 retractall(csp_full_type_constructor(_,_,_)),
2725 haskell_csp:rename_action(io([int(1)],right,unknown(test)),[rename(ack,right),rename(right,dotTuple([mid,int(2)]))],Res),
2726 Res== io([int(2),int(1)],mid,unknown(test)) )).
2727 :- assert_must_succeed((
2728 retractall(csp_full_type_constructor(_,_,_)),
2729 haskell_csp:rename_action(io([int(1)],ack,unknown(test)),[rename(ack,left),rename(ack,right)],Res),
2730 Res== io([int(1)],left,unknown(test)) )).
2731 :- assert_must_succeed((
2732 retractall(csp_full_type_constructor(_,_,_)),
2733 haskell_csp:rename_action(io([int(1)],ack,unknown(test)),[rename(ack,left),rename(ack,right)],Res),
2734 Res== io([int(1)],right,unknown(test)) )).
2735 % :- assert_must_succeed((
2736 % haskell_csp:haskell_csp:rename_action(io([int(0)],gen,unknown(test)),
2737 % [rename(gen,gen1),rename(gen,dotTuple([gen2,int(1)])),
2738 % rename(dotTuple([gen,int(0)]),dotTuple([gen2,int(9),int(9)])),
2739 % rename(stop(no_loc_info_available),dotTuple([gen2,int(2)+int(3)]))],R),
2740 % R == io([int(1),int(0)],gen2,unknown(test)) )).
2741
2742 :- block rename_action(-,?,-).
2743 rename_action(tick(TS),_,tick(TS)).
2744 rename_action(tau(X),_,tau(X)).
2745 rename_action(io(V,Ch,Span),RenamePatternList,Res) :- Res=io(_,_,_),
2746 ? match_pattern_list(RenamePatternList,V,Ch,Span,Res,false).
2747
2748 force_rename_action(io(V,Ch,Span),RenamePatternList,Res) :- /* as above; but renaming must occur */
2749 match_pattern_list(RenamePatternList,V,Ch,Span,Res,true). % true: means MatchOccured: not allowed to not rename
2750
2751 %not_renamed(tick(_),_). % case cannot occur, functor_dif(AX,tick) is always called before the not_renamed/2 predicate
2752 not_renamed(tau(_X),_).
2753 not_renamed(io(V,Ch,_Span),RenamePatternList) :-
2754 not_covered_action(RenamePatternList,V,Ch).
2755
2756 not_covered_action([],_,_).
2757 not_covered_action([rename(ChPat,_NewCh)|T],V,Ch) :-
2758 (ChPat= tuple([Ch2|TPat2]) %dotTuple([Ch2|T2])
2759 -> (dif(Ch,Ch2) ; Ch=Ch2,no_match_list(TPat2,V))%,print(nca_dif(V,T2)),nl
2760 ; dif(Ch,ChPat)
2761 ), not_covered_action(T,V,Ch).
2762
2763 :- assert_must_succeed(( haskell_csp:no_match_list([int(1)],[int(2)]) )).
2764 :- assert_must_succeed(( haskell_csp:no_match_list([int(2)],[int(1),int(2)]) )).
2765 :- assert_must_fail(( haskell_csp:no_match_list([],[int(1),int(2)]) )).
2766 :- assert_must_fail(( haskell_csp:no_match_list([int(2),int(3)],[int(2),int(3)]) )).
2767 %% :- assert_must_fail(( haskell_csp:no_match_list([out(int(2)),out(int(3))],[int(2),int(3)]) )).
2768 :- assert_must_succeed(( haskell_csp:no_match_list(X,[int(2),int(1)]),
2769 X=[int(2),int(2)])).
2770
2771 % check if a rename pattern matches a value on a channel:
2772 no_match_list(RenPattern,ChValue) :- % print(no_match_list(A,B)),nl,
2773 l_match_pattern_value(RenPattern,ChValue,match_false).
2774
2775 % check if a value matches an entry in the ChannelPatternList
2776 match_list(ChannelPatternList,V,Ch,Span) :-
2777 match_pattern_list(ChannelPatternList,V,Ch,Span,true,true).
2778
2779 :- block match_pattern_value(-,?,?), match_pattern_value(?,-,?).
2780 match_pattern_value(record(C,PatArgs),record(VC,ValArgs),Res) :- !,
2781 match_record(C,PatArgs,VC,ValArgs,Res).
2782 match_pattern_value(tuple(L1),tuple(L2),Res) :- !,
2783 l_match_pattern_value(L1,L2,Res).
2784 match_pattern_value(X,tuple([H|Rest]),Res) :- !,(H=X -> Res = match_true(Rest); Res=match_false).
2785 match_pattern_value(X,dotTuple([H|Rest]),Res) :- !,(H=X -> Res = match_true(Rest); Res=match_false).
2786 match_pattern_value(X,record([X|Rest]),Res) :- !, Res = match_true(Rest).
2787 match_pattern_value(Pat,Val,Res) :-
2788 when(?=(Pat,Val),(unify_check(Pat,Val)
2789 -> Res=match_true([]) ; Res=match_false)).
2790
2791 unify_check(int(V1),I2) :- !,
2792 (I2=int(V2) -> V1=V2
2793 %; preference(use_clpfd_solver,true), number(I2) -> V1 = I2
2794 ; add_internal_error('Type error in unification of values: ',unify_check(int(V1),I2)),fail).
2795 unify_check(true,I2) :- !,
2796 (I2=true -> true ; I2=false -> fail
2797 ; add_internal_error('Type error in unification of values: ',unify_check(true,I2)),fail).
2798 unify_check(false,I2) :- !,
2799 (I2=false -> true ; I2=true -> fail
2800 ; add_internal_error('Type error in unification of values: ',unify_check(false,I2)),fail).
2801 unify_check(V,V).
2802
2803
2804
2805 :- block match_record(-,?,?,?,?), match_record(?,?,-,?,?).
2806 match_record(C1,_,C2,_,Res) :- C1\=C2,!, Res=match_false.
2807 match_record(C,PatArgs,C,ValArgs,Res) :- l_match_pattern_value(PatArgs,ValArgs,Res).
2808
2809 :- block l_match_pattern_value(-,?,?).
2810 l_match_pattern_value(vclosure,_T,R) :- !, R=match_true(vclosure).
2811 l_match_pattern_value([],T,R) :- !, R=match_true(T).
2812 l_match_pattern_value([H|T],Y,R) :- !, l_match_pattern_value1(Y,H,T,R).
2813 l_match_pattern_value(I,V,R) :-
2814 add_internal_error('Could not evaluate: ',l_match_pattern_value(I,V,R)),fail.
2815
2816 :- block l_match_pattern_value1(-,?,?,?).
2817 l_match_pattern_value1([],H,T,R) :- !, add_error(haskell_csp,'Too many values in rename pattern: ',[H|T]), R=match_false.
2818 l_match_pattern_value1([IODVal|IT],Pat,TPat,R) :- !,
2819 get_value_alsoPat(IODVal,PV),
2820 match_pattern_value(Pat,PV,Res),
2821 % print(matched(Pat,PV,Res,TPat,IT)),nl, %
2822 l_match_pattern_value2(Res,TPat,IT,R).
2823
2824 :- block l_match_pattern_value2(-,?,?,?).
2825 l_match_pattern_value2(match_true(M),TailPat,TailValue,Res) :-
2826 ((TailPat=[],TailValue==[]) -> Res=match_true(M) % avoid error message in conjoin
2827 ; TailPat=vclosure -> Res = match_true([]) % ignore match M;
2828 % there could be strange pattern match, but
2829 % it can happen that a partial record was provided (e.g., [|{|c_s.c_picks, in philosophers.csp)
2830 ; (is_list(M),M\=[]) -> % one of the list arguments was a tuple, we need to pattern match the rest of the tuple arguments
2831 append(TailValue,M,TailValue1),
2832 l_match_pattern_value(TailPat,TailValue1,Res)
2833 ;
2834 l_match_pattern_value(TailPat,TailValue,RT), % print(conjoin(RT,match_true(M),Res)),nl,
2835 conjoin_match(RT,match_true(M),Res)).
2836 l_match_pattern_value2(match_false,_,_,match_false).
2837
2838 :- block get_value_alsoPat(-,?).
2839 get_value_alsoPat(X,Res) :-
2840 get_value(X,R),
2841 (nonvar(R),R=alsoPat(V1,_V2) -> Res=V1 ; Res=R).
2842
2843 :- block conjoin_match(-,?,?), conjoin_match(?,-,?).
2844 conjoin_match(match_false,_,match_false).
2845 conjoin_match(match_true(_T),match_false,match_false).
2846 conjoin_match(match_true(T1),match_true(T2),Res) :- %append(T1,T2,TT).
2847 (T2==[] -> Res=match_true(T1) /* note T2: is the first match, T1 the later one */
2848 ; T2==vclosure -> Res=match_true(T1) /* vclosure can propagate to the next level up */
2849 ; conjoin_error(T2,T1,ResMatch), Res=match_true(ResMatch)).
2850
2851 % note: records (for example) are gradually enumerated; hence delay error message until we know the value of the inner match
2852 % check if we have a pattern match like rec.a.?.b.? -> this cannot be handled by us nor by FDR
2853 :- block conjoin_error(-,?,?).
2854 conjoin_error([],T1,M) :- !, M=T1.
2855 conjoin_error(vclosure,T1,M) :- !, M=T1.
2856 conjoin_error(T2,T1,T1) :- add_error(conjoin_match,'Rename pattern is incomplete in the middle. Ignoring first match: ',T2:T1).
2857
2858 :- assert_must_succeed((
2859 haskell_csp:match_pattern_list([tuple([c,int(0)|vclosure]),tuple([d|vclosure]),tuple([a,int(0),int(0),int(2)|vclosure])],[in(X),in(dotTuple([Y,Z]))],a,span,true,true),
2860 X=int(0), Y=int(0), Z=int(2))).
2861 :- assert_must_succeed((
2862 haskell_csp:match_pattern_list([tuple([c,int(0)|vclosure]),tuple([d|vclosure]),tuple([a,int(0),int(0),int(2)|vclosure])],[in(X),in(Y)],a,span,true,true),
2863 X=int(0), Y=tuple([int(0),int(2)]))).
2864 :- assert_must_succeed((
2865 haskell_csp:match_pattern_list([tuple([c,int(0)|vclosure]),tuple([d|vclosure]),tuple([a,int(0),int(0),int(2)]),tuple([d|vclosure])],[in(X),in(Y)],a,span,true,true),
2866 X=int(0), Y=tuple([int(0),int(2)]))).
2867 :- assert_must_fail((
2868 haskell_csp:match_pattern_list([tuple([a,int(0),int(0),int(2)]),tuple([c,int(0)|vclosure]),tuple([d|vclosure])],[in(X),in(Y)],a,span,true,true),
2869 X=int(0), Y=tuple([int(0),int(3)]))).
2870 :- assert_must_fail((
2871 haskell_csp:match_pattern_list([tuple([c,int(0)|vclosure]),tuple([d|vclosure]),tuple([a,int(0),int(0),int(2)])],[in(X),in(Y)],a,span,true,true),
2872 X=int(0), Y=tuple([int(0),int(3),int(2)]))).
2873
2874 % match_pattern_list(PatOrRenameList, Value,Channel,Span, Rename/MatchResult, HasMatchAlreadyOccured)
2875 match_pattern_list([],V,Ch,Span,io(V,Ch,SpanV),MatchOccured) :- %print(no_match(V,Ch,MatchOccured)),nl,
2876 set_span(SpanV,Span,match_pattern_list(Ch,V)),
2877 MatchOccured=false. % only allow unrenamed action if no match occured earlier
2878 match_pattern_list([rename(ChPat,NewCh)|T],V,Ch,Span,Res,MatchOccured) :- !,
2879 % print(checking_pat_match(ChPat,Ch,V)),nl, %%
2880 match_pattern_value(ChPat,tuple([Ch|V]),MatchRes),
2881 ? rename_action3(MatchRes,T,NewCh,V,Ch,Span,Res,MatchOccured).
2882 match_pattern_list([ChPat|T],V,Ch,Span,Res,MatchOccured) :- % for aParallel
2883 % print(checking_pat_match(ChPat,Ch,V)),nl, %%
2884 match_pattern_value(ChPat,tuple([Ch|V]),MatchRes),
2885 pat_match_action3(MatchRes,T,V,Ch,Span,Res,MatchOccured).
2886
2887 :- block pat_match_action3(-, ?,?,?,?, ?,?).
2888 pat_match_action3(match_true(Rest), _T, _V,_Ch,_Span, Res,_MatchOccured) :-
2889 (Rest=[] -> Res=true ; Rest=vclosure -> Res=true). % when doing a pat_match: we only allow full matches
2890 %pat_match_action3(match_true(_),T,V,Ch,Span,Res,_) :- match_pattern_list(T,V,Ch,Span,Res,true).
2891 pat_match_action3(match_false,T,V,Ch,Span,Res,MatchOccured) :- match_pattern_list(T,V,Ch,Span,Res,MatchOccured).
2892
2893 :- block rename_action3(-, ?,?, ?,?,?, ?,?).
2894 rename_action3(match_true(Rest), _T,NewCh, _V,_Ch,Span, Res,_MatchOccured) :-
2895 r_compose(NewCh,Rest,Span,Res).
2896 ?rename_action3(match_true(_),T,_NewCh,V,Ch,Span,Res,_) :- match_pattern_list(T,V,Ch,Span,Res,true).
2897 ?rename_action3(match_false,T,_NewCh,V,Ch,Span,Res,MatchOccured) :- match_pattern_list(T,V,Ch,Span,Res,MatchOccured).
2898
2899 r_compose(NewCh,Rest,Span,io(VRes,ResultingChannel,VSpan)) :-
2900 set_span(VSpan,Span,r_compose(NewCh)),
2901 %% print(rename_match(NewCh,Rest)),nl, %%
2902 evaluate_argument(dotTuple([NewCh|Rest]), ResultTuple),
2903 (ResultTuple = tuple([TCh|TV])
2904 -> ResultingChannel=TCh,VRes=TV
2905 ; add_internal_error('Illegal result tuple: ', evaluate_argument(dotTuple([NewCh|Rest]), ResultTuple)),
2906 ResultingChannel=NewCh, VRes=Rest
2907 ).
2908
2909
2910 evaluate_rename_list([],[]).
2911 evaluate_rename_list([rename(X,Y)|T],[rename(EX,EY)|ET]) :-
2912 evaluate_rename_channel_expression(X,EX),
2913 evaluate_rename_channel_expression(Y,EY),
2914 evaluate_rename_list(T,ET).
2915
2916 evaluate_link_list('linkList'(L),R) :- !,evaluate_link_list2(L,R).
2917 evaluate_link_list('linkListComp'(GeneratorList,LinkList),R) :- !,
2918 %print(procCompLinkList(GeneratorList,LinkList)),nl,
2919 % warning: LinkList does not have the rangeEnum wrapper expected
2920 expand_set_comprehension(rangeEnum(LinkList),GeneratorList,setValue(ExpandedLinks)),
2921 evaluate_link_list2(ExpandedLinks,R).
2922 evaluate_link_list(LL,R) :-
2923 add_internal_error('Cannot evaluate for Linked Parallel: ',evaluate_link_list(LL,R)),fail.
2924
2925 evaluate_link_list2([],[]).
2926 evaluate_link_list2([link(X,Y)|T],[rename(EX,EY)|ET]) :- /* note: link becomes rename */
2927 evaluate_rename_channel_expression(X,EX),
2928 evaluate_rename_channel_expression(Y,EY),
2929 evaluate_link_list2(T,ET).
2930
2931 rev_rename_list([],[]).
2932 rev_rename_list([rename(X,Y)|T],[rename(Y,X)|RT]) :- rev_rename_list(T,RT).
2933
2934
2935 evaluate_rename_channel_expression(E,RE) :- evaluate_argument(E,RE).
2936 % (E=dotTuple([CH|V])
2937 % -> (RE=dotTuple([CH|EV]),
2938 % l_evaluate_arguments(V,EV))
2939 % ; RE=E
2940 % ).
2941
2942 %%%%%%%%% DEAD CODE %%%%%%%%%%%%
2943 /*
2944 get_renamelist_range([],[]).
2945 get_renamelist_range([rename(_X,Y)|T],[Y|DT]) :-
2946 get_renamelist_range(T,DT).
2947 */
2948
2949 /* ------------------------------------- */
2950
2951 /* hidden(Action, ChannelPatternList) */
2952 /* check whether an Action is covered by a CSP Channel Pattern List */
2953
2954 hidden(tau(_),_) :- fail.
2955 hidden(tick(_),_) :- fail.
2956 hidden(io(V,Ch,Span), ChannelPatternList) :- match_list(ChannelPatternList,V,Ch,Span).
2957
2958 /* same as hidden but allows tau; useful for alphab. parallel */
2959 :- block hidden_or_tau(-,?).
2960 hidden_or_tau(tau(_),_).
2961 hidden_or_tau(tick(_),_) :- fail.
2962 hidden_or_tau(io(V,Ch,Span), ChannelPatternList) :- match_list(ChannelPatternList,V,Ch,Span).
2963
2964
2965 expand_channel_pattern_expression(X,_,SrcSpan) :-
2966 % nl,print(expand_channel_pattern_expression(X)),nl,
2967 var(X), !,
2968 add_error(haskell_csp,'VARIABLE in expand_channel_pattern_expression: ',X,SrcSpan),fail.
2969 expand_channel_pattern_expression(agent_call(Span,F,Par),Res,SrcSpan) :- !,
2970 unfold_function_call_once(F,Par,Body,Span), expand_channel_pattern_expression(Body,Res,SrcSpan).
2971 expand_channel_pattern_expression(setValue(List),EList,SrcSpan) :- !,l_expand(List,EList,SrcSpan).
2972 expand_channel_pattern_expression(closure(List),EList,_SrcSpan) :- !,
2973 %print(haskell_csp:l_cexpand(List,EList)),nl,
2974 l_cexpand(List,EList).
2975 %% this two clauses are already computed by expanding the setValue(-) and closure(-) predicates above (DEAD CODE)
2976 /* expand_channel_pattern_expression([],R,_SrcSpan) :- !, R=[]. */ /* already computed */
2977 /*expand_channel_pattern_expression([tuple([C|T])|T2],R,SrcSpan) :- !,*/ /* already computed */
2978 /* (check_channel_value_is_complete(C,T,SrcSpan)
2979 -> R=[tuple([C|T])|R2] ; R=R2),
2980 expand_channel_pattern_expression(T2,R2,SrcSpan).
2981 */
2982 expand_channel_pattern_expression(Exp,_,SrcSpan) :-
2983 add_error(haskell_csp,'Unknown expand_channel_pattern_expression: ',Exp,SrcSpan),fail.
2984
2985 /* translate a list of channel pattern expr. into uniform format */
2986 l_expand(X,R,SrcSpan) :- var(X),
2987 add_internal_error_with_span(haskell_csp,'Variable List for l_expand',X,SrcSpan), R=[].
2988 l_expand(List,Res,SrcSpan) :-
2989 convlist(expand_1(SrcSpan),List,Res).
2990
2991 expand_1(SrcSpan,El,R) :-
2992 expand(El,R,SrcSpan),!.
2993
2994 /*
2995 l_expand([],[],_).
2996 l_expand([H|T],Res,SrcSpan) :-
2997 (expand(H,EH,SrcSpan)->Res=[EH|ET];Res=ET),
2998 l_expand(T,ET,SrcSpan).
2999 */
3000
3001 expand(tuple([Ch|List]),R,SrcSpan) :- !,R=tuple([Ch|List]),
3002 check_channel_value_is_complete(Ch,List,SrcSpan).
3003 expand(Channel,R,SrcSpan) :-
3004 (atomic(Channel) -> R=tuple([Channel])
3005 ; add_error(haskell_csp,'Non-atomic argument: ',expand(Channel,R,SrcSpan)),fail).
3006
3007 check_channel_value_is_complete(Ch,List,SrcSpan) :-
3008 (channel_type_list(Ch,ChannelTypes)
3009 ->
3010 (same_length(ChannelTypes,List) -> true
3011 ; length(ChannelTypes,CL), length(List,L),
3012 (CL>L -> add_error(check_channel_value,'Incomplete event: ','.'(Ch,List),SrcSpan)
3013 ; add_error(check_channel_value,'Too many values for event: ','.'(Ch,List),SrcSpan)
3014 ), fail
3015 )
3016 ; add_error(haskell_csp,'Undefined channel: ','.'(Ch,List),SrcSpan),fail
3017 ).
3018
3019
3020 /* translate a list of channel pattern expr. into uniform format and add closure at end of list */
3021 l_cexpand(X,R) :- var(X), add_error(l_cexpand,'Variable List',X), R=[].
3022 l_cexpand(L,EL) :- maplist(cl_expand,L,EL).
3023
3024 % what about pat(_,_)
3025 cl_expand(tuple([Ch|List]),R) :- !, R = tuple([Ch|EL]),append_vclosure(List,EL). %, print(app_vcl(Ch,List,EL)),nl.
3026 cl_expand(Channel,R) :-
3027 (atomic(Channel) -> R = tuple([Channel|vclosure])
3028 ; add_error(haskell_csp, 'Non-atomic argument: ',cl_expand(Channel,R)),fail).
3029
3030
3031 append_vclosure([record(X,Fields)],Res) :- incomplete_record(record(X,Fields),[_|_],_),!,
3032 Res = [record(X,EFields)|vclosure],
3033 append_vclosure(Fields,EFields).
3034 append_vclosure([],vclosure).
3035 append_vclosure([H|T],[H|VT]) :- append_vclosure(T,VT).
3036
3037
3038 /* not_hidden(Action, ChannelPatternList) */
3039 /* check whether an Action is *not* covered by a CSP Channel Pattern List */
3040
3041 /* not_hidden_test(io(tail_in(X),outf),
3042 [pat([int(2)],outf),pat([int(3)],outf),pat([int(8)],outf)]) */
3043
3044 :- block not_hidden(-,?).
3045 not_hidden(tau(_),_).
3046 not_hidden(tick(_),_).
3047 not_hidden(io(V,Ch,Span),ChannelPatternList) :- % print(not_hidden_test(V,Ch,ChannelPatternList)),nl, %
3048 %not_hidden_test(ChannelPatternList,V,Ch,Span).
3049 match_pattern_list(ChannelPatternList,V,Ch,Span,io(_,_,_),false). % Result is true in case match occurs with list
3050
3051
3052 /* ------------------------------------- */
3053
3054 :- block get_value(-,?).
3055
3056 get_value(in(V),R) :- !,R=V.
3057 get_value(out(V),R) :- !, add_internal_error('Obsolete out: ',get_value(out(V),R)), R=V.
3058 get_value(dot(V),R) :- !, add_internal_error('Obsolete dot: ',get_value(out(V),R)), R=V.
3059 get_value(record(Constructor,Fields),R) :- !, R = record(Constructor,ValueFields),
3060 l_get_value(Fields,ValueFields).
3061 get_value(V,V).
3062
3063 :- block l_get_value(-,?).
3064 l_get_value(L,VL) :- maplist(get_value,L,VL).
3065
3066 ?valid_constant(X) :- atomic(X), (csp_constant(X,_) -> true ; fail).
3067
3068
3069 /* ------------------------------------------ */
3070 /* SPAN Utilities */
3071 /* ------------------------------------------ */
3072
3073 %%%%%%%%%%%%%%%%%%%%% UNIT TESTS FOR THE SPAN UTILITIES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3074 :- assert_must_succeed((haskell_csp: extract_span_info(_S,Info),Info == [])).
3075 :- assert_must_succeed((haskell_csp: extract_span_info(span_info(info,src_span(3,9,3,12,45,3)),R),R == [info])).
3076 :- assert_must_succeed((haskell_csp: extract_span_info(src_position(3,9,3,12), R),R == [])).
3077 :- assert_must_succeed((haskell_csp: extract_span_info(src_span(3,9,3,12,45,3), R),R == [])).
3078 :- assert_must_succeed((haskell_csp: extract_span_info(unknown(_), R),R == [])).
3079 :- assert_must_succeed((haskell_csp: extract_span_info(multi_span(3,9,3,12,45,3,span_info(info,src_span(3,9,3,12,45,3))), R),
3080 R == [info])).
3081 :- assert_must_succeed((haskell_csp: extract_span_info(src_span_operator(span_info(info,
3082 src_span(94417,10,94421,21,1496266,98)),src_span(94421,2,94421,4,1496345,2)),R), R == [info])).
3083 :- assert_must_succeed((haskell_csp: extract_span_info(no_loc_info_available,R), R == [])).
3084
3085 :- assert_must_succeed((haskell_csp: unify_spans(src_span(3,9,3,12,45,3),S,R),S== src_span(3,9,3,12,45,3), R == src_span(3,9,3,12,45,3))).
3086 :- assert_must_succeed((haskell_csp: unify_spans(src_span(3,9,3,12,45,3),src_span(4,9,5,16,40,5),R),
3087 R == multi_span(3,9,3,12,45,3,src_span(4,9,5,16,40,5)))).
3088 :- assert_must_succeed((haskell_csp: unify_spans(src_span_operator(src_span(94417,10,94421,21,1496266,98),src_span(94421,2,94421,4,1496345,2)),SP2, R), SP2 == src_span(94421,2,94421,4,1496345,2),
3089 R == src_span_operator(src_span(94417,10,94421,21,1496266,98),src_span(94421,2,94421,4,1496345,2)))).
3090 :- assert_must_succeed((haskell_csp: unify_spans(unknown(_),SP2,R), SP2 == R)).
3091 :- assert_must_succeed((haskell_csp: unify_spans(no_loc_info_available,SP2,R), SP2 == R)).
3092 :- assert_must_succeed((haskell_csp: unify_spans(src_span(3,9,3,12,12,3), no_loc_info_available,R), R == src_span(3,9,3,12,12,3))).
3093 :- assert_must_succeed((haskell_csp: unify_spans(span_info(info,src_span(3,9,3,12,45,3)),src_span(3,9,3,12,45,3),R),
3094 R == span_info(info,src_span(3,9,3,12,45,3)))).
3095 :- assert_must_succeed((haskell_csp: unify_spans(src_position(3,9,3,12),src_span(4,9,4,15,45,6),R),
3096 R == multi_span(3,9,3,21,3,12,src_span(4,9,4,15,45,6)))).
3097 :- assert_must_succeed((extract_span_from_event2(start_cspm_MAIN,SPAN, start_cspm_MAIN,_), SPAN == src(3,1,3,5,20,4))).
3098 :- assert_must_succeed((extract_span_from_event2(start_cspm('REC'),SPAN,start_cspm('REC'),_), SPAN == src(8,1,8,4,4,3))).
3099 :- assert_must_fail((extract_span_from_event(_X,_Span,_T,_NS))).
3100 :- assert_must_succeed((extract_span_info(src_position(_,_,_,_),R1), R1 ==[], extract_span_info(unknown(_),R2), R2 ==[])).
3101 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3102
3103 % span can already be set:
3104 % problem: rename_action in eprocRenaming has to instantiate Span; in other contexts hidden should not instantiate span
3105 set_span(SpanVar,SpanValue,PP) :- nonvar(SpanVar),!,
3106 debug_println(9,span_already_set(PP,SpanValue)).
3107 % print('*** Span already set to: '), print(SpanVar),nl,
3108 % print('*** tried to assign value: '),print(SpanValue),nl,print('*** Context: '), print(PP),nl.
3109 set_span(S,S,_C). % :- print(setting_span(S,_C)),nl.
3110
3111 extract_span_info(Span,Info) :- var(Span),!,Info=[].
3112 extract_span_info(span_info(Info,Span),[Info|T]) :- extract_span_info(Span,T).
3113 extract_span_info(src_position(_,_,_,_),[]).
3114 extract_span_info(src_span(_,_,_,_,_,_),[]).
3115 extract_span_info(src_span_operator(WholeSP1,_JustOperatorSP2),T) :- extract_span_info(WholeSP1,T).
3116 extract_span_info(unknown(_),[]).
3117 extract_span_info(multi_span(_,_,_,_,_,_,SP1),T) :- extract_span_info(SP1,T).
3118 extract_span_info(no_loc_info_available,[]).
3119
3120 :- block unify_spans(-,?,?).
3121 %unify_spans(S,_,R) :- !,R=S. % commenting this in gains 10 % performance, e.g., on crossing.csp benchmark
3122 unify_spans(SP1,SP2,R) :- ( unify_spans1(SP1,SP2,R) -> true
3123 ; add_internal_error('Failed: ',unify_spans(SP1,SP2,R)),set_span(SP1,R,unify_spans)).
3124 :- block unify_spans1(-,?,?).
3125 unify_spans1(SP1,SP2,R) :- nonvar(R),!,
3126 debug_println(9,span_already_computed(R,unify_spans(SP1,SP2))).
3127 unify_spans1(span_info(Info,SP1),SP2,R) :- !, R=span_info(Info,RS),
3128 unify_spans1(SP1,SP2,RS).
3129 unify_spans1(src_position(StartLine,SC,OffsetByte,LenBytes),SP2,R) :- number(SC), number(LenBytes),!,
3130 EndLine = StartLine, EC is SC+LenBytes,
3131 gen_multi_span(SP2, StartLine,SC,EndLine,EC,OffsetByte,LenBytes, R).
3132 unify_spans1(src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes),S,R) :- !,
3133 unify_spans2(src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes),S,R).
3134 unify_spans1(src_span_operator(SP1,SP2),SP3,R) :- !, R=src_span_operator(SP1,SP23),
3135 unify_spans1(SP2,SP3,SP23).
3136 unify_spans1(multi_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes,SP1),SP2,R) :- !,
3137 unify_spans1(SP1,SP2,TailS),
3138 gen_multi_span(TailS, StartLine,SC,EndLine,EC,OffsetByte,LenBytes, R).
3139 unify_spans1(unknown(_),S,R) :- !, R=S.
3140 unify_spans1(no_loc_info_available,S,R) :- !, R=S.
3141 unify_spans1(S,_,S) :- add_error(unify_spans1,'Unknown Span: ',S).
3142
3143
3144 :- block unify_spans2(-,?,?).
3145 unify_spans2(src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes),S,R) :-
3146 S=src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes),!, R=S.
3147 unify_spans2(src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes),SP2,R) :- !,
3148 gen_multi_span(SP2, StartLine,SC,EndLine,EC,OffsetByte,LenBytes, R).
3149
3150
3151 :- block gen_multi_span(-, ?,?,?,?, ?,?,?).
3152 gen_multi_span(no_loc_info_available, StartLine,SC,EndLine,EC, OffsetByte,LenBytes, R) :- !,
3153 R = src_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes).
3154 gen_multi_span(Span2,StartLine,SC,EndLine,EC,OffsetByte,LenBytes,R) :-
3155 R = multi_span(StartLine,SC,EndLine,EC,OffsetByte,LenBytes, Span2),!.
3156
3157
3158 :- block merge_span_into_event(?,-,?).
3159 merge_span_into_event(Event,no_loc_info_available,NewEvent) :- !,
3160 NewEvent=Event.
3161 merge_span_into_event(Event,AdditionalSpan,NewEvent) :-
3162 (extract_span_from_event(Event,SPAN,Templ,NewSPAN)
3163 -> Templ = NewEvent, unify_spans(SPAN,AdditionalSpan,NewSPAN)
3164 ; (%add_error(merge_span_into_event,'Unknown Event: ',Event),
3165 % sometimes we cannot extract a source span, e.g., tau(repInternalChoice ...)
3166 NewEvent = Event)
3167 ).
3168
3169 %type_of_event(io( or colour_of_event ...
3170 extract_span_from_event(Event,_Span,_Template,_NewSpan) :- var(Event),
3171 debug_println(9,'### extract_span_from_event variable'),!,fail.
3172 extract_span_from_event(Event,Span,Template,NewSpan) :- process_algebra_mode,!,
3173 extract_span_from_event2(Event,Span,Template,NewSpan).
3174
3175 %:- block extract_span_from_event2(-,?,?,?).
3176 extract_span_from_event2(start_cspm_MAIN,SPAN,start_cspm_MAIN,_) :- !,get_symbol_span('MAIN',SPAN).
3177 extract_span_from_event2(start_cspm(S),SPAN,start_cspm(S),_) :- !,get_symbol_span(S,SPAN).
3178 extract_span_from_event2(io(Ev,Ch,SPAN),SPAN,io(Ev,Ch,NewSPAN),NewSPAN).
3179 extract_span_from_event2(tau(link(Left,Right)),SPAN,Templ,NS) :- !, Templ = tau(link(Left,RTempl)),
3180 extract_span_from_event2(Right,SPAN,RTempl,NS). % the linking code already puts info into right branch
3181 %extract_span_from_event2(Left,RS,LTempl,RS),
3182 %unify_spans(LS,RS,NS).
3183 extract_span_from_event2(tau(hide(Event)),SPAN,Templ,NS) :- !, Templ = tau(hide(ETempl)),
3184 extract_span_from_event2(Event,SPAN,ETempl,NS).
3185 %extract_span_from_event2(tau(repInternalChoice(X)),no_loc_info_available,Templ,NS) :- !, Templ = tau(repInternalChoice(X)).
3186 extract_span_from_event2(tau(int_choice_left(S,LSpan)),SPAN,Templ,NS) :- !,
3187 Templ = tau(int_choice_left(S,NS)),
3188 SPAN = LSpan.
3189 extract_span_from_event2(tau(int_choice_right(S,RSpan)),SPAN,Templ,NS) :- !,
3190 Templ = tau(int_choice_right(S,NS)),
3191 SPAN = RSpan.
3192 extract_span_from_event2(tau(Event),SPAN,tau(Templ),NS) :- simple_tau_event(Event,Constructor,SPAN),!,
3193 functor(Templ,Constructor,1),
3194 arg(1,Templ,NS).
3195 %%extract_span_from_event2(i(SPAN),SPAN,i(NS),NS). %% deprecated
3196 extract_span_from_event2(tick(SPAN),SPAN,tick(NS),NS).
3197
3198 simple_tau_event(chaos_stop(Span),chaos_stop,Span).
3199 simple_tau_event(timeout(Span),timeout,Span).
3200 %simple_tau_event(int_choice_left(_,SrcSpan),int_choice_left,SrcSpan).
3201 %shift_span_for_left_branch(SrcSpan,LSpan).
3202 %simple_tau_event(int_choice_right(_,SrcSpan),int_choice_right,SrcSpan).
3203 %shift_span_for_right_branch(SrcSpan,RSpan).
3204 simple_tau_event(rep_int_choice(Span),rep_int_choice,Span).
3205 simple_tau_event(tick(Span),tick,Span).
3206
3207 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(src_span(3,1,_,_,4,_),R),
3208 R == src_span(3,1,3,2,4,1))).
3209 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(src_position(3,1,3,_),R),
3210 R == src_position(3,1,3,1))).
3211 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(src_span_operator(_SP,src_span(3,1,_,_,4,_)),R),
3212 R == src_span(3,1,3,2,4,1))).
3213 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(no_loc_info_available,R),
3214 R == no_loc_info_available)).
3215 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(unknown,R),
3216 R == unknown)).
3217 :- assert_must_succeed((haskell_csp: shift_span_for_left_branch(src,R),
3218 R == src)).
3219 :- block shift_span_for_left_branch(-,?).
3220 shift_span_for_left_branch(src_span(StartLine,SC,_EndLine,_EC,Off,_LenBytes),R) :- !,
3221 NEC is SC+1,
3222 R=src_span(StartLine,SC,StartLine,NEC,Off,1).
3223 shift_span_for_left_branch(src_position(StartLine,SC,Off,_LenBytes),R) :- !,
3224 R = src_position(StartLine,SC,Off,1).
3225 shift_span_for_left_branch(src_span_operator(_WholeSpan,JustOperator),R) :- !,
3226 shift_span_for_left_branch(JustOperator,R).
3227 shift_span_for_left_branch(no_loc_info_available,R) :- !, R=no_loc_info_available.
3228 shift_span_for_left_branch(unknown(I),R) :- !, R=unknown(I).
3229 shift_span_for_left_branch(X,X):- debug_println(9,not_shifting_left(X)).
3230
3231 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(src_span(_,_,3,2,6,5),R),
3232 R == src_span(3,1,3,2,10,1))).
3233 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(src_position(3,1,3,4),R),
3234 R == src_position(3,4,6,1))).
3235 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(src_span_operator(_SP,src_span(_,_,3,2,6,5)),R),
3236 R == src_span(3,1,3,2,10,1))).
3237 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(no_loc_info_available,R),
3238 R == no_loc_info_available)).
3239 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(unknown,R),
3240 R == unknown)).
3241 :- assert_must_succeed((haskell_csp: shift_span_for_right_branch(src,R),
3242 R == src)).
3243
3244 :- block shift_span_for_right_branch(-,?).
3245 shift_span_for_right_branch(src_span(_StartLine,_SC,EndLine,EC,Off,LenBytes),R) :- !,
3246 NL is 1, NSC is EC-1, NO is Off+LenBytes-1,
3247 R=src_span(EndLine,NSC,EndLine,EC,NO,NL).
3248 shift_span_for_right_branch(src_position(StartLine,SC,Off,LenBytes),R) :- !,
3249 NL is 1, NSC is SC+LenBytes-1, NO is Off+LenBytes-1,
3250 R = src_position(StartLine,NSC,NO,NL).
3251 shift_span_for_right_branch(src_span_operator(_WholeSpan,JustOperator),R) :- !,
3252 shift_span_for_right_branch(JustOperator,R).
3253 shift_span_for_right_branch(no_loc_info_available,R) :- !, R=no_loc_info_available.
3254 shift_span_for_right_branch(unknown(I),R) :- !, R=unknown(I).
3255 shift_span_for_right_branch(X,X):- debug_println(9,not_shifting_right(X)).
3256
3257
3258 % ----------------------
3259
3260 get_cspm_identifier(channel,ID) :- channel(ID,_).
3261 get_cspm_identifier(datatype,DT) :- is_a_datatype(DT,_).