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