1 % (c) 2009-2024 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(parsercall, [load_b_machine_as_term/3,
6 load_b_machine_probfile_as_term/2, % a way to directly load a .prob file
7 load_b_machine_probfile_as_term/3,
8 load_b_machine_list_of_facts_as_term/2,
9 get_parser_version/1,
10 get_parser_version/2,
11 get_parser_version/6,
12 get_java_command_path/1,
13 check_java_version/2,
14 get_java_fullversion/1, get_java_fullversion/3, get_java_version/1,
15 ensure_console_parser_launched/0, % just make sure the console parser is up and running
16 connect_to_external_console_parser_on_port/1, % connect to a separately started parser
17 release_console_parser/0,
18 console_parser_jar_available_in_lib/0,
19 call_ltl_parser/3,
20 call_tla2b_parser/1, tla2b_filename/2,
21 %call_promela_parser/1, promela_prolog_filename/2,
22 call_alloy2pl_parser/2,
23 tla2prob_filename/2,
24 parse/3,
25 parse_at_position_in_file/5,
26 parse_formula/2, parse_predicate/2, parse_expression/2,
27 parse_substitution/2,
28 transform_string_template/3,
29 call_fuzz_parser/2,
30 register_parsing_call_back/1, deregister_parsing_call_back/0,
31 set_default_filenumber/2, reset_default_filenumber/2
32 ]).
33
34 :- meta_predicate register_parsing_call_back(4).
35
36 :- use_module(module_information,[module_info/2]).
37 :- module_info(group,typechecker).
38 :- module_info(description,'This module takes care of calling the Java B Parser if necessary.').
39
40 :- use_module(library(lists)).
41 :- use_module(library(process)).
42 :- use_module(library(file_systems)).
43 :- use_module(library(codesio)).
44 :- use_module(library(system)).
45 :- use_module(library(sockets)).
46
47 :- use_module(error_manager,[add_error/2, add_error/3, add_error/4, add_error_fail/3,
48 add_failed_call_error/1, add_internal_error/2, add_warning/3, add_warning/4, real_error_occurred/0,
49 add_message/3, add_message/4, extract_line_col/5, add_all_perrors/3]).
50 :- use_module(self_check).
51 :- use_module(preferences).
52 :- use_module(tools, [split_filename/3, same_file_name/2, get_PROBPATH/1, safe_atom_chars/3]).
53 :- use_module(tools_platform, [host_platform/1, platform_is_64_bit/0]).
54 :- use_module(tools_strings,[ajoin_with_sep/3, ajoin/2]).
55 :- use_module(tools_printing,[print_error/1, format_with_colour_nl/4]).
56 :- use_module(debug).
57 :- use_module(bmachine,[b_get_definition/5, b_machine_is_loaded/0]).
58 :- use_module(specfile, [b_or_z_mode/0]).
59
60 :- set_prolog_flag(double_quotes, codes).
61
62 :- dynamic java_parser_version/6.
63
64 % stores the java process of the parser, consisting of ProcessIdentifier, Socket Stream, STDErrStream
65 :- dynamic java_parser_process/4.
66 :- volatile java_parser_process/4.
67
68
69 send_definition(Stream,def(Name,Type,Arity)) :-
70 write(Stream,'definition'), nl(Stream),
71 format(Stream,'~w\n~w\n~w\n',[Name,Type,Arity]).
72
73 :- dynamic definitions_already_sent/0.
74 :- volatile definitions_already_sent/0.
75
76 send_definitions(ToParser) :-
77 b_or_z_mode, b_machine_is_loaded,
78 \+ definitions_already_sent,
79 !,
80 findall_definitions(L),
81 % format('~nSending definitions ~w~n~n',[L]),
82 maplist(send_definition(ToParser),L),
83 assertz(definitions_already_sent).
84 send_definitions(_).
85
86 findall_definitions(DefList) :-
87 findall(def(Name,Type,Arity),(b_get_definition(Name,Type,Args,_,_),length(Args,Arity)),DefList).
88
89 get_definitions(L) :- b_or_z_mode, b_machine_is_loaded,!, findall_definitions(L).
90 get_definitions([]).
91
92 reset_definitions :-
93 retractall(definitions_already_sent),
94 parser_is_launched, % otherwise no need to reset; inside prob2_kernel there is no Java parser for probcli
95 (debug_mode(off) -> true
96 ; get_parser_version(Version),
97 format('Resetting DEFINITIONS for parser version ~w ~n',[Version])
98 ),
99 % TO DO: check if parser Version is at least 2.9.27
100 get_console_parser(ParserStream,Out,Err),!,
101 write(ParserStream,'resetdefinitions'), nl(ParserStream), % only supported in more recent versions of the parser
102 flush_output(ParserStream),
103 display_pending_outputs(Out,user_output),
104 display_pending_outputs(Err,user_error).
105 reset_definitions.
106
107 % update preferences of parser using new PREPL commands
108 update_jvm_parser_preferences :-
109 get_preference(jvm_parser_fastrw,FAST),
110 try_set_parser_option_nc(fastPrologOutput,FAST,_),
111 get_preference(jvm_parser_position_infos,LINENO),
112 try_set_parser_option_nc(addLineNumbers,LINENO,_),
113 % we have to set the swi mode here so it works with older parser versions
114 (current_prolog_flag(dialect, swi) -> SWI=true ; SWI=false),
115 try_set_parser_option_nc(swiSupport,SWI,_),
116 (debug_mode(off) -> VERBOSE=false ; VERBOSE=true),
117 try_set_parser_option_nc(verbose,VERBOSE,_).
118
119
120 :- dynamic cur_defaultFileNumber/1.
121
122 try_set_parser_option(defaultFileNumber,Value,Res) :- !,
123 (cur_defaultFileNumber(Value) % cache last value to avoid unnecessary parser calls
124 -> Res=prev_value(Value) % nothing to do
125 ; retractall(cur_defaultFileNumber(_)),
126 assert(cur_defaultFileNumber(Value)),
127 try_set_parser_option_nc(defaultFileNumber,Value,Res)
128 ).
129 try_set_parser_option(Name,Value,Res) :-
130 try_set_parser_option_nc(Name,Value,Res).
131
132 reset_parser_option_cache :- retractall(cur_defaultFileNumber(_)).
133
134 % try_set_parser_option_nc: non-caching version
135 try_set_parser_option_nc(Name,Value,Res) :-
136 parser_command_supported(setoption),
137 !,
138 debug_format(4,'Updating parser option: ~q=~q~n',[Name,Value]),
139 get_console_parser(Stream,_Out,Err),
140 write(Stream,setoption), nl(Stream),
141 write(Stream,Name), nl(Stream),
142 write(Stream,Value), nl(Stream),
143 flush_output(Stream),
144 read_line(Stream,CodesIn),
145 my_read_from_codes(CodesIn,Res,Stream,Err).
146 try_set_parser_option_nc(Name,Value,Res) :-
147 old_option_command(Name,Command),
148 parser_command_supported(Command),
149 !,
150 debug_format(19,'Updating JVM parser option (using old command ~q): ~q=~q~n',[Command,Name,Value]),
151 get_console_parser(Stream,_Out,_Err),
152 write(Stream,Command), nl(Stream),
153 write(Stream,Value), nl(Stream),
154 flush_output(Stream),
155 Res = changed. % prev_value isn't returned here
156 try_set_parser_option_nc(Name,Value,unsupported) :-
157 debug_format(19,'Parser too old to change option at runtime: ~q=~q~n',[Name,Value]).
158
159 get_parser_option(Name,Value) :-
160 parser_command_supported(getoption),
161 !,
162 debug_format(4,'Getting parser option: ~q~n',[Name]),
163 get_console_parser(Stream,_Out,Err),
164 write(Stream,getoption), nl(Stream),
165 write(Stream,Name), nl(Stream),
166 flush_output(Stream),
167 read_line(Stream,CodesIn),
168 my_read_from_codes(CodesIn,Value,Stream,Err).
169
170 old_option_command(addLineNumbers,lineno).
171 old_option_command(verbose,verbose).
172 old_option_command(fastPrologOutput,fastprolog).
173 old_option_command(compactPrologPositions,compactpos).
174 old_option_command(machineNameMustMatchFileName,checkname).
175
176 reset_old_parser_option_value(Name,Value,prev_value(Old)) :- \+ unchanged(Value,Old), !,
177 try_set_parser_option(Name,Old,_).
178 reset_old_parser_option_value(_,_,_).
179
180 % the Java values are stored as strings, even for number attributes
181 unchanged(V,V).
182 unchanged(N,A) :- number(N), atom(A), number_codes(N,C), atom_codes(A,C).
183
184 reset_parser :- reset_definitions, reset_parser_option_cache.
185 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
186 :- register_event_listener(clear_specification,reset_parser,
187 'Remove DEFINITIONS from parser cache and reset parer options cache.').
188
189 crlf(10).
190 crlf(13).
191
192 % remove newlines in a B formula so that we can pass the formula as a single line to the parser
193 cleanup_newlines([],[]).
194 cleanup_newlines([H|T],CleanCodes) :- crlf(H),!,
195 % this could also be inside a multi-line string; the string will be modified by this conversion
196 CleanCodes=[8232|TC], % 8232 \x2028 is Unicode line separator
197 cleanup_newlines(T,TC).
198 %cleanup_newlines([47,47|T],CleanCodes) :-
199 % % a B Comment '//': we used to skip until end of line
200 % % but this could be inside a string ! see test 2236
201 % CleanCodes=[8232|TC], skip_until_crlf(T,T2), !, cleanup_newlines(T2,TC).
202 cleanup_newlines([H|T],[H|R]) :- cleanup_newlines(T,R).
203
204 %skip_until_crlf([],[]).
205 %skip_until_crlf([H|T],T) :- crlf(H),!.
206 %skip_until_crlf([_|T],R) :- skip_until_crlf(T,R).
207
208 % register parsing call back from prob_socket_server within ProB2
209 :- dynamic prob2_call_back_available/1.
210 register_parsing_call_back(CallBackPred4) :- deregister_parsing_call_back,
211 assertz(prob2_call_back_available(CallBackPred4)).
212 deregister_parsing_call_back :-
213 retractall(prob2_call_back_available(_)).
214
215 % ---------
216
217 %! parse_x(+Kind,+Codes,-Tree)
218 % Kind is formula, expression, predicate, substitution
219 %:- use_module(prob_socketserver,[prob2_call_back_available/0, prob2_call_back/2]).
220 parse_x(Kind,CodesWithNewlines,Tree) :-
221 parse_simple(Kind,CodesWithNewlines,Res),!,
222 % format('Parse simple ~s : ~w~n',[CodesWithNewlines,Res]),
223 Tree=Res.
224 parse_x(Kind,CodesWithNewlines,Tree) :-
225 parse_y(Kind,CodesWithNewlines,Tree).
226
227 % a version which does not attempt simple parsing without calling Java:
228 parse_y(Kind,CodesWithNewlines,Tree) :-
229 prob2_call_back_available(ParseCallBackPred),
230 cleanup_newlines(CodesWithNewlines,Codes), atom_codes(Formula,Codes),
231 debug_format(19,'Parsing ~w via call_back: ~w~n',[Kind,Formula]),
232 get_definitions(DefList),
233 call(ParseCallBackPred,Kind,DefList,Formula,Tree),
234 % TO DO: deal with substitutions
235 debug_println(19,prob2_call_back_available_parse_result(Tree)),
236 (Tree = call_back_not_supported ->
237 % Parsing callback isn't implemented (e. g. ProB Rodin plugin) - don't try to use it again in the future.
238 deregister_parsing_call_back,
239 fail
240 ; true),
241 !,
242 (Tree = parse_error(Exception)
243 -> handle_parser_exception(Exception)
244 ; functor(Tree,parse_error,_) % deprecated
245 -> throw(parse_errors([error('Parse error occurred via ProB2 call_back:',unknown)]))
246 ; true).
247 parse_y(Kind,CodesWithNewlines,Tree) :-
248 % Java parser expects only one line of input -> remove newlines
249 cleanup_newlines(CodesWithNewlines,Codes),
250 % statistics(walltime,[Tot,Delta]), format('~s~n~w~n0 ~w (Delta ~w) ms ~n',[Codes,Kind,Tot,Delta]),
251 get_console_parser(Stream,Out,Err),
252 send_definitions(Stream),
253 write(Stream,Kind),
254 nl(Stream),
255 format(Stream,'~s',[Codes]), %format(user_output,'sent: ~s~n',[Codes]),
256 nl(Stream),
257 flush_output(Stream),
258 read_line(Stream,CodesIn),
259 %format('read: ~s~n',[CodesIn]),
260 catch(
261 (my_read_from_codes(CodesIn,Tree,Stream,Err),handle_parser_exception(Tree)),
262 error(_,_),
263 (append("Illegal parser result exception: ",CodesIn,ErrMsgCodes),
264 atom_codes(ErrMsg,ErrMsgCodes),
265 throw(parse_errors([internal_error(ErrMsg,none)])))),
266 display_pending_outputs(Out,user_output).
267 %statistics(walltime,[Tot4,Delta4]), format('4 ~w (Delta ~w) ms ~n ~n',[Tot4,Delta4]).
268
269 % a few very simple cases, which can be parsed without accessing Java parser:
270 % common e.g., in JSON trace files or Latex files to avoid overhead of calling parser
271 parse_simple(Kind,Codes,AST) :-
272 (Kind=expression -> true ; Kind=formula),
273 (cur_defaultFileNumber(FN) -> true ; FN = -1),
274 parse_simple_codes(Codes,FN,1,1,AST).
275
276 % ---------------------------
277
278 % benchmarking code:
279 % statistics(walltime,[_W1,_]),(for(I,1,10000) do parsercall:parse_formula("123",Tree)),statistics(walltime,[_W2,_]),D is _W2-_W1.
280 % | ?- findall("|-> 123",between(2,10000,X),L), append(["123 "|L],Str), statistics(walltime,[_W1,_]),parsercall:parse_expression(Str,Tree), statistics(walltime,[_W2,_]),D is _W2-_W1.
281
282 parse_simple_codes(Codes,FileNr,SL,SC,AST) :-
283 parse_int_codes(Codes,Len,Val), !,
284 L2 is Len+SC, % EndColumn of p4 position (same line)
285 AST=integer(p4(FileNr,SL,SC,L2),Val).
286 parse_simple_codes("TRUE",FileNr,SL,SC,AST) :- !, EC is SC+4, AST=boolean_true(p4(FileNr,SL,SC,EC)).
287 parse_simple_codes("FALSE",FileNr,SL,SC,AST) :- !, EC is SC+5, AST=boolean_false(p4(FileNr,SL,SC,EC)).
288 parse_simple_codes("{}",FileNr,SL,SC,AST) :- !, EC is SC+2, AST=empty_set(p4(FileNr,SL,SC,EC)).
289 parse_simple_codes(Codes,FileNr,SL,SC,AST) :- is_real_literal_codes(Codes),!,
290 length(Codes,Len), L2 is Len+SC,
291 atom_codes(Atom,Codes),
292 AST=real(p4(FileNr,SL,SC,L2),Atom).
293 % TO DO: maybe simple string values, simple identifiers: but we need to know the keyword list for this
294
295 :- assert_must_succeed((parsercall:parse_int_codes("0",Len,Res), Len==1, Res==0)).
296 :- assert_must_succeed((parsercall:parse_int_codes("1",Len,Res), Len==1, Res==1)).
297 :- assert_must_succeed((parsercall:parse_int_codes("12",Len,Res), Len==2, Res==12)).
298 :- assert_must_succeed((parsercall:parse_int_codes("931",Len,Res), Len==3, Res==931)).
299 :- assert_must_succeed((parsercall:parse_int_codes("100931",Len,Res), Len==6, Res==100931)).
300 parse_int_codes([Digit|T],Len,Res) :- digit_code_2_int(Digit,DVal),
301 (DVal=0 -> T=[], Len=1, Res=0
302 ; parse_int2(T,DVal,Res,1,Len)).
303
304 parse_int2([],Acc,Acc,LenAcc,LenAcc).
305 parse_int2([Digit|T],Acc,Res,LenAcc,Len) :-
306 digit_code_2_int(Digit,DVal),
307 NewAcc is Acc*10 + DVal,
308 L1 is LenAcc+1,
309 parse_int2(T,NewAcc,Res,L1,Len).
310
311 digit_code_2_int(X,Val) :- X >= 48, X =< 57, Val is X - 48.
312 is_digit(X) :- X >= 48, X =< 57.
313
314 :- assert_must_succeed(parsercall:is_real_literal_codes("0.0")).
315 :- assert_must_succeed(parsercall:is_real_literal_codes("112300.0010")).
316 :- assert_must_succeed(parsercall:is_real_literal_codes("1234567890.9876543210")).
317 :- assert_must_succeed(parsercall:is_real_literal_codes("001.0")). % is accepted by parser
318 :- assert_must_fail(parsercall:is_real_literal_codes("0")).
319 :- assert_must_fail(parsercall:is_real_literal_codes("11.")).
320 :- assert_must_fail(parsercall:is_real_literal_codes(".12")).
321 :- assert_must_fail(parsercall:is_real_literal_codes("12a.0")).
322 % TODO: we could return length and merge with parse_int_codes to do only one traversal
323
324 is_real_literal_codes([Digit|T]) :- is_digit(Digit), is_real_lit1(T).
325 is_real_lit1([0'.,Digit|T]) :- is_digit(Digit), is_real_lit2(T).
326 is_real_lit1([Digit|T]) :- is_digit(Digit), is_real_lit1(T).
327 is_real_lit2([]).
328 is_real_lit2([Digit|T]) :- is_digit(Digit), is_real_lit2(T).
329
330 % ---------------------
331
332 my_read_from_codes(end_of_file,_,_,Err) :- !,
333 read_line_if_ready(Err,Err1Codes), % we just read one line
334 safe_name(ErrMsg,Err1Codes),
335 add_error(parsercall,'Abnormal termination of parser: ',ErrMsg),
336 missing_parser_diagnostics,
337 ajoin(['Parser not available (',ErrMsg,')'],FullErrMsg),
338 read_lines_and_add_as_error(Err), % add other info on error stream as single error
339 throw(parse_errors([error(FullErrMsg,none)])).
340 my_read_from_codes(ErrorCodes,_Tree,Out,_) :-
341 append("Error",_,ErrorCodes),!,
342 atom_codes(ErrMsg,ErrorCodes),
343 add_error(parsercall,'Error running/starting parser: ',ErrMsg),
344 read_lines_and_add_as_error(Out),
345 fail.
346 my_read_from_codes(CodesIn,Tree,_,_) :- read_from_codes(CodesIn,Tree).
347
348 % a version of my_read_from_codes which has no access to error stream
349 my_read_from_codes(end_of_file,_) :- !,
350 missing_parser_diagnostics,
351 throw(parse_errors([error('Parser not available (end_of_file on input stream)',none)])).
352 my_read_from_codes(ErrorCodes,_Tree) :-
353 append("Error",_,ErrorCodes),!,
354 atom_codes(ErrMsg,ErrorCodes),
355 add_error(parsercall,'Error running/starting parser: ',ErrMsg),
356 fail.
357 my_read_from_codes(CodesIn,Tree) :- read_from_codes(CodesIn,Tree).
358
359 :- use_module(probsrc(preferences),[get_prob_application_type/1]).
360 missing_parser_diagnostics :-
361 parser_location(Classpath), debug_println(9,classpath(Classpath)),fail.
362 missing_parser_diagnostics :- runtime_application_path(P),
363 atom_concat(P,'/lib/probcliparser.jar',ConParser), % TODO: adapt for GraalVM cliparser
364 (file_exists(ConParser)
365 -> add_error(parsercall,'The Java B parser (probcliparser.jar) cannot be launched: ',ConParser),
366 (get_prob_application_type(tcltk) ->
367 add_error(parsercall,'Please check that Java and B Parser are available using the "Check Java and Parser Version" command in the Debug menu.')
368 ; host_platform(windows) ->
369 add_error(parsercall,'Please check that Java and B Parser are available, e.g., using "probcli.exe -check_java_version" command.')
370 ; add_error(parsercall,'Please check that Java and B Parser are available, e.g., using "probcli -check_java_version" command.')
371 % application_type
372 % TODO: avoid printing the message when the user is already calling check_java_version
373 ),
374 (get_preference(jvm_parser_additional_args,ExtraArgStr), ExtraArgStr\=''
375 -> add_error(parsercall,'Also check your JVM_PARSER_ARGS preference value:',ExtraArgStr)
376 ; true)
377 ; add_internal_error('Java B parser (probcliparser.jar) is missing from lib directory in: ',P)
378 ).
379
380 % ProB2 cli builds do not have the cli parser bundled
381 % check if there is a jar available in the lib folder:
382 % should only happen for get_prob_application_type(probcli) in ProB2
383 console_parser_jar_available_in_lib :-
384 runtime_application_path(P),
385 atom_concat(P,'/lib/probcliparser.jar',ConParser),
386 file_exists(ConParser).
387
388 handle_parser_exception(Exception) :-
389 ? handle_parser_exception(Exception,ExAuxs,[]),
390 !,
391 throw(parse_errors(ExAuxs)).
392 handle_parser_exception(_).
393
394 handle_parser_exception(compound_exception([])) --> [].
395 handle_parser_exception(compound_exception([Ex|MoreEx])) -->
396 handle_parser_exception(Ex),
397 handle_parser_exception(compound_exception(MoreEx)).
398 % Non-list version of parse_exception is handled in handle_parser_exception_aux.
399 % (Note: The non-list version is no longer generated by the parser -
400 % see comments on handle_console_parser_result below.)
401 handle_parser_exception(parse_exception([],_Msg)) --> [].
402 handle_parser_exception(parse_exception([Pos|MorePos],Msg)) -->
403 [error(Msg,Pos)],
404 ? handle_parser_exception(parse_exception(MorePos,Msg)).
405 handle_parser_exception(Ex) -->
406 {handle_parser_exception_aux(Ex,ExAux)},
407 [ExAux].
408
409 handle_parser_exception_aux(parse_exception(Pos,Msg),error(SanitizedMsg,Pos)) :-
410 remove_msg_posinfo_known(Msg,SanitizedMsg).
411 handle_parser_exception_aux(io_exception(Pos,Msg),error(Msg,Pos)).
412 handle_parser_exception_aux(io_exception(Msg),error(Msg,unknown)).
413 handle_parser_exception_aux(exception(Msg),error(Msg,unknown)). % TO DO: get Pos from Java parser !
414
415 %! parse_formula(+Codes,-Tree)
416 parse_formula(Codes,Tree) :-
417 parse_x(formula,Codes,Tree).
418
419 %! parse_expression(+Codes,-Tree)
420 parse_expression(Codes,Tree) :-
421 parse_x(expression,Codes,Tree).
422
423 %! parse_predicate(+Codes,-Tree)
424 parse_predicate(Codes,Tree) :-
425 parse_x(predicate,Codes,Tree).
426
427 %! parse_substitution(+Codes,-Tree)
428 parse_substitution(Codes,Tree) :-
429 parse_x(substitution,Codes,Tree).
430
431 % parse in the context of particular files and position within the file (e.g., VisB JSON file)
432
433 parse_at_position_in_file(Kind,Codes,Tree,Span,Filenumber) :- Span \= unknown,
434 %format('Parse @ ~w~n ~s~n',[Span,Codes]),
435 extract_line_col_for_b_parser(Span,Line,Col),!,
436 parse_at_position_in_file2(Kind,Codes,Tree,Filenumber,Line,Col).
437 parse_at_position_in_file(Kind,Codes,Tree,_,_) :-
438 parse_x(Kind,Codes,Tree).
439
440 parse_at_position_in_file2(Kind,Codes,Tree,Filenumber,Line,Col) :-
441 (Kind=expression -> true ; Kind=formula),
442 % special case to avoid setting parser options if parser not called in parse_x !
443 parse_simple_codes(Codes,Filenumber,Line,Col,AST),!,
444 Tree=AST.
445 parse_at_position_in_file2(Kind,Codes,Tree,Filenumber,Line,Col) :-
446 (Line \= 1 -> try_set_parser_option_nc(startLineNumber,Line,_OldLine)
447 ; true), % default in ParsingBehaviour.java: 1
448 (Col \= 1 -> try_set_parser_option_nc(startColumnNumber,Col,_OldCol)
449 ; true), % default in ParsingBehaviour.java: 1
450 (integer(Filenumber) -> Fnr=Filenumber ; format('Invalid filenumber : ~w~n',[Filenumber]), Fnr = -1),
451 try_set_parser_option(defaultFileNumber,Fnr,OldFile),
452 % Note: Filenumber will be used in AST, but parse errors will have null as filename
453 % format('Parsing at line ~w col ~w in file ~w (old ~w:~w in ~w)~n',[Line,Col,Filenumber,OldLine,OldCol,OldFile]),
454 call_cleanup(parse_y(Kind,Codes,Tree),
455 (%reset_old_parser_option_value(startLineNumber,Line,OldLine), % not required anymore, is now volatile
456 %reset_old_parser_option_value(startColumnNumber,Col,OldCol), % not required anymore, is now volatile
457 % TODO: should we check at startup whether the parser has volatilePosOptions feature?
458 reset_old_parser_option_value(defaultFileNumber,Filenumber,OldFile))).
459
460 extract_line_col_for_b_parser(Span,Line,Col1) :-
461 extract_line_col(Span,Line,Col,_EndLine,_EndCol),
462 Col1 is Col+1. % the BParser starts column numbering at 1
463
464 set_default_filenumber(Filenumber,OldFile) :- try_set_parser_option(defaultFileNumber,Filenumber,OldFile).
465 reset_default_filenumber(Filenumber,OldFile) :- reset_old_parser_option_value(defaultFileNumber,Filenumber,OldFile).
466
467 %! parse(+Kind,+Codes,-Tree)
468 parse(Kind,Codes,Tree) :- parse_x(Kind,Codes,Tree).
469
470 %! parse_temporal_formula(+Kind,+LanguageExtension,+Formula,-Tree)
471 parse_temporal_formula(Kind,LanguageExtension,Formula,Tree) :-
472 write_to_codes(Formula,CodesWithNewlines),
473 % Java parser expects only one line of input -> remove newlines
474 cleanup_newlines(CodesWithNewlines,Codes),
475 get_console_parser(Stream,Out,Err),
476 send_definitions(Stream),
477 format(Stream,'~s', [Kind]), nl(Stream),
478 format(Stream,'~s', [LanguageExtension]), nl(Stream),
479 format(Stream,'~s',[Codes]), nl(Stream),
480 flush_output(Stream),
481 % format('Parsing temporal formula, kind=~s, lge=~s, formula="~s"~n',[Kind,LanguageExtension,Codes]),
482 read_line(Stream,CodesIn), % TODO: Improve feedback from java!
483 catch(my_read_from_codes(CodesIn,Tree,Stream,Err),_,throw(parse_errors([error(exception,none)]))),
484 display_pending_outputs(Out,user_output).
485
486 % throws parse_errors(Errors) in case of syntax errors
487 load_b_machine_as_term(Filename, Machine,Options) :- %print(load_b_machine(Filename)),nl,
488 prob_filename(Filename, ProBFile),
489 debug_println(9,prob_filename(Filename,ProBFile)),
490 ( get_preference(jvm_parser_force_parsing,false),
491 dont_need_compilation(Filename,ProBFile,Machine,LoadResult,Options) ->
492 % no compilation is needed, .prob file was loaded
493 release_parser_if_requested(Options),
494 (LoadResult=loaded -> debug_println(20,'.prob file up-to-date')
495 ; print_error('*** Loading failed *** '),nl,fail)
496 ; % we need to parse and generate .prob file
497 (debug:debug_mode(on) ->
498 time_with_msg('generating .prob file with Java parser',call_console_parser(Filename,ProBFile))
499 ; call_console_parser(Filename,ProBFile)
500 ),
501 release_parser_if_requested(Options),
502 load_b_machine_probfile_as_term(ProBFile, Options, Machine)
503 ).
504 release_parser_if_requested(Options) :- (member(release_java_parser,Options) -> release_console_parser ; true).
505
506 % converts the filename of the machine into a filename for the parsed machine
507 prob_filename(Filename, ProB) :-
508 split_filename(Filename,Basename,_Extension),
509 safe_atom_chars(Basename,BasenameC,prob_filename1),
510 append(BasenameC,['.','p','r','o','b'],ProBC),
511 safe_atom_chars(ProB,ProBC,prob_filename2),!.
512 prob_filename(Filename, ProB) :-
513 add_failed_call_error(prob_filename(Filename,ProB)),fail.
514
515 check_version_and_read_machine(Filename,ProBFile, ProbTime, Version, GitSha, Machine,Options) :-
516 (Version='$UNKNOWN'
517 -> add_warning(parsercall,'*** Unknown parser version number. Trying to load parsed file: ',ProBFile)
518 /* keep CheckVersionNr as variable */
519 ; CheckVersionNr=Version),
520 read_machine_term_from_file(ProBFile,prob_parser_version(CheckVersionNr,GitSha),
521 [check_if_up_to_date(Filename,ProbTime)|Options],Machine).
522
523 read_machine_term_from_file(ProBFile,VersionTerm,Options,CompleteMachine) :-
524 (debug:debug_mode(on)
525 -> time_with_msg('loading .prob file',
526 read_machine_term_from_file_aux(ProBFile,VersionTerm,Options,CompleteMachine))
527 ; read_machine_term_from_file_aux(ProBFile,VersionTerm,Options,CompleteMachine)).
528
529 read_machine_term_from_file_aux(ProBFile,VersionTerm,Options,complete_machine(MainName,Machines,Files)) :-
530 open_probfile(ProBFile,Options,Stream,Opt2),
531 call_cleanup(( safe_read_term(Stream,Opt2,ProBFile,parser_version,VersionTermInFile),
532 debug_format(9,'Parser version term in file: ~w~n',[VersionTermInFile]),
533 same_parser_version(VersionTermInFile,VersionTerm), % CHECK correct version
534 read_machines(Stream,ProBFile,Opt2,Machines,MainName,Files),
535 (var(MainName)
536 -> add_internal_error('Missing classical_b fact',ProBFile), MainName=unknown,Files=[]
537 ; true)
538 ),
539 close(Stream)).
540
541 % open a .prob file:
542 open_probfile(ProBFile,Options,NewStream,NewOptions) :-
543 open(ProBFile, read, Stream),
544 file_property(ProBFile,size_in_bytes,Size),
545 check_prob_file_not_empty(Stream,Size,ProBFile,Options),
546 peek_code(Stream,Code),
547 open_probfile_aux(Code,Size,Stream,ProBFile,Options,NewStream,NewOptions).
548
549 open_probfile_aux(Code,_,Stream,ProBFile,Options,NewStream,NewOptions) :-
550 fastrw_start_code(Code),!,
551 close(Stream),
552 add_message(parsercall,'Reading .prob file using fastrw library: ',ProBFile),
553 open(ProBFile, read, NewStream, [type(binary)]),
554 % delete(use_fastread)
555 NewOptions = [use_fastrw|Options].
556 open_probfile_aux(Code,Size,Stream,ProBFile,Options,Stream,NewOptions) :-
557 check_prob_file_first_code(Code,Stream,ProBFile,Options),
558 update_options(Options,Size,NewOptions).
559
560 % automatically use fastread if file large
561 update_options(Options,Size,Opt2) :- nonmember(use_fastread,Options),
562 nonmember(use_fastrw,Options),
563 Size>1000000, % greater than 1 MB
564 !, Opt2 = [use_fastread|Options],
565 debug_println(19,automatically_using_fastread(Size)).
566 update_options(Opts,_,Opts).
567
568 % check if the file starts out in an expected way
569 check_prob_file_not_empty(Stream,Size,ProBFile,Options) :- Size=<0,!,
570 close(Stream),
571 (member(check_if_up_to_date(_,_),Options)
572 -> add_warning(parsercall,'Re-running parser as .prob file is empty: ',ProBFile)
573 % due to possible crash or CTRL-C of previous parser run
574 ; add_internal_error('Generated .prob file is empty',ProBFile)
575 ),fail.
576 check_prob_file_not_empty(_,_,_,_).
577
578 % check first character code
579 check_prob_file_first_code(Code,Stream,ProBFile,Options) :-
580 (valid_start_code(Code) -> true
581 ; fastrw_start_code(Code)
582 -> close(Stream),
583 % we need to do: open(ProBFile,read,S,[type(binary)]),
584 (member(check_if_up_to_date(_,_),Options)
585 -> add_warning(parsercall,'Re-running parser as .prob file seems to be in new fast-rw format: ',ProBFile)
586 ; add_error(parsercall,'Cannot load .prob file; it seems to be in new fast-rw format:',ProBFile)
587 ),
588 fail
589 ; add_message(parsercall,'Strange start character code in .prob file: ',[Code]) % probably syntax error will happen
590 ).
591
592 :- if(current_prolog_flag(dialect, swi)).
593 fastrw_start_code(C) :- fastrw_start_code_swi(C).
594 :- else.
595 fastrw_start_code(C) :- fastrw_start_code_sicstus(C).
596 :- endif.
597
598 fastrw_start_code_sicstus(0'D). % typical start DS...
599
600 fastrw_start_code_swi(C) :- platform_is_64_bit -> fastrw_start_code_swi_64(C) ; fastrw_start_code_swi_32(C).
601 fastrw_start_code_swi_64(98). % b / 0x62, base header for 64bit
602 fastrw_start_code_swi_64(114). % r / 0x72, base header + ground for 64bit
603 fastrw_start_code_swi_64(118). % v / 0x76, int fast path for 64bit
604 fastrw_start_code_swi_64(122). % z / 0x7a, atom fast path for 64bit
605 fastrw_start_code_swi_32(97). % a / 0x61, base header for 32bit
606 fastrw_start_code_swi_32(113). % q / 0x71, base header + ground for 32bit
607 fastrw_start_code_swi_32(117). % u / 0x75, int fast path for 32bit
608 fastrw_start_code_swi_32(121). % y / 0x79, atom fast path for 32bit
609
610 valid_start_code(0'p). % from parser_version(_) term
611 valid_start_code(37). % percentage sign; appears when parser called with verbose flag
612 valid_start_code(47). % start of comment slash (inserted by user)
613 valid_start_code(39). % ' (inserted by user)
614 valid_start_code(32). % whitespace (inserted by user)
615 valid_start_code(8). % tab (inserted by user)
616 valid_start_code(10). % lf (inserted by user)
617 valid_start_code(13). % cr (inserted by user)
618
619 % --------------------
620
621 % use various read_term mechanisms depending on Options
622
623 safe_read_term(Stream,Options,File,Expecting,T) :-
624 catch(
625 safe_read_term2(Options,Stream,File,Expecting,T),
626 error(permission_error(_,_,_),ERR),
627 (
628 ajoin(['Permission error in .prob file trying to read ',Expecting,' term in ',File,':'],Msg),
629 add_internal_error(Msg,ERR),
630 fail
631 )).
632
633 :- use_module(tools_fastread,[read_term_from_stream/2, fastrw_read/3]).
634
635 safe_read_term2([use_fastrw|_],Stream,File,Expecting,Term) :- !,
636 fastrw_read(Stream,Term,Error),
637 (Error=false -> true
638 ; ajoin(['.prob (fastrw) file has error in ',Expecting,' term:'],Msg),
639 add_internal_error(Msg,File),
640 fail
641 ), functor(Term,F,N),debug_println(19,fast_read_term(F,N)).
642 safe_read_term2([use_fastread|_],Stream,File,Expecting,Term) :- !,
643 (read_term_from_stream(Stream,Term) -> true
644 ; ajoin(['.prob file has Prolog syntax error in ',Expecting,' term:'],Msg),
645 add_internal_error(Msg,File), fail
646 ).
647 safe_read_term2([_|Opts],Stream,File,Expecting,T) :- !,
648 safe_read_term2(Opts,Stream,File,Expecting,T).
649 safe_read_term2([],Stream,File,Expecting,T) :- % use regular SICStus Prolog reader
650 catch(read(Stream,T), error(E1,E2), (
651 ajoin(['.prob file (',File,') has error in ',Expecting,' term:'],Msg),
652 add_error(parser_call,Msg,error(E1,E2)),
653 fail
654 )).
655
656
657
658 % ------------------
659
660 % check if file was parsed with same parser version as currently in use by ProB
661 same_parser_version(parser_version(V), prob_parser_version(VB,GitSha)) :- !,
662 (V=VB -> true ; V=GitSha).
663 same_parser_version(end_of_file,_) :- !, debug_format(19,'.prob file is empty~n',[]).
664 same_parser_version(T,_) :-
665 add_internal_error('.prob file contains illegal parser_version term:',T),fail.
666
667 load_b_machine_list_of_facts_as_term(Facts,Machine) :-
668 read_machine_term_from_list_of_facts(Facts,_,Machine).
669 read_machine_term_from_list_of_facts(Facts,VersionTerm,complete_machine(MainName,Machines,FileList)) :-
670 (select(parser_version(VERS),Facts,F2) -> VersionTerm = parser_version(VERS)
671 ; add_internal_error('No parser_version available',read_machine_from_list_of_facts),
672 F2=Facts, VersionTerm = unknown),
673 (select(classical_b(MainName,FileList),F2,F3) -> true
674 ; add_internal_error('No classical_b file information available',read_machine_from_list_of_facts),
675 fail),
676 debug_println(9,loading_classical_b(VersionTerm,MainName,FileList)),
677 include(is_machine_term,F3,F4),
678 maplist(get_machine_term,F4,Machines).
679
680 is_machine_term(machine(_M)).
681 get_machine_term(machine(M),M).
682
683 load_b_machine_probfile_as_term(ProBFile, Machine) :-
684 load_b_machine_probfile_as_term(ProBFile, [], Machine).
685
686 load_b_machine_probfile_as_term(ProBFile, Options, Machine) :-
687 debug_println(9,consulting(ProBFile)),
688 ( read_machine_term_from_file(ProBFile,_VersionTerm,Options,Machine) -> true
689 ; add_error(parsercall,'Failed to read parser output: wrong format?',ProBFile),fail).
690
691 read_machines(S,ProBFile,Options,Machines,MainName,Files) :-
692 safe_read_term(S,Options,ProBFile,machine,Term),
693 %, write_term(Term,[max_depth(5),numbervars(true)]),nl,
694 ( Term == end_of_file ->
695 Machines = []
696 ; Term = classical_b(M,F) ->
697 ((M,F)=(MainName,Files) -> true ; add_internal_error('Inconsistent classical_b fact: ',classical_b(M,F))),
698 (member(check_if_up_to_date(MainFileName,ProbTime),Options)
699 -> debug_format(9,'Checking if .prob file up-to-date for subsidiary files and if it was generated for ~w~n',[MainFileName]),
700 all_older(Files, ProbTime), % avoid reading rest if subsidiary source files not all_older !
701 (Files = [File1|_],
702 same_file_name(MainFileName,File1) -> true
703 ; format('Re-parsing: .prob file created for different source file:~n ~w~n',[MainFileName]),
704 % this can happen, e.g., when we have M.def and M.mch and we previously loaded the other file
705 Files = [File1|_],
706 format(' ~w~n',[File1]),
707 fail
708 )
709 ; true),
710 read_machines(S,ProBFile,Options,Machines,MainName,Files)
711 ; Term = machine(M) ->
712 Machines = [M|Mrest],
713 read_machines(S,ProBFile,Options,Mrest,MainName,Files)
714 ).
715
716
717 % checks if all files that the prob-file depends on
718 % are older than the prob-file
719 dont_need_compilation(Filename,ProB,Machine,LoadResult,Options) :-
720 file_exists(Filename),
721 catch( ( get_parser_version(Version,GitSha),
722 file_property(Filename, modify_timestamp, BTime),
723 debug_format(9, 'Parser Version: ~w, Filename Timestamp: ~w : ~w~n',[Version,Filename,BTime]),
724 file_exists(ProB), % the .prob file exists
725 file_property(ProB, modify_timestamp, ProbTime),
726 debug_format(9, '.prob Timestamp: ~w : ~w~n',[ProB,ProbTime]),
727 % print(time_stamps(ProB,ProbTime,Filename,BTime)),nl,
728 BTime < ProbTime, % .mch file is older than .prob file
729 file_property(ProB,size_in_bytes,Size),
730 (Size>0 -> true
731 ; debug_mode(on),
732 add_message(parsercall,'.prob file is empty; parsing again',ProB),
733 % possibly due to crash or error before, cf second run of test 254
734 fail),
735 check_version_and_read_machine(Filename,ProB, ProbTime, Version, GitSha, Machine,Options),
736 %Machine = complete_machine(_,_,_),
737 LoadResult = loaded),
738 error(A,B),
739 (debug_println(9,error(A,B)),
740 (A=resource_error(memory)
741 -> add_error(load_b_machine,'Insufficient memory to load file.\nTry starting up ProB with more memory\n (e.g., setting GLOBALSTKSIZE=500M before starting ProB).'),
742 LoadResult=A
743 ; fail))).
744
745 % check that all included files are older than the .prob file (ProbTime):
746 all_older([],_).
747 all_older([File|Rest],ProbTime) :-
748 (file_exists(File)
749 -> file_property(File, modify_timestamp, BTime),
750 debug_format(9,' Subsidiary File Timestamp: ~w:~w~n',[File,BTime]),
751 ( BTime < ProbTime -> true
752 ; format('File has changed : ~w : ~w~n',[File,BTime]),
753 fail )
754 ; virtual_dsl_file(File) -> debug_format(9,'Virtual file generated by DSL translator: ~w~n',[File])
755 ; debug_format(20,'File does not exist anymore: ~w; calling parser.~n',[File]),fail),
756 all_older(Rest,ProbTime).
757
758 virtual_dsl_file(File) :- atom_codes(File,Codes),
759 Codes = [95|_], % file name starts with _ underscore
760 nonmember(47,Codes), % no slash
761 nonmember(92,Codes). % no backslash
762
763 :- use_module(system_call).
764
765 get_extra_args_list(ExtraArgs) :-
766 get_preference(jvm_parser_additional_args,ExtraArgsStr),
767 ExtraArgsStr \= '',
768 atom_codes(ExtraArgsStr,C),
769 split_chars(C," ",CA),
770 maplist(atom_codes,ExtraArgs,CA).
771
772 jvm_options -->
773 ({get_preference(jvm_parser_heap_size_mb,Heap), Heap>0} ->
774 {ajoin(['-Xmx',Heap,'m'],HeapOpt)},
775 [HeapOpt]
776 ;
777 % comment in to simulate low-memory situations
778 % use -Xmx221500000m instead to force exception and test ProB's response
779 [] %['-Xmx20m']
780 ),
781
782 ({get_extra_args_list(ExtraArgs)} ->
783 {debug_format(19,'Using additional arguments for JVM (JVM_PARSER_ARGS): ~w~n',[ExtraArgs])},
784 ExtraArgs
785 % use the former LARGE_JVM / use_large_jvm_for_parser by default
786 % if we are running on a 64-bit system
787 % FIXME Is it intentional that this option is not added if JVM_PARSER_ARGS is set?
788 ; {platform_is_64_bit} -> ['-Xss5m'] % default stacksize; set to -Xss150k to mimic low stack setting
789 ; []
790 ).
791
792 parser_jvm_options -->
793 {get_PROBPATH(PROBPATH), atom_concat('-Dprob.stdlib=', PROBPATH, Stdlibpref)},
794 [Stdlibpref],
795 jvm_options.
796
797
798 % we could do something like this: or allow user to provide list of JVM options
799 %get_gc_options([]) :- !,get_preference(jvm_parser_aggressive_gc,true).
800 %get_gc_options(['-XX:GCTimeRatio=19', '-XX:MinHeapFreeRatio=20', '-XX:MaxHeapFreeRatio=30']).
801 % see https://stackoverflow.com/questions/30458195/does-gc-release-back-memory-to-os
802
803 parser_cli_options -->
804 %% ['-v'], % comment in for verbose, -time for timing info
805 ({debug_mode(on)} -> ['-v', '-time'] ; []),
806
807 % useful for very large data validation machines
808 ({get_preference(jvm_parser_position_infos,true)} -> ['-lineno'] ; []),
809
810 %( get_preference(jvm_parser_fastrw,false) ; parser_version_at_least(2,12,0) )
811 % we cannot call: parser_version_at_least(2,12,0) as parser not yet started
812 % older parsers were printing comments into the binary fastrw output; TODO: perform check later
813 ({get_preference(jvm_parser_fastrw,true)} -> ['-fastprolog'] ; ['-prolog']),
814
815 % enable swi support when required
816 % does not work on older parsers and version check is inaccessible here
817 % ({current_prolog_flag(dialect, swi)} -> ['-swi'] ; []),
818
819 % -compactpos enables new p3, p4, p5 position terms and disables node numbering
820 ['-prepl', '-compactpos'].
821
822 parser_command_args(native(NativeCmd), NativeCmd) -->
823 parser_jvm_options,
824 parser_cli_options.
825 parser_command_args(java_jar(NativeCmd,JarPath), NativeCmd) -->
826 parser_jvm_options,
827 ['-jar', JarPath],
828 parser_cli_options.
829
830 % ensure that the console Java process is running
831 ensure_console_parser_launched :-
832 catch(parse_formula("1",_), E, (
833 add_internal_error('Cannot launch console parser (probcliparser.jar)',E),
834 fail
835 )).
836
837 parser_is_launched :-
838 java_parser_process(_,_,_,_).
839
840
841 % TO DO: also store output stream for debugging messages
842 get_console_parser(Stream,Out,Err) :-
843 java_parser_process(PID,Stream,Out,Err),
844 % On SICStus, calling is_process seams to be unreliable (if the process has crashed)
845 % and process_wait does not always work either,
846 % so first check if in and output streams are still available.
847 \+ at_end_of_stream(Stream),
848 % On SWI, at_end_of_stream doesn't detect broken pipes,
849 % so additionally also check that the process has not exited/crashed.
850 process_wait(PID,timeout,[timeout(0)]),
851 !,
852 (at_end_of_stream(Err)
853 -> add_error(parsercall,'Java process not running'),
854 read_lines_and_add_as_error(Stream)
855 ; true).
856 get_console_parser(Stream,Out,Err) :-
857 clear_old_console_parsers,
858 get_java_command_for_parser(ParserCmd),
859 phrase(parser_command_args(ParserCmd, NativeCmd), FullArgs),
860 debug_println(19,launching_java_console_parser(NativeCmd,FullArgs)),
861 debug_print_system_call(NativeCmd,FullArgs),
862 system_call_keep_open(NativeCmd,FullArgs,PID,_In,Out,Err,[]), % note: if probcliparser.jar does not exist we will not yet get an error here !
863 debug_println(9,java_console_parser_launched(PID)),
864 % read first line to get port number
865 safe_read_line(Out,Err,1,[],PortTerm),
866 connect_to_console_parser_on_port(PortTerm,PID,Out,Err,Stream),
867 !.
868 get_console_parser(_,_,_) :- missing_parser_diagnostics, fail.
869
870
871
872
873 connect_to_console_parser_on_port(PortTerm,PID,Out,Err,Stream) :-
874 catch(
875 socket_client_open('':PortTerm, Stream, [type(text),encoding(utf8)]),
876 Exc, %error(system_error,system_error(E)), % SPIO_E_NET_HOST_NOT_FOUND
877 (
878 ajoin(['Exception while opening parser socket on port ', PortTerm,
879 ' (possibly an error occurred during startup of the parser): '],Msg),
880 add_internal_error(Msg,Exc),
881 % e.g., not enough memory to start parser and wait for socket connection
882 read_lines_and_add_as_error(Err), % try and read additional info;
883 % if we set the stack size to be very small (-Xss20k) we get: Error: Could not create the Java Virtual Machine
884 fail
885 )),
886 assertz(java_parser_process(PID,Stream,Out,Err)).
887
888 % connect to a separately started parser
889 % allow to connect to a separately started java command line parser (java -jar probcliparser.jar -prepl)
890 connect_to_external_console_parser_on_port(PortNumber) :-
891 clear_old_console_parsers,
892 format('Trying to connect to external parser on port ~w~n',[PortNumber]),
893 Out=user_input, Err=user_input,
894 (connect_to_console_parser_on_port(PortNumber,external_process,Out,Err,_)
895 -> format('Connected to parser on port ~w~n',[PortNumber])
896 ; add_error(parsercall,'Could not connect to parser on port:',PortNumber)
897 ).
898
899 clear_old_console_parsers :-
900 retract(java_parser_process(PID,_,_,_)),
901 parser_process_release(PID),
902 fail.
903 clear_old_console_parsers.
904
905 parser_process_release(external_process) :- !.
906 parser_process_release(PID) :- process_release(PID).
907
908 % useful to try and free up memory
909 % alternatively we could add some JVM options: -XX:GCTimeRatio=19 -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=30
910 % see https://stackoverflow.com/questions/30458195/does-gc-release-back-memory-to-os
911 release_console_parser :-
912 (java_parser_process(PID,Stream,_,_),
913 PID \= external_process
914 -> format('Releasing Java parser id=~w (note: access to DEFINITIONS is lost)~n',[PID]),
915 write(Stream,'halt'), nl(Stream),
916 flush_output(Stream), % handled in Java in runPRepl in CliBParser.java;
917 retract(java_parser_process(PID,_,_,_)),
918 parser_process_release(PID) % or should we call process_kill ?
919 %process_kill(PID)
920 % Note: parser maybe launched again, but then not have access to DEFINITIONS
921 ; true).
922
923 :- use_module(runtime_profiler,[profile_single_call/3]).
924 call_console_parser(Filename, ProB) :-
925 profile_single_call('$parsing',unknown,parsercall:call_console_parser2(Filename, ProB)).
926 call_console_parser2(Filename, ProB) :-
927 update_jvm_parser_preferences,
928 get_console_parser(Stream,Out,Err),
929
930 % path to the .prob file
931 replace_windows_path_backslashes(ProB,ProBW),
932 % the input file
933 replace_windows_path_backslashes(Filename,FilenameW),
934 % call PREPL 'machine' command
935 debug_format(4,'PREPL command: machine~n~w~n~w~n',[FilenameW,ProBW]),
936 format(Stream,'machine~n~w~n~w~n',[FilenameW,ProBW]), % tell parser to write output to ProBW .prob file
937 flush_output(Stream),
938
939 %% WARNING: if the java parser writes too much output on the out stream it will block
940 %% until its output is read and we have a deadlock !
941 %% hence we use safe_polling_read_line
942 safe_polling_read_line(Stream,Out,Err,1,[],Term),
943
944 display_pending_outputs(Out,user_output),
945 handle_console_parser_result(Term,Err).
946
947
948 safe_read_line(Out,Err,LineNr,SoFar,Term) :-
949 safe_read_line_aux(read_line,Out,Err,LineNr,SoFar,Term).
950
951 safe_read_line_if_ready(Out,Err,LineNr,SoFar,Term) :-
952 safe_read_line_aux(read_line_if_ready,Out,Err,LineNr,SoFar,Term).
953
954 % a version that will check every second if there is output to be read
955 safe_polling_read_line(Stream,_Out,Err,LineNr,SoFar,Term) :-
956 stream_ready_to_read(Stream,2),!, % try for two seconds
957 safe_read_line_aux(read_line,Stream,Err,LineNr,SoFar,Term).
958 safe_polling_read_line(Stream,Out,Err,LineNr,SoFar,Term) :-
959 % this should normally not happen unless we have a debugging version of the parser
960 debug_format(19,'Parser not responded yet, trying to read its output~n',[]),
961 display_pending_outputs(Out,user_output),
962 read_lines_and_add_as_error(Err),
963 safe_polling_read_line(Stream,Out,Err,LineNr,SoFar,Term).
964
965 safe_read_line_aux(Pred,Out,Err,LineNr,SoFar,Term) :-
966 catch(call(Pred,Out,Codes),Exception, % read another line
967 (add_error(parsercall,'Exception while reading next line: ',Exception),
968 read_lines_and_add_as_error(Err),
969 display_pending_outputs(user_error,Out),
970 throw(Exception))),
971 Codes \= end_of_file, !, % happens if parser crashed and stream is closed
972 append(SoFar,Codes,NewCodes),
973 catch(my_read_from_codes(NewCodes,Term,Out,Err),Exception,
974 safe_read_exception(Out,Err,LineNr,Exception,NewCodes,Term)).
975 safe_read_line_aux(_Pred,_Out,Err,_LineNr,CodesSoFar,_) :-
976 safe_name(T,CodesSoFar),
977 add_error(parsercall,'Unexpected error while parsing machine: ',T),
978 read_lines_and_add_as_error(Err),fail.
979
980
981 safe_read_exception(Out,_,1,_Exception,CodesSoFar,_Term) :- append("Error",_,CodesSoFar),!,
982 % probably some Java error, we do not obtain a correct Prolog term, but probably something like:
983 % "Error occurred during initialization of VM"
984 safe_name(T,CodesSoFar),
985 add_error(parsercall,'Java error while parsing machine: ',T),
986 read_lines_and_add_as_error(Out),fail.
987 safe_read_exception(Out,Err,LineNr,error(syntax_error(M),_),CodesSoFar,Term) :- LineNr<10, % avoid infinite loop in case unexpected errors occur which cannot be solved by reading more input lines
988 !,
989 %(debug:debug_mode(off) -> true ; format('Syntax error in parser result (line ~w): ~w~nTrying to read another line.~n',[LineNr,M])),
990 add_warning(parsercall,'Syntax error in parser result; trying to read another line. Line:Error = ',LineNr:M),
991 L1 is LineNr+1,
992 safe_read_line_if_ready(Out,Err,L1,CodesSoFar,Term). % try and read another line; we assume the syntax error is because the TERM is not complete yet and transmitted on multiple lines (Windows issue)
993 safe_read_exception(_,_,_LineNr,parse_errors(Errors),_CodesSoFar,_Term) :- !,
994 debug_println(4,read_parse_errors(Errors)),
995 throw(parse_errors(Errors)).
996 safe_read_exception(_,_,_LineNr,Exception,_CodesSoFar,_Term) :-
997 add_internal_error('Unexpected exception occurred during parsing: ',Exception),fail.
998 %safe_name(T,CodesSoFar), add_error_fail(parsercall,'Unexpected error while parsing machine: ',T).
999
1000 safe_name(Name,Codes) :- var(Name),Codes == end_of_file,!,
1001 %add_internal_error('Parser does not seem to be available',''),
1002 Name=end_of_file.
1003 safe_name(Name,Codes) :- number(Name),!,
1004 safe_number_codes(Name,Codes).
1005 safe_name(Name,Codes) :-
1006 catch(atom_codes(Name,Codes), E,
1007 (print('Exception during atom_codes: '),print(E),nl,nl,throw(E))).
1008
1009 safe_number_codes(Name,Codes) :-
1010 catch(number_codes(Name,Codes), E,
1011 (print('Exception during number_codes: '),print(E),nl,nl,throw(E))).
1012
1013 % Note: As of parser version 2.9.28 commit ee2592d8ca2900b4e339da973920e034dff43658,
1014 % all parse errors are reported as terms of the form
1015 % parse_exception(Positions,Msg) where Positions is a list of pos/5 terms.
1016 % The term formats preparse_exception(Tokens,Msg) (where Tokens is a list of none/0 or pos/3 terms)
1017 % and parse_exception(Pos,Msg) (where Pos is a single none/0, pos/3 or pos/5 term)
1018 % are no longer generated by the parser.
1019 % The code for handling these old term formats can probably be removed soon.
1020
1021 % see also handle_parser_exception
1022 %handle_console_parser_result(E,_) :- nl,print(E),nl,fail.
1023 handle_console_parser_result(exit(0),_) :- !.
1024 handle_console_parser_result(io_exception(Msg),_) :- !,
1025 add_error_fail(parsercall,'Error while opening the B file: ',Msg).
1026 handle_console_parser_result(compound_exception(List),ErrStream) :- !,
1027 get_compound_exceptions(List,ErrStream,ParseErrors,[]),
1028 throw(parse_errors(ParseErrors)).
1029 handle_console_parser_result(preparse_exception(Tokens,Msg),_) :- !,
1030 remove_msg_posinfo(Msg,SanitizedMsg,MsgPos),
1031 findall(error(SanitizedMsg,Pos),member(Pos,Tokens),Errors1),
1032 (Errors1 = []
1033 -> /* if there are no error tokens: use pos. info from text Msg */
1034 Errors = [error(SanitizedMsg,MsgPos)]
1035 ; Errors = Errors1),
1036 debug_println(4,preparse_exception_parse_errors(Tokens,Msg,Errors)),
1037 throw(parse_errors(Errors)).
1038 handle_console_parser_result(parse_exception([],Msg),_) :-
1039 atom(Msg), atom_codes(Msg,MC),
1040 append("StackOverflowError",_,MC),!,
1041 add_error(parsercall,'Java VM error while running parser: ',Msg),
1042 print_hint('Try increasing stack size for Java using the JVM_PARSER_ARGS preference (e.g.,"-Xss10m").'),
1043 fail.
1044 handle_console_parser_result(parse_exception(Positions,Msg),_) :-
1045 (Positions = [] ; Positions = [_|_]), !,
1046 remove_msg_posinfo(Msg,SanitizedMsg,MsgPos),
1047 findall(error(SanitizedMsg,Pos),member(Pos,Positions),Errors1),
1048 (Errors1 = []
1049 -> /* if there are no error tokens: use pos. info from text Msg */
1050 Errors = [error(SanitizedMsg,MsgPos)]
1051 ; Errors = Errors1),
1052 debug_println(4,parse_exception_parse_errors(Positions,Msg,Errors)),
1053 throw(parse_errors(Errors)).
1054 handle_console_parser_result(parse_exception(Pos,Msg),_) :- !,
1055 remove_msg_posinfo_known(Msg,SanitizedMsg), %print(sanitized(SanitizedMsg)),nl,
1056 debug_println(4,parse_exception(Pos,Msg,SanitizedMsg)),
1057 throw(parse_errors([error(SanitizedMsg,Pos)])).
1058 handle_console_parser_result(exception(Msg),_) :- !,
1059 %add_error(bmachine,'Error in the classical B parser: ', Msg),
1060 remove_msg_posinfo(Msg,SanitizedMsg,Pos),
1061 debug_println(4,exception_in_parser(Msg,SanitizedMsg,Pos)),
1062 throw(parse_errors([error(SanitizedMsg,Pos)])).
1063 handle_console_parser_result(end_of_file,Err) :- !,
1064 % probably NullPointerException or similar in parser; no result on StdOut
1065 debug_println(9,end_of_file_on_parser_output_stream),
1066 format(user_error,'Detected abnormal termination of B Parser~n',[]), % print in case we block
1067 read_line_if_ready(Err,Err1),
1068 (Err1=end_of_file -> Msg = 'Abnormal termination of B Parser: EOF on streams'
1069 ; append("Abnormal termination of B Parser: ",Err1,ErrMsgCodes),
1070 safe_name(Msg,ErrMsgCodes),
1071 read_lines_and_add_as_error(Err) % also show additional error infos
1072 ),
1073 throw(parse_errors([error(Msg,none)])).
1074 handle_console_parser_result(compound_exception(Exs),_) :- !,
1075 maplist(handle_parser_exception_aux,Exs,ExAuxs),
1076 debug_println(4,compound_exception(Exs,ExAuxs)),
1077 throw(parse_errors(ExAuxs)).
1078 handle_console_parser_result(Term,_) :- !,
1079 write_term_to_codes(Term,Text,[]),
1080 safe_name(Msg,Text),
1081 %add_error(bmachine,'Error in the classical B parser: ', Msg),
1082 remove_msg_posinfo(Msg,SanitizedMsg,Pos),
1083 debug_println(4,unknown_error_term(Term,SanitizedMsg,Pos)),
1084 throw(parse_errors([error(SanitizedMsg,Pos)])).
1085
1086 % get all compound exceptions as a single result to be thrown once later:
1087 get_compound_exceptions([],_) --> [].
1088 get_compound_exceptions([Err1|T],ErrStream) -->
1089 {handle_and_catch(Err1,ErrStream,ParseErrors) },
1090 ParseErrors,
1091 get_compound_exceptions(T,ErrStream).
1092
1093 handle_and_catch(Exception,ErrStream,ParseErrors) :-
1094 catch(
1095 (handle_console_parser_result(Exception,ErrStream) -> ParseErrors=[] ; ParseErrors=[]),
1096 parse_errors(Errors1),
1097 ParseErrors=Errors1).
1098
1099 % now replaced by remove_msg_posinfo:
1100 %extract_position_info(Text,pos(Row,Col,Filename)) :-
1101 % atom_codes(Text,Codes),
1102 % epi(Row,Col,Filename,Codes,_),!.
1103 %extract_position_info(_Text,none).
1104
1105 :- assert_must_succeed((parsercall:epi(R,C,F,"[2,3] xxx in file: /usr/lib.c",[]), R==2,C==3,F=='/usr/lib.c')).
1106 :- assert_must_succeed((parsercall:epi(R,C,F,"[22,33] xxx yyy ",_), R==22,C==33,F=='unknown')).
1107
1108 % we expect error messages to start with [Line,Col] information
1109 epi(Row,Col,Filename) --> " ",!,epi(Row,Col,Filename).
1110 epi(Row,Col,Filename) --> "[", epi_number(Row),",",epi_number(Col),"]",
1111 (epi_filename(Filename) -> [] ; {Filename=unknown}).
1112 epi_number(N) --> epi_numbers(Chars),{safe_number_codes(N,Chars)}.
1113 epi_numbers([C|Rest]) --> [C],{is_number(C)},epi_numbers2(Rest).
1114 epi_numbers2([C|Rest]) --> [C],{is_number(C),!},epi_numbers2(Rest).
1115 epi_numbers2("") --> !.
1116 is_number(C) :- member(C,"0123456789"),!.
1117 epi_filename(F) --> " in file: ",!,epi_path2(Chars),{safe_name(F,Chars)}.
1118 epi_filename(F) --> [_], epi_filename(F).
1119 epi_path2([C|Rest]) --> [C],!,epi_path2(Rest). % assume everything until the end is a filename
1120 epi_path2([]) --> [].
1121
1122 :- assert_must_succeed((parsercall:remove_rowcol(R,C,"[22,33] xxx yyy ",_), R==22,C==33)).
1123 % remove parser location info from message to avoid user clutter
1124 remove_rowcol(Row,Col) --> " ",!, remove_rowcol(Row,Col).
1125 remove_rowcol(Row,Col) --> "[", epi_number(Row),",",epi_number(Col),"]".
1126
1127 :- assert_must_succeed((parsercall:remove_filename(F,C,"xxx yyy in file: a.out",R), F == 'a.out', C == "xxx yyy", R==[])).
1128 remove_filename(F,[]) --> " in file: ",!,epi_path2(Chars),{safe_name(F,Chars)}.
1129 remove_filename(F,[C|T]) --> [C], remove_filename(F,T).
1130
1131 :- assert_must_succeed((parsercall:remove_filename_from_codes("xxx yyy in file: a.out",F,C), F == 'a.out', C == "xxx yyy")).
1132 :- assert_must_succeed((parsercall:remove_filename_from_codes("xxx yyy zzz",F,C), F == 'unknown', C == "xxx yyy zzz")).
1133 remove_filename_from_codes(Codes,F,NewCodes) :-
1134 (remove_filename(F,C1,Codes,C2) -> append(C1,C2,NewCodes) ; F=unknown, NewCodes=Codes).
1135
1136 % obtain position information from a message atom and remove the parts from the message at the same time
1137 remove_msg_posinfo_known(Msg,NewMsg) :- remove_msg_posinfo(Msg,NewMsg,_,pos_already_known).
1138 remove_msg_posinfo(Msg,NewMsg,Pos) :- remove_msg_posinfo(Msg,NewMsg,Pos,not_known).
1139 remove_msg_posinfo(Msg,NewMsg,Pos,AlreadyKnown) :- %print(msg(Msg,AlreadyKnown)),nl,
1140 atom_codes(Msg,Codes),
1141 (remove_rowcol(Row,Col,Codes,RestCodes)
1142 -> Pos=pos(Row,Col,Filename),
1143 remove_filename_from_codes(RestCodes,Filename,NewCodes)
1144 ; AlreadyKnown==pos_already_known ->
1145 Pos = none,
1146 remove_filename_from_codes(Codes,_Filename2,NewCodes)
1147 ;
1148 NewCodes=Codes, Pos=none
1149 % do not remove filename: we have not found a position and cannot return the filename
1150 % see, e.g., public_examples/B/Tickets/Hansen27_NestedMchErr/M1.mch
1151 ),
1152 !,
1153 atom_codes(NewMsg,NewCodes).
1154 remove_msg_posinfo(M,M,none,_).
1155
1156
1157 % ----------------------
1158
1159 parser_command_supported(_) :-
1160 prob2_call_back_available(_), % TODO: support at least setoption in parser callback in ProB2
1161 !,
1162 fail.
1163 parser_command_supported(Command) :-
1164 parser_version_at_least(2,12,2),
1165 !,
1166 query_command_supported(Command,true).
1167 parser_command_supported(Command) :-
1168 (Command = fastprolog
1169 ; Command = compactpos
1170 ; Command = verbose
1171 ; Command = checkname
1172 ; Command = lineno
1173 ),
1174 !,
1175 parser_version_at_least(2,12,0).
1176
1177 :- dynamic query_command_supported_cached/2.
1178
1179 query_command_supported(Command,Res) :-
1180 query_command_supported_cached(Command,Res),
1181 !.
1182 query_command_supported(Command,Res) :-
1183 get_console_parser(Stream,_Out,Err),
1184 !,
1185 write(Stream,'commandsupported'), nl(Stream),
1186 write(Stream,Command), nl(Stream),
1187 flush_output(Stream),
1188 read_line(Stream,CodesIn),
1189 my_read_from_codes(CodesIn,Res,Stream,Err),
1190 assertz(query_command_supported_cached(Command,Res)).
1191
1192 % java_parser_version(VersionStr) :- java_parser_version(VersionStr,_,_,_,_,_).
1193
1194 parser_version_at_least(RV1,RV2,RV3) :-
1195 get_parser_version(_,V1,V2,V3,_,_),
1196 lex_leq([RV1,RV2,RV3],[V1,V2,V3]).
1197
1198 lex_leq([V1|_],[VV1|_]) :- number(VV1), % with old parsers this can be '?'
1199 V1 < VV1,!.
1200 lex_leq([V1|T1],[V1|T2]) :- lex_leq(T1,T2).
1201 lex_leq([],_).
1202
1203
1204 get_parser_version(VersionStr) :- get_parser_version(VersionStr,_).
1205 get_parser_version(VersionStr,GitSha) :- get_parser_version(VersionStr,_,_,_,_,GitSha).
1206
1207 get_parser_version(VersionStr,V1,V2,V3,SNAPSHOT,GitSha) :- java_parser_version(VersionStr,V1,V2,V3,SNAPSHOT,GitSha),!.
1208 get_parser_version(VersionStr,V1,V2,V3,SNAPSHOT,GitSha) :-
1209 get_version_from_parser(VersionStr),
1210 !,
1211 ? (get_version_numbers(VersionStr,V1,V2,V3,SNAPSHOT,GitSha)
1212 -> assertz(java_parser_version(VersionStr,V1,V2,V3,SNAPSHOT,GitSha)),
1213 debug_format(19,'Parser version recognized ~w.~w.~w (SNAPSHOT=~w)~n',[V1,V2,V3,SNAPSHOT])
1214 ; assertz(java_parser_version(VersionStr,'?','?','?','?','?'))
1215 ).
1216 get_parser_version(_Vers,_V1,_V2,_V3,_SNAPSHOT,_GitSha) :-
1217 (real_error_occurred -> true % already produced error messages in get_version_from_parser
1218 ; add_error(get_parser_version,'Could not get parser version.')),
1219 %missing_parser_diagnostics, % already called if necessary by get_version_from_parser
1220 fail.
1221
1222 :- use_module(probsrc(tools),[split_atom/3,atom_to_number/2]).
1223 % newer parsers generate a version string like 2.9.27-GITSHA or 2.9.27-SNAPSHOT-GITSHA; older ones just GITSHA
1224 get_version_numbers(VersionStr,V1,V2,V3,SNAPSHOT,GitSha) :-
1225 split_atom(VersionStr,['.'],List),
1226 [AV1,AV2,AV3T] = List,
1227 split_atom(AV3T,['-'],List2),
1228 [AV3,Suffix1|T] = List2,
1229 ? atom_to_number(AV1,V1),
1230 ? atom_to_number(AV2,V2),
1231 ? atom_to_number(AV3,V3),
1232 (Suffix1 = 'SNAPSHOT' -> SNAPSHOT=true, [GitSha]=T
1233 ; T=[], SNAPSHOT=false, GitSha=Suffix1).
1234
1235
1236 get_version_from_parser(Version) :-
1237 get_console_parser(Stream,Out,Err),
1238 write(Stream,'version'), nl(Stream),
1239 flush_output(Stream),
1240 read_line(Stream,Text), % if parser cannot be started we receive end_of_file; length will fail
1241 (Text = end_of_file -> add_error(parsercall,'Could not get parser version: '),
1242 read_lines_and_add_as_error(Err),fail
1243 ; length(Text,Length),
1244 ( append("Error",_,Text)
1245 -> atom_codes(ErrMsg,Text),
1246 add_error(parsercall,'Error getting parser version: ',ErrMsg),
1247 read_lines_and_add_as_error(Stream),fail
1248 ; Length < 100 -> atom_codes(Version,Text)
1249 ; prefix_length(Text,Prefix,100),
1250 append(Prefix,"...",Full),
1251 safe_name(Msg,Full),
1252 add_error_fail(parsercall, 'B parser returned unexpected version string: ', Msg))
1253 ),
1254 display_pending_outputs(Out,user_output).
1255
1256 :- use_module(library(sockets),[socket_select/7]).
1257 % check if a stream is ready for reading
1258 stream_ready_to_read(Out) :- stream_ready_to_read(Out,1). % wait 1 second, off: wait forever
1259 stream_ready_to_read(Out,TO) :- var(Out),!,
1260 add_internal_error('Illegal stream: ',stream_ready_to_read(Out,TO)),fail.
1261 stream_ready_to_read(Out,TO) :-
1262 socket_select([],_, [Out],RReady, [],_, TO), % wait TO sec at most %print(ready(Out,RReady)),nl,
1263 RReady == [Out].
1264
1265
1266 read_lines_and_add_as_error(Out) :- read_lines_until_eof(Out,false,ErrMsgCodes,[]),
1267 (ErrMsgCodes=[] -> true
1268 ; ErrMsgCodes=[10] -> true % just a single newline
1269 ; ErrMsgCodes=[13] -> true % ditto
1270 ; safe_name(ErrMsg,ErrMsgCodes),
1271 add_error(parsercall,'Additional information: ',ErrMsg),
1272 analyse_java_error_msg(ErrMsgCodes)
1273 ).
1274
1275 % analyse error messages from the JVM; providing possible solutions:
1276 analyse_java_error_msg(ErrMsgCodes) :-
1277 append([_,"java.lang.OutOfMemoryError",_],ErrMsgCodes),!,
1278 % a typical message contains: Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
1279 % or: Exception in ...: Java heap space
1280 print_hint('Try increasing memory for Java by setting the JVM_PARSER_HEAP_MB preference.'),
1281 print_hint('You can also provide custom JVM arguments using the JVM_PARSER_ARGS preference.').
1282 analyse_java_error_msg(ErrMsgCodes) :-
1283 append([_,"java.lang.StackOverflowError",_],ErrMsgCodes),!,
1284 print_hint('Try increasing stack size for Java using the JVM_PARSER_ARGS preference (e.g.,"-Xss10m").').
1285 analyse_java_error_msg(_).
1286
1287 print_hint(Msg) :- format_with_colour_nl(user_error,[blue],'~w',[Msg]).
1288
1289 read_line_if_ready(Stream,Line) :- stream_ready_to_read(Stream), !, read_line(Stream,Line).
1290 read_line_if_ready(_,end_of_file). % pretend we are at the eof
1291
1292 read_lines_until_eof(Out,NewlineRequired) --> {read_line_if_ready(Out,Text)},
1293 !,
1294 ({Text = end_of_file} -> []
1295 ; ({NewlineRequired==true} -> "\n" ; []),
1296 Text, %{format("read: ~s~n",[Text])},
1297 read_lines_until_eof(Out,true)).
1298 read_lines_until_eof(_Out,_) --> [].
1299
1300 % display pending output lines from a stream
1301 display_pending_outputs(OutStream,ToStream) :- stream_ready_to_read(OutStream,0), !, read_line(OutStream,Line),
1302 (Line=end_of_file -> true
1303 ; format(ToStream,' =parser-output=> ~s~n',[Line]),
1304 display_pending_outputs(OutStream,ToStream)).
1305 display_pending_outputs(_,_).
1306
1307 :- use_module(tools,[get_tail_filename/2]).
1308 get_java_command_for_parser(native(GraalNativeCmd)) :-
1309 (parser_location(GraalNativeCmd)
1310 -> get_tail_filename(GraalNativeCmd,'cliparser'),
1311 (file_exists(GraalNativeCmd) -> true
1312 ; add_warning(parsercall,'Path to parser points to non-existant compiled GraalVM binary: ',GraalNativeCmd)
1313 )
1314 ; fail, % comment out fail to enable auto-detection of cliparser in lib folder
1315 library_abs_name('cliparser',GraalNativeCmd),
1316 file_exists(GraalNativeCmd)
1317 ),
1318 format('Using GRAAL native parser at ~w~n',[GraalNativeCmd]),
1319 !.
1320 get_java_command_for_parser(java_jar(JavaCmdW,JarPathW)) :-
1321 (parser_location(JarPath) -> true ; library_abs_name('probcliparser.jar',JarPath)),
1322 get_java_command_path(JavaCmdW),
1323 replace_windows_path_backslashes(JarPath,JarPathW).
1324
1325 parser_location(PathToParser) :- get_preference(path_to_java_parser,PathToParser), PathToParser \= ''.
1326
1327 % a predicate to check whether we have correct java version number and whether java seems to work ok
1328 % ResultStatus=compatible if everything is ok
1329 check_java_version(VersionCheckResult,ResultStatus) :- get_java_fullversion(Version),!,
1330 check_java_version_aux(Version,VersionCheckResult,ResultStatus).
1331 check_java_version(VersionCheckResult,error) :- get_java_command_for_parser(java_jar(JavaCmdW,JarPathW)),!,
1332 ajoin(['*** Unable to launch java command: ',JavaCmdW,' (classpath: ',JarPathW,')!'],VersionCheckResult).
1333 check_java_version('*** Unable to launch Java or get path to java command!',error). % should not happen
1334
1335 check_java_version_aux(VersionCodes,VersionCheckResult,ResultStatus) :-
1336 get_java_fullversion_numbers(VersionCodes,V1,V2,V3Atom),!,
1337 check_java_version_aux2(V1,V2,V3Atom,VersionCheckResult,ResultStatus).
1338 check_java_version_aux(VersionCodes,VersionCheckResult,error) :-
1339 atom_codes(VersionA,VersionCodes),
1340 ajoin(['*** Unable to identify Java version number: ',VersionA, ' !'],VersionCheckResult).
1341
1342 check_java_version_aux2(V1,V2,V3Atom,VersionCheckResult,compatible) :- java_version_ok_for_parser(V1,V2,V3Atom),
1343 get_java_version(_),!, % if get_java_version fails, this is an indication that Java not fully installed with admin rights
1344 ajoin(['Java is correctly installed and version ',V1,'.',V2,'.',V3Atom,
1345 ' is compatible with ProB requirements (>= 1.7).'],VersionCheckResult).
1346 check_java_version_aux2(V1,V2,V3Atom,VersionCheckResult,error) :- java_version_ok_for_parser(V1,V2,V3Atom),!,
1347 ajoin(['*** Java version ',V1,'.',V2,'.',V3Atom,
1348 ' is compatible with ProB requirements (>= 1.7) ',
1349 'but does not seem to be correctly installed: reinstall Java with admin rights!'],VersionCheckResult).
1350 check_java_version_aux2(V1,V2,V3Atom,VersionCheckResult,incompatible) :-
1351 get_java_version(_),!,
1352 ajoin(['*** Java is correctly installed but version ',V1,'.',V2,'.',V3Atom,
1353 ' is *not* compatible with ProB requirements (>= 1.7)!'],VersionCheckResult).
1354 check_java_version_aux2(V1,V2,V3Atom,VersionCheckResult,error) :-
1355 ajoin(['*** Java is not correctly installed and version ',V1,'.',V2,'.',V3Atom,
1356 ' is *not* compatible with ProB requirements (>= 1.7)!'],VersionCheckResult).
1357
1358
1359 % we need Java 1.7 or higher
1360 java_version_ok_for_parser(V1,_V2,_) :- V1>1.
1361 java_version_ok_for_parser(1,V2,_) :- V2>=7.
1362
1363 get_java_fullversion(V1,V2,V3Atom) :-
1364 get_java_fullversion(VersionCodes),
1365 get_java_fullversion_numbers(VersionCodes,VV1,VV2,VV3),!,
1366 V1=VV1, V2=VV2, V3Atom=VV3.
1367
1368 :- assert_must_succeed((parsercall:get_java_fullversion_numbers("openjdk full version \"1.8.0_312\"",V1,V2,V3),
1369 V1==1, V2==8, V3=='0_312')).
1370 :- assert_must_succeed((parsercall:get_java_fullversion_numbers("openjdk full version \"15+36-1562\"",V1,V2,V3),
1371 V1==1, V2==15, V3=='36-1562')).
1372 :- assert_must_succeed((parsercall:get_java_fullversion_numbers("java full version \"17.0.1+12-LTS-39\"",V1,V2,V3),
1373 V1==1, V2==17, V3=='0.1+12-LTS-39')). % Oracle JDK on macOS
1374 :- use_module(tools,[split_chars/3]).
1375 get_java_fullversion_numbers(VersionCodes,V1,V2,V3Atom) :-
1376 append("java full version """,Tail,VersionCodes), !,
1377 get_java_fullversion_numbers_aux(Tail,V1,V2,V3Atom).
1378 get_java_fullversion_numbers(VersionCodes,V1,V2,V3Atom) :-
1379 append("openjdk full version """,Tail,VersionCodes), !,
1380 get_java_fullversion_numbers_aux(Tail,V1,V2,V3Atom).
1381 get_java_fullversion_numbers_aux(Tail,1,V2,V3Atom) :-
1382 % new version scheme (https://openjdk.java.net/jeps/223), leading 1 dropped, 13+33 stands for 1.13.33
1383 split_chars(Tail,"+",[V2C,V3C]),
1384 !,
1385 (try_number_codes(V2,V2C)
1386 -> get_v3_atom(V3C,V3Atom)
1387 ; append(V2CC,[0'. | FurtherC], V2C) % there is at least one more dot in the version nr (e.g. 17.0.1+12-LTS-39)
1388 ->
1389 try_number_codes(V2,V2CC),
1390 append(FurtherC,[0'+ | V3C], V3C3),
1391 get_v3_atom(V3C3,V3Atom)
1392 ).
1393 get_java_fullversion_numbers_aux(Tail,V1,V2,V3Atom) :-
1394 split_chars(Tail,".",[V1C,V2C|FurtherC]),
1395 append(FurtherC,V3C),
1396 try_number_codes(V1,V1C),
1397 try_number_codes(V2,V2C),!,
1398 get_v3_atom(V3C,V3Atom).
1399
1400 get_v3_atom(V3C,V3Atom) :- strip_closing_quote(V3C,V3C2),
1401 atom_codes(V3Atom,V3C2).
1402
1403 try_number_codes(Name,Codes) :-
1404 catch(number_codes(Name,Codes), _Exc, fail).
1405
1406 strip_closing_quote([],[]).
1407 strip_closing_quote([H|_],R) :- (H=34 ; H=32),!, R=[]. % closing " or newline
1408 strip_closing_quote([H|T],[H|R]) :- strip_closing_quote(T,R).
1409
1410 % get java fullversion as code list; format "java full version "...."\n"
1411 get_java_fullversion(Version) :-
1412 get_java_command_path(JavaCmdW),
1413 (my_system_call(JavaCmdW, ['-fullversion'],java_version,Text) -> Text=Version
1414 ; format(user_error,'Could not execute ~w -fullversion~n',[JavaCmdW]),
1415 fail).
1416
1417 % when java -fullversion works but not java -version it seems that Java was improperly
1418 % installed without admin rights (http://stackoverflow.com/questions/11808829/jre-1-7-returns-java-lang-noclassdeffounderror-java-lang-object)
1419 get_java_version(Version) :-
1420 get_java_command_path(JavaCmdW),
1421 (my_system_call(JavaCmdW, ['-version'],java_version,Text) -> Text=Version
1422 ; format(user_error,'Could not execute ~w -version~n',[JavaCmdW]),
1423 fail).
1424 % should we check for JAVA_PATH first ? would allow user to override java; but default pref would have to be set to ''
1425 get_java_command_path(JavaCmdW) :-
1426 %host_platform(darwin)
1427 get_preference(path_to_java,X),
1428 debug_println(8,path_to_java_preference(X)),
1429 (X=''
1430 ; preference_default_value(path_to_java,Default), debug_println(8,default(Default)),
1431 Default=X
1432 ),
1433 % only try this when the Java path has not been set explicitly
1434 % on Mac: /usr/bin/java exists even when Java not installed ! it is a fake java command that launches a dialog
1435 ? absolute_file_name(path(java),
1436 JavaCmd,
1437 [access(exist),extensions(['.exe','']),solutions(all),file_errors(fail)]),
1438 debug_println(8,obtained_java_cmd_from_path(JavaCmd)),
1439 replace_windows_path_backslashes(JavaCmd,JavaCmdW),
1440 !.
1441 get_java_command_path(JavaCmdW) :- get_preference(path_to_java,JavaCmd),
1442 JavaCmd \= '',
1443 debug_println(8,using_path_to_java_preference(JavaCmd)),
1444 (file_exists(JavaCmd) -> true
1445 ; directory_exists(JavaCmd) -> add_warning(get_java_command_path,'No Java Runtime (7 or newer) found; please correct the JAVA_PATH advanced preference (it has to point to the java tool, *not* the directory enclosing it): ',JavaCmd)
1446 ; add_warning(get_java_command_path,'No Java Runtime (7 or newer) found; please correct the JAVA_PATH advanced preference: ',JavaCmd)),
1447 replace_windows_path_backslashes(JavaCmd,JavaCmdW),
1448 !.
1449 get_java_command_path(_JavaCmd) :-
1450 add_error(get_java_command_path,'Could not get path to the java tool. Make sure a Java Runtime (7 or newer) is installed',''),
1451 fail.
1452
1453 library_abs_name(Lib,Abs) :- absolute_file_name(prob_lib(Lib),Abs).
1454
1455
1456 call_ltl_parser(Formulas, CtlOrLtl, Result) :-
1457 get_ltl_lang_spec(LangSpec),
1458 maplist(parse_temporal_formula(CtlOrLtl,LangSpec),Formulas,Result).
1459
1460 :- use_module(specfile,[b_or_z_mode/0,csp_with_bz_mode/0]).
1461 get_ltl_lang_spec('B,none') :- csp_with_bz_mode,!.
1462 get_ltl_lang_spec('B') :- b_or_z_mode,!.
1463 get_ltl_lang_spec(none).
1464
1465 /* unused code :
1466 generate_formula_codes([F]) -->
1467 !,generate_formula_codes2(F),"\n".
1468 generate_formula_codes([F|Rest]) -->
1469 generate_formula_codes2(F), "###\n",
1470 generate_formula_codes(Rest).
1471 generate_formula_codes2(F) -->
1472 write_to_codes(F).
1473 */
1474
1475
1476 % ---------------------------
1477
1478 % call the TLA2B parser to translate a TLA file into a B machine
1479 call_tla2b_parser(TLAFile) :-
1480 get_java_command_path(JavaCmdW),
1481 replace_windows_path_backslashes(TLAFile,TLAFileW),
1482 phrase(jvm_options, XOpts),
1483 absolute_file_name(prob_lib('TLA2B.jar'),TLA2BJAR),
1484 append(XOpts,['-jar',file(TLA2BJAR),file(TLAFileW)],FullArgs),
1485 % other possible options -verbose -version -config FILE
1486 (my_system_call(JavaCmdW, FullArgs,tla2b_parser)
1487 -> true
1488 ; \+ file_exists(TLA2BJAR),
1489 print_error('Be sure to download TLA2B.jar from https://stups.hhu-hosting.de/downloads/prob/tcltk/jars/,'),
1490 print_error('and put it into the ProB lib/ directory.'),
1491 fail
1492 ).
1493
1494 %call_cspmj_parser(CSPFile,PrologFile) :-
1495 % get_java_command_path(JavaCmdW),
1496 % replace_windows_path_backslashes(CSPFile,CSPFileW),
1497 % phrase(jvm_options, XOpts),
1498 % absolute_file_name(prob_lib('cspmj.jar'),CSPMJAR),
1499 % get_writable_compiled_filename(CSPFile,'.pl',PrologFile),
1500 % tools:string_concatenate('--prologOut=', PrologFile, PrologFileOutArg),
1501 % append(XOpts,['-jar',CSPMJAR,'-parse',CSPFileW,PrologFileOutArg],FullArgs),
1502 % debug_println(9,calling_java(FullArgs)),
1503 % (my_system_call(JavaCmdW, FullArgs,cspmj_parser) -> true
1504 % ; print_error('Be sure that cspmj.jar parser is installed.'),
1505 % fail).
1506
1507
1508 tla2prob_filename(TLAFile,GeneratedProbFile) :-
1509 split_filename(TLAFile,Basename,_Extension),
1510 atom_chars(Basename,BasenameC),
1511 append(BasenameC,['.','p','r','o','b'],TLABC),
1512 atom_chars(GeneratedProbFile,TLABC),!.
1513 tla2prob_filename(Filename, GeneratedProbFile) :-
1514 add_failed_call_error(tla2b_filename(Filename,GeneratedProbFile)),fail.
1515
1516 tla2b_filename(TLAFile,BFile) :-
1517 split_filename(TLAFile,Basename,_Extension),
1518 atom_chars(Basename,BasenameC),
1519 append(BasenameC,['_',t,l,a,'.','m','c','h'],TLABC),
1520 atom_chars(BFile,TLABC),!.
1521 tla2b_filename(Filename, BFile) :-
1522 add_failed_call_error(tla2b_filename(Filename,BFile)),fail.
1523
1524
1525 my_system_call(Command,Args,Origin) :- my_system_call(Command,Args,Origin,_Text).
1526 my_system_call(Command,Args,Origin,ErrText) :-
1527 debug_print_system_call(Command,Args),
1528 system_call(Command,Args,ErrText,Exit), %nl,print(exit(Exit)),nl,nl,
1529 treat_exit_code(Exit,Command,Args,ErrText,Origin).
1530
1531 debug_print_system_call(Command,Args) :-
1532 (debug_mode(off) -> true ; print_system_call(Command,Args)).
1533 print_system_call(Command,Args) :-
1534 ajoin_with_sep(Args,' ',FS), format(user_output,'Executing: ~w ~w~n',[Command,FS]).
1535
1536 my_system_call5(Command,Args,Origin,OutputText,ErrText) :-
1537 system_call(Command,Args,OutputText,ErrText,Exit), %nl,print(exit(Exit)),nl,nl,
1538 treat_exit_code(Exit,Command,Args,ErrText,Origin).
1539
1540 treat_exit_code(exit(0),_,_,_,_) :- !.
1541 treat_exit_code(Exit,Command,Args,ErrText,Origin) :-
1542 debug_println(9,treat_exit_code(Exit,Command,Args,ErrText,Origin)),
1543 catch( my_read_from_codes(ErrText,Term),
1544 _,
1545 (safe_name(T,ErrText),Term = T)), !,
1546 %print_error(Term),
1547 (Term = end_of_file -> ErrMsg = '' ; ErrMsg = Term),
1548 ajoin(['Exit code ',Exit,' for command ',Command, ', error message: '],Msg),
1549 (get_error_position_from_term(Origin,Term,Pos)
1550 -> add_error(Origin,Msg,ErrMsg,Pos)
1551 ; add_error(Origin,Msg,ErrMsg)
1552 ),
1553 fail.
1554
1555
1556 get_error_position_from_term(alloy2b,Term,Pos) :- atom(Term),
1557 atom_codes(Term,Codes), get_error_position_from_codes(Codes,Pos).
1558
1559 % Alloy error message: ! Exception in thread "main" Type error in .../Restrictions.als at line 41 column 23:
1560 get_error_position_from_codes([97,116,32,108,105,110,101,32|Tail],lineCol(Line,Col)) :- % "at line "
1561 epi_number(Line,Tail,RestTail),
1562 (RestTail = [32,99,111,108,117,109,110,32|Tail2], % "column "
1563 epi_number(Col,Tail2,_) -> true
1564 ; Col=0).
1565 get_error_position_from_codes([_|T],Pos) :- get_error_position_from_codes(T,Pos).
1566
1567 % replace backslashes by forward slashes in atoms, only under windows
1568 % TODO(DP,14.8.2008): Check if still needed with SICStus 4.0.4 and if
1569 % everybody uses that version
1570 replace_windows_path_backslashes(Old,New) :-
1571 ( host_platform(windows) ->
1572 safe_name(Old,OldStr),
1573 replace_string_backslashes(OldStr,NewStr),
1574 safe_name(New,NewStr)
1575 ;
1576 Old=New).
1577
1578 replace_string_backslashes([],[]) :- !.
1579 replace_string_backslashes([C|OldRest],[N|NewRest]) :- !,
1580 ( C=92 /* backslash */ ->
1581 N=47 /* forward slash */
1582 ;
1583 N=C ),
1584 replace_string_backslashes(OldRest,NewRest).
1585 replace_string_backslashes(X,Y) :-
1586 add_error(parsercall,'Illegal call: ',replace_string_backslashes(X,Y)),
1587 fail.
1588
1589 % ---------------------------
1590
1591 :- assert_must_succeed((parsercall:parse_string_template("0",Res), Res==[string_codes("0")])).
1592 :- assert_must_succeed((parsercall:parse_string_template("ab${xy}cd",Res),
1593 Res==[string_codes("ab"),template_codes("xy",2,3,[]),string_codes("cd")])).
1594 :- assert_must_succeed((parsercall:parse_string_template("ab${xy}$<<z>>cd$\xab\v\xbb\",Res),
1595 Res==[string_codes("ab"),template_codes("xy",2,3,[]),template_codes("z",3,5,[]),
1596 string_codes("cd"),template_codes("v",2,3,[])])). % \xab\ is double angle
1597
1598 % parse a ProB string template
1599 % each recognised template is an expression.
1600 parse_string_template(Codes,TemplateList) :- %format("parsing: ~s~n",[Codes]),
1601 parse_string_template([],TemplateList,Codes,[]).
1602
1603 parse_string_template(Acc,TemplateList) -->
1604 template_inside_string(Str,StartOffset,AdditionalChars,Options),!,
1605 {add_acc_string(Acc,TemplateList,
1606 [template_codes(Str,StartOffset,AdditionalChars,Options)|T])},
1607 parse_string_template([],T).
1608 parse_string_template(Acc,TemplateList) --> [H], !, parse_string_template([H|Acc],TemplateList).
1609 parse_string_template(Acc,TemplateList) --> "", {add_acc_string(Acc,TemplateList,[])}.
1610
1611 % add accumulator as regular string before a detected template ${...}
1612 add_acc_string([],L,R) :- !, L=R.
1613 add_acc_string(Acc,[string_codes(Str)|T],T) :- reverse(Acc,Str).
1614
1615 template_inside_string(Str,StartOffset,AdditionalChars,Options) --> "$",
1616 template_options(Options,OptLen),
1617 template_open_paren(ClosingParen,ParenLen),
1618 {StartOffset is OptLen+ParenLen+1,
1619 AdditionalChars is StartOffset+ParenLen}, % add closing parentheses length
1620 template_content(Str,ClosingParen).
1621
1622 template_options(Options,Len) --> "[", template_options2(Options,Len).
1623 template_options([],0) --> [].
1624
1625 template_options2([H|T],Len) --> template_option(H,HLen), !, template_options3(T,HLen,Len).
1626 template_options2([],2) --> "]".
1627 template_options3([H|T],AccLen,Len) --> ",", template_option(H,HLen), !,
1628 {A1 is AccLen+HLen},template_options3(T,A1,Len).
1629 template_options3([],AccLen,Len) --> "]", {Len is AccLen+2}.
1630 template_option(ascii,5) --> "ascii".
1631 template_option(ascii,1) --> "a".
1632 template_option(unicode,7) --> "unicode".
1633 template_option(unicode,1) --> "u".
1634 template_option(template_width(Option,Nr),L1) --> digits(Nr,Len),template_width_option(Option,LO), {L1 is Len+LO}.
1635 % other options could be hex output or padding, ...
1636 % TODO: provide error feedback when option/template parsing fails
1637
1638 template_width_option(float_fixed_point,1) --> "f".
1639 template_width_option(integer_decimal_string,1) --> "d".
1640 template_width_option(pad_string(' '),1) --> "p".
1641
1642 digits(MinusNr,Len) --> "-",!, digit(X), digits2(X,Nr,2,Len), {MinusNr is -Nr}.
1643 digits(Nr,Len) --> digit(X), digits2(X,Nr,1,Len).
1644 digits2(X,Nr,AccLen,Len) --> digit(Y), !, {XY is X*10+Y, A1 is AccLen+1}, digits2(XY,Nr,A1,Len).
1645 digits2(X,X,Len,Len) --> "".
1646
1647 digit(Nr) --> [X], {X >= 48, X=<57, Nr is X-48}.
1648
1649 template_open_paren("}",1) --> "{".
1650 template_open_paren(">>",2) --> "<<".
1651 template_open_paren([187],1) --> [ 171 ]. % Double angle quotation mark "«»"
1652
1653 template_content("",Closing) --> Closing,!.
1654 template_content([H|T],Closing) --> [H], template_content(T,Closing).
1655
1656 % TODO: offset span within template
1657 parse_template_b_expression(Span,Filenumber,template_codes(Codes,_,_,Options),RawStrExpr) :-
1658 \+ get_prob_application_type(rodin), % in Rodin parser callback is not available
1659 !,
1660 catch( parse_at_position_in_file(expression,Codes,RawExpr,Span,Filenumber),
1661 parse_errors(Errors),
1662 (add_all_perrors(Errors,[],parse_template_string), % add_all_perrors_in_context_of_used_filenames?
1663 fail)
1664 ),
1665 create_to_string_conversion(RawExpr,Span,Options,RawStrExpr).
1666 parse_template_b_expression(Span,_,template_codes(Codes,_,_,_),string(Span,Atom)) :-
1667 atom_codes(Atom,Codes).
1668 parse_template_b_expression(Span,_,string_codes(Codes),string(Span,Atom)) :-
1669 atom_codes(Atom,Codes).
1670
1671 :- assert_must_succeed((parsercall:transform_string_template('1+1 = ${1+1}',p3(1,1,12),Res),
1672 Res= general_concat(_,sequence_extension(_,[_|_])) )).
1673 :- assert_must_succeed((parsercall:transform_string_template('abc',p3(1,1,3),Res),
1674 Res= string(_,'abc') )).
1675
1676 :- use_module(error_manager,[extract_file_number_and_name/3]).
1677 % transform a string template into a raw expression that computes a string value
1678 transform_string_template(Atom,Span,RawExpr) :-
1679 atom_codes(Atom,Codes),
1680 parse_string_template(Codes,TemplateList),
1681 transform_str_templ_aux(TemplateList,Atom,Span,RawExpr).
1682
1683 transform_str_templ_aux([string_codes(_)],Atom,Span,RawExpr) :- !,
1684 debug_println(19,unnecessary_string_template(Span)), % regular string suffices
1685 RawExpr = string(Span,Atom).
1686 transform_str_templ_aux(TemplateList,_,Span,RawExpr) :-
1687 (extract_file_number_and_name(Span,FileNr,_) -> true ; FileNr = -1),
1688 InitialOffset = 3, % for three starting quotes
1689 l_parse_templates(TemplateList,0,InitialOffset,Span,FileNr,BTemplateList),
1690 generate_conc_expr(BTemplateList,Span,RawExpr).
1691
1692 :- use_module(tools_positions, [add_col_offset_to_position/3, add_line_col_offset_to_position/4]).
1693 l_parse_templates([],_,_,_,_,[]).
1694 l_parse_templates([Templ1|T],LineOffset,ColOffset,Span,FileNr,[RawStrExpr|BT]) :-
1695 templ_start_offset(Templ1,StartOffset),
1696 CO2 is ColOffset+StartOffset, % e.g., add two chars for ${ in case Templ1 is a template
1697 add_line_col_offset_to_position(Span,LineOffset,CO2,Span1),
1698 % it is only start position of Span1 that is important
1699 parse_template_b_expression(Span1,FileNr,Templ1,RawStrExpr),
1700 count_template_offset(Templ1,LineOffset,ColOffset,LineOffset2,ColOffset2),
1701 l_parse_templates(T,LineOffset2,ColOffset2,Span,FileNr,BT).
1702
1703 % accumulate length of template part and add to line/col offset to be added to start of template string
1704 count_template_offset(template_codes(Codes,_StartOffset,AdditionalChars,_),L,C,LineOffset,C3) :-
1705 count_offset(Codes,L,C,LineOffset,ColOffset),
1706 C3 is ColOffset+AdditionalChars. % e.g., 3 for ${.}
1707 count_template_offset(string_codes(Codes),L,C,LineOffset,ColOffset) :-
1708 count_offset(Codes,L,C,LineOffset,ColOffset).
1709
1710 templ_start_offset(template_codes(_,StartOffset,_,_),StartOffset). % usually 2 for ${
1711 templ_start_offset(string_codes(_),0).
1712
1713 % count line/column offset inside a list of codes:
1714 %count_offset(Codes,LineOffset,ColOffset) :- count_offset(Codes,0,0,LineOffset,ColOffset).
1715 count_offset([],Line,Col,Line,Col).
1716 count_offset(Codes,L,_ColOffset,Line,Col) :- newline(Codes,T),!,
1717 L1 is L+1,
1718 count_offset(T,L1,0,Line,Col).
1719 count_offset([_|T],L,ColOffset,Line,Col) :- C1 is ColOffset+1,
1720 count_offset(T,L,C1,Line,Col).
1721
1722 newline([10|T],T).
1723 newline([13|X],T) :- (X=[10|TX] -> T=TX ; T=X). % TO DO: should we check if we are on Windows ?
1724
1725 % generate a raw expression for the concatenation of a list of expressions
1726 generate_conc_expr([],Pos,string(Pos,'')).
1727 generate_conc_expr([OneEl],_,Res) :- !, Res = OneEl. % no need to concatenate
1728 generate_conc_expr(List,Pos,general_concat(Pos,sequence_extension(Pos,List))).
1729
1730 create_to_string_conversion(RawExpr,Pos,Options,
1731 external_function_call_auto(Pos,'STRING_PADLEFT',[RawStrExpr,Len,Char])) :-
1732 select(template_width(pad_string(PadChar),Nr),Options,RestOpts),!,
1733 create_to_string_conversion(RawExpr,Pos,RestOpts,RawStrExpr),
1734 Char = string(Pos,PadChar),
1735 Len = integer(Pos,Nr).
1736 create_to_string_conversion(RawExpr,Pos,Options,RawStrExpr) :-
1737 is_definitely_string(RawExpr),!,
1738 (Options=[] -> true
1739 ; add_warning(string_template,'Ignoring options in string template (already a string): ',Options, Pos)),
1740 RawStrExpr=RawExpr.
1741 create_to_string_conversion(RawExpr,Pos,Options,external_function_call_auto(Pos,'REAL_TO_DEC_STRING',[RawExpr,Prec])) :-
1742 select_option(template_width(float_fixed_point,Nr),Options,Pos),!,
1743 Prec = integer(Pos,Nr).
1744 create_to_string_conversion(RawExpr,Pos,Options,external_function_call_auto(Pos,'INT_TO_DEC_STRING',[RawExpr,Prec])) :-
1745 select_option(template_width(integer_decimal_string,Nr),Options,Pos),!,
1746 Prec = integer(Pos,Nr).
1747 create_to_string_conversion(RawExpr,Pos,Options,external_function_call_auto(Pos,'TO_STRING_UNICODE',[RawExpr])) :-
1748 select_option(unicode,Options,Pos),!. % TODO use a TO_STRING function with options list
1749 create_to_string_conversion(RawExpr,Pos,_Options,external_function_call_auto(Pos,'TO_STRING',[RawExpr])).
1750
1751 select_option(Option,Options,Pos) :-
1752 select(Option,Options,Rest),
1753 (Rest=[] -> true ; add_warning(string_template,'Ignoring additional string template options: ',Rest,Pos)).
1754
1755
1756 is_definitely_string(string(_,_)).
1757
1758 % ---------------------------
1759 :- use_module(pathes,[runtime_application_path/1]).
1760
1761 call_jar_parser(PMLFile,JARFile,Args,ParserName) :-
1762 get_java_command_path(JavaCmdW),
1763 replace_windows_path_backslashes(PMLFile,PMLFileW),
1764 phrase(jvm_options, XOpts),
1765 absolute_file_name(prob_lib(JARFile),FullJAR),
1766 append(XOpts,['-jar',FullJAR,PMLFileW|Args],FullArgs),
1767 %format('Java: ~w, Parser: ~w, Args: ~w~n',[JavaCmdW,ParserName,FullArgs]),
1768 my_system_call(JavaCmdW, FullArgs,ParserName).
1769
1770
1771
1772 call_alloy2pl_parser(AlloyFile,BFile) :-
1773 alloy_pl_filename(AlloyFile,BFile),
1774 call_alloy2pl_parser_aux(AlloyFile,'alloy2b.jar',BFile).
1775
1776 call_alloy2pl_parser_aux(AlloyFile,JARFile,PrologBFile) :-
1777 compilation_not_needed(AlloyFile,PrologBFile,JARFile),!.
1778 call_alloy2pl_parser_aux(AlloyFile,JARFile,PrologBFile) :-
1779 (file_exists(PrologBFile) -> delete_file(PrologBFile) ; true), % TODO: only delete generated files
1780 replace_windows_path_backslashes(PrologBFile,BFileW),
1781 call_jar_parser(AlloyFile,JARFile,['-toProlog',BFileW],alloy2b).
1782
1783 alloy_pl_filename(AlloyFile,BFile) :- atom_codes(AlloyFile,BasenameC),
1784 append(BasenameC,".pl",NewC),
1785 atom_codes(BFile,NewC),!.
1786 alloy_pl_filename(Filename, BFile) :-
1787 add_failed_call_error(alloy_pl_filename(Filename,BFile)),fail.
1788
1789 compilation_not_needed(BaseFile,DerivedFile,LibraryFile) :-
1790 file_exists(BaseFile),
1791 file_property(BaseFile, modify_timestamp, BTime),
1792 %system:datime(BTime,datime(_Year,Month,Day,Hour,Min,Sec)), format('~w modfied on ~w/~w at ~w:~w (~w sec)~n',[BaseFile,Day,Month,Hour,Min,Sec]),
1793 file_exists(DerivedFile),
1794 file_property(DerivedFile, modify_timestamp, DTime),
1795 DTime > BTime,
1796 absolute_file_name(prob_lib(LibraryFile),FullLibFile),
1797 (file_exists(FullLibFile)
1798 -> file_property(FullLibFile, modify_timestamp, LibTime),
1799 DTime > LibTime % check that file was generated by this library (hopefully); ideally we should put version numbers into the DerivedFiles
1800 ; true % Jar/command not available anyway; use the derived file
1801 ).
1802
1803 % ---------------------------
1804
1805 call_fuzz_parser(TexFile,FuzzFile) :-
1806 get_command_in_lib(fuzz,FuzzCmd),
1807 absolute_file_name(prob_lib('fuzzlib'),FUZZLIB), % TO DO: windows
1808 fuzz_filename(TexFile,FuzzFile),
1809 % fuzz options:
1810 % -d Allow use before definition
1811 % -l Lisp-style echoing of input
1812 % -p file Use <file> in place of standard prelude
1813 debug_format(19,'Fuzz: running ~w -d -l with library ~w on ~w~n',[FuzzCmd,FUZZLIB,TexFile]),
1814 (file_exists(FUZZLIB)
1815 -> my_system_call5(FuzzCmd,['-d', '-l', '-p', file(FUZZLIB), file(TexFile)],call_fuzz_parser,Text,_ErrText)
1816 ; my_system_call5(FuzzCmd,['-d', '-l', file(TexFile)],call_fuzz_parser,Text,_ErrText)
1817 ),
1818 format('Writing fuzz AST to ~s~n',[FuzzFile]),
1819 open(FuzzFile,write,Stream),
1820 call_cleanup(format(Stream,'~s~n',[Text]), close(Stream)).
1821
1822 get_command_in_lib(Name,Command) :-
1823 get_binary_extensions(Extensions),
1824 absolute_file_name(prob_lib(Name),
1825 Command,
1826 [access(exist),extensions(Extensions),solutions(all),file_errors(fail)]).
1827
1828 get_binary_extensions(List) :-
1829 host_platform(windows),!, List=['.exe','']. % will backtrack in get_command_in_lib
1830 get_binary_extensions(['']).
1831
1832 fuzz_filename(TexFile,FuzzFile) :-
1833 split_filename(TexFile,Basename,_Extension),
1834 atom_chars(Basename,BasenameC),
1835 append(BasenameC,['.','f','u','z','z'],CC),
1836 atom_chars(FuzzFile,CC),!.
1837 fuzz_filename(TexFile, FuzzFile) :-
1838 add_failed_call_error(fuzz_filename(TexFile,FuzzFile)),fail.