1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2006-2025, University of Amsterdam 7 VU University Amsterdam 8 SWI-Prolog Solutions b.v. 9 All rights reserved. 10 11 Redistribution and use in source and binary forms, with or without 12 modification, are permitted provided that the following conditions 13 are met: 14 15 1. Redistributions of source code must retain the above copyright 16 notice, this list of conditions and the following disclaimer. 17 18 2. Redistributions in binary form must reproduce the above copyright 19 notice, this list of conditions and the following disclaimer in 20 the documentation and/or other materials provided with the 21 distribution. 22 23 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 26 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 27 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 28 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 29 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 30 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 31 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 32 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 33 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 POSSIBILITY OF SUCH DAMAGE. 35*/ 36 37:- module(prolog_source, 38 [ prolog_read_source_term/4, % +Stream, -Term, -Expanded, +Options 39 read_source_term_at_location/3, %Stream, -Term, +Options 40 prolog_file_directives/3, % +File, -Directives, +Options 41 prolog_open_source/2, % +Source, -Stream 42 prolog_close_source/1, % +Stream 43 prolog_canonical_source/2, % +Spec, -Id 44 45 load_quasi_quotation_syntax/2, % :Path, +Syntax 46 47 file_name_on_path/2, % +File, -PathSpec 48 file_alias_path/2, % ?Alias, ?Dir 49 path_segments_atom/2, % ?Segments, ?Atom 50 directory_source_files/3, % +Dir, -Files, +Options 51 valid_term_position/2 % +Term, +TermPos 52 ]). 53:- use_module(library(debug), [debug/3, assertion/1]). 54:- autoload(library(apply), [maplist/2, maplist/3, foldl/4]). 55:- autoload(library(error), [domain_error/2, is_of_type/2]). 56:- autoload(library(lists), [member/2, last/2, select/3, append/3, selectchk/3]). 57:- autoload(library(operators), [push_op/3, push_operators/1, pop_operators/0]). 58:- autoload(library(option), 59 [select_option/4, option/3, option/2, merge_options/3]). 60:- autoload(library(modules),[in_temporary_module/3]).
86:- thread_local 87 open_source/2, % Stream, State 88 mode/2, % Stream, Data 89 syntax_option/2. % Stream, ReadOption 90 91:- multifile 92 requires_library/2, 93 prolog:xref_source_identifier/2, % +Source, -Id 94 prolog:xref_source_time/2, % +Source, -Modified 95 prolog:xref_open_source/2, % +SourceId, -Stream 96 prolog:xref_close_source/2, % +SourceId, -Stream 97 prolog:alternate_syntax/4, % Syntax, +Module, -Setup, -Restore 98 prolog:xref_update_syntax/2, % +Directive, +Module 99 prolog:quasi_quotation_syntax/2. % Syntax, Library 100 101 102:- predicate_options(prolog_read_source_term/4, 4, 103 [ pass_to(system:read_clause/3, 3) 104 ]). 105:- predicate_options(read_source_term_at_location/3, 3, 106 [ line(integer), 107 offset(integer), 108 module(atom), 109 operators(list), 110 error(-any), 111 pass_to(system:read_term/3, 3) 112 ]). 113:- predicate_options(directory_source_files/3, 3, 114 [ recursive(boolean), 115 if(oneof([true,loaded])), 116 pass_to(system:absolute_file_name/3,3) 117 ]). 118 119 120 /******************************* 121 * READING * 122 *******************************/
This predicate is intended to read the file from the start. It tracks directives to update its notion of the currently effective syntax (e.g., declared operators).
138prolog_read_source_term(In, Term, Expanded, Options0) :- 139 add_syntax_options(In, Options0, Options), 140 read_source_term(In, Term, Expanded, Options). 141 142read_source_term(In, Term, Expanded, Options) :- 143 maplist(read_clause_option, Options), 144 !, 145 select_option(subterm_positions(TermPos), Options, 146 RestOptions, TermPos), 147 read_clause(In, Term, 148 [ subterm_positions(TermPos) 149 | RestOptions 150 ]), 151 expand(Term, TermPos, In, Expanded), 152 '$current_source_module'(M), 153 update_state(Term, Expanded, M, In). 154read_source_term(In, Term, Expanded, Options) :- 155 '$current_source_module'(M), 156 select_option(syntax_errors(SE), Options, RestOptions0, dec10), 157 select_option(subterm_positions(TermPos), RestOptions0, 158 RestOptions, TermPos), 159 ( style_check(?(singleton)) 160 -> FinalOptions = [ singletons(warning) | RestOptions ] 161 ; FinalOptions = RestOptions 162 ), 163 read_term(In, Term, 164 [ module(M), 165 syntax_errors(SE), 166 subterm_positions(TermPos) 167 | FinalOptions 168 ]), 169 expand(Term, TermPos, In, Expanded), 170 update_state(Term, Expanded, M, In). 171 172read_clause_option(syntax_errors(_)). 173read_clause_option(term_position(_)). 174read_clause_option(process_comment(_)). 175read_clause_option(comments(_)). 176read_clause_option(var_prefix(_)). 177read_clause_option(variable_names(_)).
user.185add_syntax_options(In, Options0, Options) :- 186 findall(Opt, syntax_option(In, Opt), Opts), 187 merge_options(Options0, Opts, Options). 188 189:- public 190 expand/3. % Used by Prolog colour 191 192expand(Term, In, Exp) :- 193 expand(Term, _, In, Exp). 194 195expand(Var, _, _, Var) :- 196 var(Var), 197 !. 198expand(Term, _, _, Term) :- 199 no_expand(Term), 200 !. 201expand(Term, _, _, _) :- 202 requires_library(Term, Lib), 203 ensure_loaded(user:Lib), 204 fail. 205expand(Term, _, In, Term) :- 206 chr_expandable(Term, In), 207 !. 208expand(Term, Pos, _, Expanded) :- 209 expand_term(Term, Pos, Expanded, _). 210 211no_expand((:- if(_))). 212no_expand((:- elif(_))). 213no_expand((:- else)). 214no_expand((:- endif)). 215no_expand((:- require(_))). 216 217chr_expandable((:- chr_constraint(_)), In) :- 218 add_mode(In, chr). 219chr_expandable((handler(_)), In) :- 220 mode(In, chr). 221chr_expandable((rules(_)), In) :- 222 mode(In, chr). 223chr_expandable(<=>(_, _), In) :- 224 mode(In, chr). 225chr_expandable(@(_, _), In) :- 226 mode(In, chr). 227chr_expandable(==>(_, _), In) :- 228 mode(In, chr). 229chr_expandable(pragma(_, _), In) :- 230 mode(In, chr). 231chr_expandable(option(_, _), In) :- 232 mode(In, chr). 233 234add_mode(Stream, Mode) :- 235 mode(Stream, Mode), 236 !. 237add_mode(Stream, Mode) :- 238 asserta(mode(Stream, Mode)).
244requires_library((:- emacs_begin_mode(_,_,_,_,_)), library(emacs_extend)). 245requires_library((:- draw_begin_shape(_,_,_,_)), library(pcedraw)). 246requires_library((:- use_module(library(pce))), library(pce)). 247requires_library((:- pce_begin_class(_,_)), library(pce)). 248requires_library((:- pce_begin_class(_,_,_)), library(pce)). 249requires_library((:- html_meta(_)), library(http/html_decl)).
255:- multifile 256 pce_expansion:push_compile_operators/1, 257 pce_expansion:pop_compile_operators/0. 258 259update_state((:- pce_end_class), _, _, _) => 260 ignore(pce_expansion:pop_compile_operators). 261update_state((:- pce_extend_class(_)), _, SM, _) => 262 pce_expansion:push_compile_operators(SM). 263update_state(Raw, _, Module, _), 264 catch(prolog:xref_update_syntax(Raw, Module), 265 error(_,_), 266 fail) => 267 true. 268update_state(_Raw, Expanded, M, In) => 269 update_state(Expanded, M, In). 270 271update_state(Var, _, _) :- 272 var(Var), 273 !. 274update_state([], _, _) :- 275 !. 276update_state([H|T], M, In) :- 277 !, 278 update_state(H, M, In), 279 update_state(T, M, In). 280update_state((:- Directive), M, In) :- 281 nonvar(Directive), 282 !, 283 catch(update_directive(Directive, M, In), _, true). 284update_state((?- Directive), M, In) :- 285 !, 286 update_state((:- Directive), M, In). 287update_state(MetaDecl, _M, _) :- 288 MetaDecl = html_write:html_meta_head(_Head,_Module,_Meta), 289 ( clause(MetaDecl, true) 290 -> true 291 ; assertz(MetaDecl) 292 ). 293update_state(_, _, _).
297update_directive(Directive, Module, _) :- 298 prolog:xref_update_syntax((:- Directive), Module), 299 !. 300update_directive(encoding(Enc), _, In) :- 301 !, 302 set_stream(In, encoding(Enc)). 303update_directive(module(Module, Public), _, _) :- 304 atom(Module), 305 is_list(Public), 306 !, 307 '$set_source_module'(Module), 308 maplist(import_syntax(_,Module, _), Public). 309update_directive(M:op(P,T,N), SM, In) :- 310 atom(M), 311 ground(op(P,T,N)), 312 !, 313 update_directive(op(P,T,N), SM, In). 314update_directive(op(P,T,N), SM, _) :- 315 ground(op(P,T,N)), 316 !, 317 strip_module(SM:N, M, PN), 318 push_op(P,T,M:PN). 319update_directive(set_prolog_flag(var_prefix, Prefix), _, In) :- 320 atom(Prefix), 321 !, 322 retractall(syntax_option(In, var_prefix(_))), 323 assertz(syntax_option(In, var_prefix(Prefix))). 324update_directive(style_check(Style), _, _) :- 325 ground(Style), 326 style_check(Style), 327 !. 328update_directive(use_module(Spec), SM, _) :- 329 ground(Spec), 330 catch(module_decl(Spec, Path, Public), _, fail), 331 is_list(Public), 332 !, 333 maplist(import_syntax(Path, SM, _), Public). 334update_directive(use_module(Spec, Imports), SM, _) :- 335 ground(Spec), 336 is_list(Imports), 337 catch(module_decl(Spec, Path, Public), _, fail), 338 is_list(Public), 339 !, 340 maplist(import_syntax(Path, SM, Imports), Public). 341update_directive(pce_begin_class_definition(_,_,_,_), SM, _) :- 342 pce_expansion:push_compile_operators(SM), 343 !. 344update_directive(_, _, _).
351import_syntax(_, _, _, Var) :- 352 var(Var), 353 !. 354import_syntax(_, M, Imports, Op) :- 355 Op = op(_,_,_), 356 \+ \+ member(Op, Imports), 357 !, 358 update_directive(Op, M, _). 359import_syntax(Path, SM, Imports, Syntax/4) :- 360 \+ \+ member(Syntax/4, Imports), 361 load_quasi_quotation_syntax(SM:Path, Syntax), 362 !. 363import_syntax(_,_,_, _).
380load_quasi_quotation_syntax(SM:Path, Syntax) :- 381 atom(Path), atom(Syntax), 382 source_file_property(Path, module(M)), 383 functor(ST, Syntax, 4), 384 predicate_property(M:ST, quasi_quotation_syntax), 385 !, 386 use_module(SM:Path, [Syntax/4]). 387load_quasi_quotation_syntax(SM:Path, Syntax) :- 388 atom(Path), atom(Syntax), 389 prolog:quasi_quotation_syntax(Syntax, Spec), 390 absolute_file_name(Spec, Path2, 391 [ file_type(prolog), 392 file_errors(fail), 393 access(read) 394 ]), 395 Path == Path2, 396 !, 397 use_module(SM:Path, [Syntax/4]).
405module_decl(Spec, Source, Exports) :- 406 absolute_file_name(Spec, Path, 407 [ file_type(prolog), 408 file_errors(fail), 409 access(read) 410 ]), 411 module_decl_(Path, Source, Exports). 412 413module_decl_(Path, Source, Exports) :- 414 file_name_extension(_, qlf, Path), 415 !, 416 '$qlf_module'(Path, Info), 417 _{file:Source, exports:Exports} :< Info. 418module_decl_(Path, Path, Exports) :- 419 setup_call_cleanup( 420 prolog_open_source(Path, In), 421 read_module_decl(In, Exports), 422 prolog_close_source(In)). 423 424read_module_decl(In, Decl) :- 425 read(In, Term0), 426 read_module_decl(Term0, In, Decl). 427 428read_module_decl((:- module(_, DeclIn)), _In, Decl) => 429 Decl = DeclIn. 430read_module_decl((:- encoding(Enc)), In, Decl) => 431 set_stream(In, encoding(Enc)), 432 read(In, Term2), 433 read_module_decl(Term2, In, Decl). 434read_module_decl(_, _, _) => 435 fail.
This predicate has two ways to find the right syntax. If the file is loaded, it can be passed the module using the module option. This deals with module files that define the used operators globally for the file. Second, there is a hook alternate_syntax/4 that can be used to temporary redefine the syntax.
The options below are processed in addition to the options of
read_term/3. Note that the line and offset options are
mutually exclusive.
det).479:- thread_local 480 last_syntax_error/2. % location, message 481 482read_source_term_at_location(Stream, Term, Options) :- 483 retractall(last_syntax_error(_,_)), 484 seek_to_start(Stream, Options), 485 stream_property(Stream, position(Here)), 486 '$current_source_module'(DefModule), 487 option(module(Module), Options, DefModule), 488 option(operators(Ops), Options, []), 489 alternate_syntax(Syntax, Module, Setup, Restore), 490 set_stream_position(Stream, Here), 491 debug(read, 'Trying with syntax ~w', [Syntax]), 492 push_operators(Module:Ops), 493 call(Setup), 494 Error = error(Formal,_), % do not catch timeout, etc. 495 setup_call_cleanup( 496 asserta(user:thread_message_hook(_,_,_), Ref), % silence messages 497 catch(qq_read_term(Stream, Term0, 498 [ module(Module) 499 | Options 500 ]), 501 Error, 502 true), 503 erase(Ref)), 504 call(Restore), 505 pop_operators, 506 ( var(Formal) 507 -> !, Term = Term0 508 ; assert_error(Error, Options), 509 fail 510 ). 511read_source_term_at_location(_, _, Options) :- 512 option(error(Error), Options), 513 !, 514 setof(CharNo:Msg, retract(last_syntax_error(CharNo, Msg)), Pairs), 515 last(Pairs, Error). 516 517assert_error(Error, Options) :- 518 option(error(_), Options), 519 !, 520 ( ( Error = error(syntax_error(Id), 521 stream(_S1, _Line1, _LinePos1, CharNo)) 522 ; Error = error(syntax_error(Id), 523 file(_S2, _Line2, _LinePos2, CharNo)) 524 ) 525 -> message_to_string(error(syntax_error(Id), _), Msg), 526 assertz(last_syntax_error(CharNo, Msg)) 527 ; debug(read, 'Error: ~q', [Error]), 528 throw(Error) 529 ). 530assert_error(_, _).
Calls the hook alternate_syntax/4 with the same signature to allow for user-defined extensions.
546alternate_syntax(prolog, _, true, true). 547alternate_syntax(Syntax, M, Setup, Restore) :- 548 prolog:alternate_syntax(Syntax, M, Setup, Restore).
555seek_to_start(Stream, Options) :- 556 option(line(Line), Options), 557 !, 558 seek(Stream, 0, bof, _), 559 seek_to_line(Stream, Line). 560seek_to_start(Stream, Options) :- 561 option(offset(Start), Options), 562 !, 563 seek(Stream, Start, bof, _). 564seek_to_start(_, _).
570seek_to_line(Fd, N) :- 571 N > 1, 572 !, 573 skip(Fd, 10), 574 NN is N - 1, 575 seek_to_line(Fd, NN). 576seek_to_line(_, _). 577 578 579 /******************************* 580 * QUASI QUOTATIONS * 581 *******************************/
589qq_read_term(Stream, Term, Options) :- 590 select(syntax_errors(ErrorMode), Options, Options1), 591 ErrorMode \== error, 592 !, 593 ( ErrorMode == dec10 594 -> repeat, 595 qq_read_syntax_ex(Stream, Term, Options1, Error), 596 ( var(Error) 597 -> ! 598 ; print_message(error, Error), 599 fail 600 ) 601 ; qq_read_syntax_ex(Stream, Term, Options1, Error), 602 ( ErrorMode == fail 603 -> print_message(error, Error), 604 fail 605 ; ErrorMode == quiet 606 -> fail 607 ; domain_error(syntax_errors, ErrorMode) 608 ) 609 ). 610qq_read_term(Stream, Term, Options) :- 611 qq_read_term_ex(Stream, Term, Options). 612 613qq_read_syntax_ex(Stream, Term, Options, Error) :- 614 catch(qq_read_term_ex(Stream, Term, Options), 615 error(syntax_error(Syntax), Context), 616 Error = error(Syntax, Context)). 617 618qq_read_term_ex(Stream, Term, Options) :- 619 stream_property(Stream, position(Here)), 620 catch(read_term(Stream, Term, Options), 621 error(syntax_error(unknown_quasi_quotation_syntax(Syntax, Module)), Context), 622 load_qq_and_retry(Here, Syntax, Module, Context, Stream, Term, Options)). 623 624load_qq_and_retry(Here, Syntax, Module, _, Stream, Term, Options) :- 625 set_stream_position(Stream, Here), 626 prolog:quasi_quotation_syntax(Syntax, Library), 627 !, 628 use_module(Module:Library, [Syntax/4]), 629 read_term(Stream, Term, Options). 630load_qq_and_retry(_Pos, Syntax, Module, Context, _Stream, _Term, _Options) :- 631 print_message(warning, quasi_quotation(undeclared, Syntax)), 632 throw(error(syntax_error(unknown_quasi_quotation_syntax(Syntax, Module)), Context)).
This multifile hook is used by library(prolog_source) to load quasi quotation handlers on demand.
643prologquasi_quotation_syntax(html, library(http/html_write)). 644prologquasi_quotation_syntax(javascript, library(http/js_write)).
true (default false), do not report syntax errors and
other errors.663prolog_file_directives(File, Directives, Options) :- 664 option(canonical_source(Path), Options, _), 665 prolog_canonical_source(File, Path), 666 in_temporary_module( 667 TempModule, 668 true, 669 read_directives(TempModule, Path, Directives, Options)). 670 671read_directives(TempModule, Path, Directives, Options) :- 672 setup_call_cleanup( 673 read_directives_setup(TempModule, Path, In, State), 674 phrase(read_directives(In, Options, [true]), Directives), 675 read_directives_cleanup(In, State)). 676 677read_directives_setup(TempModule, Path, In, OldM) :- 678 prolog_open_source(Path, In), 679 '$set_source_module'(OldM, TempModule), 680 push_prolog_flag(xref, true). 681 682read_directives_cleanup(In, OldM) :- 683 '$set_source_module'(OldM), 684 pop_prolog_flag(xref), 685 prolog_close_source(In). 686 687read_directives(In, Options, State) --> 688 { E = error(_,_), 689 repeat, 690 catch(prolog_read_source_term(In, Term, Expanded, 691 [ process_comment(true), 692 syntax_errors(error) 693 ]), 694 E, report_syntax_error(E, Options)) 695 -> nonvar(Term), 696 Term = (:-_) 697 }, 698 !, 699 terms(Expanded, State, State1), 700 read_directives(In, Options, State1). 701read_directives(_, _, _) --> []. 702 703report_syntax_error(_, Options) :- 704 option(silent(true), Options), 705 !, 706 fail. 707report_syntax_error(E, _Options) :- 708 print_message(warning, E), 709 fail. 710 711terms(Var, State, State) --> { var(Var) }, !. 712terms([H|T], State0, State) --> 713 !, 714 terms(H, State0, State1), 715 terms(T, State1, State). 716terms((:-if(Cond)), State0, [True|State0]) --> 717 !, 718 { eval_cond(Cond, True) }. 719terms((:-elif(Cond)), [True0|State], [True|State]) --> 720 !, 721 { eval_cond(Cond, True1), 722 elif(True0, True1, True) 723 }. 724terms((:-else), [True0|State], [True|State]) --> 725 !, 726 { negate(True0, True) }. 727terms((:-endif), [_|State], State) --> !. 728terms(H, State, State) --> 729 ( {State = [true|_]} 730 -> [H] 731 ; [] 732 ). 733 734% eval_cond(+Cond, -True) is det. 735% 736% Evaluate the condition of ``:- if(Cond)`` or ``:- elif(Cond)``. 737% Reading the directives of a file must not run its code: the file is 738% often one that is merely opened, e.g., cross-referenced by an 739% editor. We therefore only evaluate conditions that use the side 740% effect free predicates of safe_cond_predicate/1. Anything else is 741% false, which is also what a call to a predicate of the file 742% itself evaluates to, as that is not defined while reading. 743 744eval_cond(Cond, true) :- 745 safe_cond(Cond), 746 catch(Cond, error(_,_), fail), 747 !. 748eval_cond(_, false). 749 750safe_cond(Var) :- 751 var(Var), 752 !, 753 fail. 754safe_cond((A,B)) :- 755 !, 756 safe_cond(A), 757 safe_cond(B). 758safe_cond((A;B)) :- 759 !, 760 safe_cond(A), 761 safe_cond(B). 762safe_cond((A->B)) :- 763 !, 764 safe_cond(A), 765 safe_cond(B). 766safe_cond((A*->B)) :- 767 !, 768 safe_cond(A), 769 safe_cond(B). 770safe_cond(\+(A)) :- 771 !, 772 safe_cond(A). 773safe_cond(Goal) :- 774 callable(Goal), 775 Goal \= _:_, 776 functor(Goal, Name, Arity), 777 safe_cond_predicate(Name/Arity). 778 779safe_cond_predicate(true/0). 780safe_cond_predicate(fail/0). 781safe_cond_predicate(false/0). 782safe_cond_predicate(current_prolog_flag/2). 783safe_cond_predicate(current_predicate/1). 784safe_cond_predicate(current_predicate/2). 785safe_cond_predicate(predicate_property/2). 786safe_cond_predicate(current_module/1). 787safe_cond_predicate(current_op/3). 788safe_cond_predicate(exists_source/1). 789safe_cond_predicate(exists_source/2). 790safe_cond_predicate(exists_file/1). 791safe_cond_predicate(exists_directory/1). 792safe_cond_predicate(absolute_file_name/2). 793safe_cond_predicate(absolute_file_name/3). 794safe_cond_predicate(getenv/2). 795safe_cond_predicate(statistics/2). 796safe_cond_predicate(debugging/1). 797safe_cond_predicate((=)/2). 798safe_cond_predicate((\=)/2). 799safe_cond_predicate((==)/2). 800safe_cond_predicate((\==)/2). 801safe_cond_predicate((@<)/2). 802safe_cond_predicate((@>)/2). 803safe_cond_predicate((@=<)/2). 804safe_cond_predicate((@>=)/2). 805safe_cond_predicate((<)/2). 806safe_cond_predicate((>)/2). 807safe_cond_predicate((=<)/2). 808safe_cond_predicate((>=)/2). 809safe_cond_predicate((=:=)/2). 810safe_cond_predicate((=\=)/2). 811safe_cond_predicate(var/1). 812safe_cond_predicate(nonvar/1). 813safe_cond_predicate(atom/1). 814safe_cond_predicate(integer/1). 815safe_cond_predicate(ground/1). 816 817elif(true, _, else_false) :- !. 818elif(false, true, true) :- !. 819elif(True, _, True). 820 821negate(true, false). 822negate(false, true). 823negate(else_false, else_false). 824 825 /******************************* 826 * SOURCES * 827 *******************************/
process_source(Src) :-
prolog_open_source(Src, In),
call_cleanup(process(Src), prolog_close_source(In)).
849prolog_open_source(Src, Fd) :- 850 '$push_input_context'(source), 851 catch(do_open_source(Src, Fd, Hooked), 852 E, 853 ( '$pop_input_context', 854 throw(E) 855 )), 856 skip_hashbang(Fd), 857 push_operators([]), 858 '$current_source_module'(SM), 859 '$save_lex_state'(LexState, []), 860 asserta(open_source(Fd, state(Hooked, Src, LexState, SM))). 861 862do_open_source(Src, Stream, stream) :- 863 is_stream(Src), 864 !, 865 Stream = Src. 866do_open_source(Src, Stream, hooked) :- 867 prolog:xref_open_source(Src, Stream), 868 !. 869do_open_source(Src, Stream, opened) :- 870 open(Src, read, Stream). 871 872 873skip_hashbang(Fd) :- 874 catch(( peek_char(Fd, #) % Deal with #! script 875 -> skip(Fd, 10) 876 ; true 877 ), E, 878 ( close(Fd, [force(true)]), 879 '$pop_input_context', 880 throw(E) 881 )).
expand_term(end_of_file, _) to allow expansion
modules to clean-up.899prolog_close_source(In) :- 900 call_cleanup( 901 restore_source_context(In, Hooked, Src), 902 close_source(Hooked, Src, In)). 903 904close_source(stream, _Src, _Stream) :- 905 !, 906 '$pop_input_context'. 907close_source(hooked, Src, In) :- 908 catch(prolog:xref_close_source(Src, In), _, false), 909 !, 910 '$pop_input_context'. 911close_source(_, _Src, In) :- % If hook fails we must do normal close 912 close(In, [force(true)]), 913 '$pop_input_context'. 914 915restore_source_context(In, Hooked, Src) :- 916 ( at_end_of_stream(In) 917 -> true 918 ; ignore(catch(expand(end_of_file, _, In, _), _, true)) 919 ), 920 pop_operators, 921 retractall(mode(In, _)), 922 retractall(syntax_option(In, _)), 923 ( retract(open_source(In, state(Hooked, Src, LexState, SM))) 924 -> '$restore_lex_state'(LexState), 925 '$set_source_module'(SM) 926 ; assertion(fail) 927 ).
force(true) is used.942prolog_canonical_source(Source, Src) :- 943 var(Source), 944 !, 945 Src = Source. 946prolog_canonical_source(User, user) :- 947 User == user, 948 !. 949prolog_canonical_source(Stream, Src) :- 950 is_stream(Stream), 951 !, 952 Src = Stream. 953prolog_canonical_source(Src, Id) :- % Call hook 954 prolog:xref_source_identifier(Src, Id), 955 !. 956prolog_canonical_source(Source, Src) :- 957 loaded_source_file(Source), 958 !, 959 Src = Source. 960prolog_canonical_source(Source, Src) :- 961 absolute_file_name(Source, Src, 962 [ file_type(prolog), 963 access(read), 964 file_errors(fail) 965 ]), 966 !. 967 968% loaded_source_file(+Source) is semidet. 969% 970% True if Source is the name of a loaded source file. Unlike 971% source_file/1, Source is not resolved: a relative name or alias 972% for a loaded file must canonicalise to its absolute name, the same 973% as when the file is not loaded. 974 975loaded_source_file(Source) :- 976 atom(Source), 977 '$time_source_file'(Source, Time, _), 978 float(Time), 979 !.
987file_name_on_path(Path, ShortId) :-
988 ( file_alias_path(Alias, Dir),
989 atom_concat(Dir, Local, Path)
990 -> ( Alias == '.'
991 -> ShortId = Local
992 ; file_name_extension(Base, pl, Local)
993 -> ShortId =.. [Alias, Base]
994 ; ShortId =.. [Alias, Local]
995 )
996 ; ShortId = Path
997 ).1005:- dynamic 1006 alias_cache/2. 1007 1008file_alias_path(Alias, Dir) :- 1009 ( alias_cache(_, _) 1010 -> true 1011 ; build_alias_cache 1012 ), 1013 ( nonvar(Dir) 1014 -> ensure_slash(Dir, DirSlash), 1015 alias_cache(Alias, DirSlash) 1016 ; alias_cache(Alias, Dir) 1017 ). 1018 1019build_alias_cache :- 1020 findall(t(DirLen, AliasLen, Alias, Dir), 1021 search_path(Alias, Dir, AliasLen, DirLen), Ts), 1022 sort(0, >, Ts, List), 1023 forall(member(t(_, _, Alias, Dir), List), 1024 assert(alias_cache(Alias, Dir))). 1025 1026search_path('.', Here, 999, DirLen) :- 1027 working_directory(Here0, Here0), 1028 ensure_slash(Here0, Here), 1029 atom_length(Here, DirLen). 1030search_path(Alias, Dir, AliasLen, DirLen) :- 1031 user:file_search_path(Alias, _), 1032 Alias \== autoload, % TBD: Multifile predicate? 1033 Alias \== noautoload, 1034 Spec =.. [Alias,'.'], 1035 atom_length(Alias, AliasLen0), 1036 AliasLen is 1000 - AliasLen0, % must do reverse sort 1037 absolute_file_name(Spec, Dir0, 1038 [ file_type(directory), 1039 access(read), 1040 solutions(all), 1041 file_errors(fail) 1042 ]), 1043 ensure_slash(Dir0, Dir), 1044 atom_length(Dir, DirLen). 1045 1046ensure_slash(Dir, Dir) :- 1047 sub_atom(Dir, _, _, 0, /), 1048 !. 1049ensure_slash(Dir0, Dir) :- 1050 atom_concat(Dir0, /, Dir).
?- path_segments_atom(a/b/c, X). X = 'a/b/c'. ?- path_segments_atom(S, 'a/b/c'), display(S). /(/(a,b),c) S = a/b/c.
This predicate is part of the Prolog source library because SWI-Prolog allows writing paths as /-nested terms and source-code analysis programs often need this.
1071path_segments_atom(Segments, Atom) :- 1072 var(Atom), 1073 !, 1074 ( atomic(Segments) 1075 -> Atom = Segments 1076 ; segments_to_list(Segments, List, []) 1077 -> atomic_list_concat(List, /, Atom) 1078 ; throw(error(type_error(file_path, Segments), _)) 1079 ). 1080path_segments_atom(Segments, Atom) :- 1081 atomic_list_concat(List, /, Atom), 1082 parts_to_path(List, Segments). 1083 1084segments_to_list(Var, _, _) :- 1085 var(Var), !, fail. 1086segments_to_list(A/B, H, T) :- 1087 segments_to_list(A, H, T0), 1088 segments_to_list(B, T0, T). 1089segments_to_list(A, [A|T], T) :- 1090 atomic(A). 1091 1092parts_to_path([One], One) :- !. 1093parts_to_path(List, More/T) :- 1094 ( append(H, [T], List) 1095 -> parts_to_path(H, More) 1096 ).
true (default false), recurse into subdirectoriestrue (default loaded), only report loaded files.
Other options are passed to absolute_file_name/3, unless
loaded(true) is passed.
1111directory_source_files(Dir, SrcFiles, Options) :- 1112 option(if(loaded), Options, loaded), 1113 !, 1114 absolute_file_name(Dir, AbsDir, [file_type(directory), access(read)]), 1115 ( option(recursive(true), Options) 1116 -> ensure_slash(AbsDir, Prefix), 1117 findall(F, ( source_file(F), 1118 sub_atom(F, 0, _, _, Prefix) 1119 ), 1120 SrcFiles) 1121 ; findall(F, ( source_file(F), 1122 file_directory_name(F, AbsDir) 1123 ), 1124 SrcFiles) 1125 ). 1126directory_source_files(Dir, SrcFiles, Options) :- 1127 absolute_file_name(Dir, AbsDir, [file_type(directory), access(read)]), 1128 directory_files(AbsDir, Files), 1129 phrase(src_files(Files, AbsDir, Options), SrcFiles). 1130 1131src_files([], _, _) --> 1132 []. 1133src_files([H|T], Dir, Options) --> 1134 { file_name_extension(_, Ext, H), 1135 user:prolog_file_type(Ext, prolog), 1136 \+ user:prolog_file_type(Ext, qlf), 1137 dir_file_path(Dir, H, File0), 1138 absolute_file_name(File0, File, 1139 [ file_errors(fail) 1140 | Options 1141 ]) 1142 }, 1143 !, 1144 [File], 1145 src_files(T, Dir, Options). 1146src_files([H|T], Dir, Options) --> 1147 { \+ special(H), 1148 option(recursive(true), Options), 1149 dir_file_path(Dir, H, SubDir), 1150 exists_directory(SubDir), 1151 !, 1152 catch(directory_files(SubDir, Files), _, fail) 1153 }, 1154 !, 1155 src_files(Files, SubDir, Options), 1156 src_files(T, Dir, Options). 1157src_files([_|T], Dir, Options) --> 1158 src_files(T, Dir, Options). 1159 1160special(.). 1161special(..). 1162 1163% avoid dependency on library(filesex), which also pulls a foreign 1164% dependency. 1165dir_file_path(Dir, File, Path) :- 1166 ( sub_atom(Dir, _, _, 0, /) 1167 -> atom_concat(Dir, File, Path) 1168 ; atom_concat(Dir, /, TheDir), 1169 atom_concat(TheDir, File, Path) 1170 ).
If a position in TermPos is a variable, the validation of the
corresponding part of Term succeeds. This matches the
term_expansion/4 treats "unknown" layout information. If part of a
TermPos is given, then all its "from" and "to" information must be
specified; for example, string_position(X,Y) is an error but
string_position(0,5) succeeds. The position values are checked for
being plausible -- e.g., string_position(5,0) will fail.
This should always succeed:
read_term(Term, [subterm_positions(TermPos)]), valid_term_position(Term, TermPos)
1203valid_term_position(Term, TermPos) :- 1204 valid_term_position(0, 0x7fffffffffffffff, Term, TermPos). 1205 1206valid_term_position(OuterFrom, OuterTo, _Term, TermPos), 1207 var(TermPos), 1208 OuterFrom =< OuterTo => true. 1209valid_term_position(OuterFrom, OuterTo, Var, From-To), 1210 var(Var), 1211 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => true. 1212valid_term_position(OuterFrom, OuterTo, Atom, From-To), 1213 atom(Atom), 1214 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => true. 1215valid_term_position(OuterFrom, OuterTo, Number, From-To), 1216 number(Number), 1217 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => true. 1218valid_term_position(OuterFrom, OuterTo, [], From-To), 1219 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => true. 1220valid_term_position(OuterFrom, OuterTo, String, string_position(From,To)), 1221 ( string(String) 1222 -> true 1223 ; is_of_type(codes, String) 1224 -> true 1225 ; is_of_type(chars, String) 1226 -> true 1227 ; atom(String) 1228 ), 1229 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => true. 1230valid_term_position(OuterFrom, OuterTo, {Arg}, 1231 brace_term_position(From,To,ArgPos)), 1232 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1233 valid_term_position(From, To, Arg, ArgPos). 1234valid_term_position(OuterFrom, OuterTo, [Hd|Tl], 1235 list_position(From,To,ElemsPos,none)), 1236 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1237 term_position_list_tail([Hd|Tl], _HdPart, []), 1238 maplist(valid_term_position, [Hd|Tl], ElemsPos). 1239valid_term_position(OuterFrom, OuterTo, [Hd|Tl], 1240 list_position(From, To, ElemsPos, TailPos)), 1241 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1242 term_position_list_tail([Hd|Tl], HdPart, Tail), 1243 maplist(valid_term_position(From,To), HdPart, ElemsPos), 1244 valid_term_position(Tail, TailPos). 1245valid_term_position(OuterFrom, OuterTo, Term, 1246 term_position(From,To, FFrom,FTo,SubPos)), 1247 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1248 compound_name_arguments(Term, Name, Arguments), 1249 valid_term_position(Name, FFrom-FTo), 1250 maplist(valid_term_position(From,To), Arguments, SubPos). 1251valid_term_position(OuterFrom, OuterTo, Dict, 1252 dict_position(From,To,TagFrom,TagTo,KeyValuePosList)), 1253 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1254 dict_pairs(Dict, Tag, Pairs), 1255 valid_term_position(Tag, TagFrom-TagTo), 1256 foldl(valid_term_position_dict(From,To), Pairs, KeyValuePosList, []). 1257% key_value_position(From, To, SepFrom, SepTo, Key, KeyPos, ValuePos) 1258% is handled in valid_term_position_dict. 1259valid_term_position(OuterFrom, OuterTo, Term, 1260 parentheses_term_position(From,To,ContentPos)), 1261 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1262 valid_term_position(From, To, Term, ContentPos). 1263valid_term_position(OuterFrom, OuterTo, _Term, 1264 quasi_quotation_position(From,To, 1265 SyntaxTerm,SyntaxPos,_ContentPos)), 1266 valid_term_position_from_to(OuterFrom, OuterTo, From, To) => 1267 valid_term_position(From, To, SyntaxTerm, SyntaxPos). 1268 1269valid_term_position_from_to(OuterFrom, OuterTo, From, To) :- 1270 integer(OuterFrom), 1271 integer(OuterTo), 1272 integer(From), 1273 integer(To), 1274 OuterFrom =< OuterTo, 1275 From =< To, 1276 OuterFrom =< From, 1277 To =< OuterTo. 1278 1279:- det(valid_term_position_dict/5). 1280valid_term_position_dict(OuterFrom, OuterTo, Key-Value, 1281 KeyValuePosList0, KeyValuePosList1) :- 1282 selectchk(key_value_position(From,To,SepFrom,SepTo,Key,KeyPos,ValuePos), 1283 KeyValuePosList0, KeyValuePosList1), 1284 valid_term_position_from_to(OuterFrom, OuterTo, From, To), 1285 valid_term_position_from_to(OuterFrom, OuterTo, SepFrom, SepTo), 1286 SepFrom >= OuterFrom, 1287 valid_term_position(From, SepFrom, Key, KeyPos), 1288 valid_term_position(SepTo, To, Value, ValuePos).
append(HdPart, [Tail], List) for proper lists, but also
works for inproper lists, in which case it unifies Tail with the
tail of the partial list. HdPart is always a proper list:
?- prolog_source:term_position_list_tail([a,b,c], Hd, Tl). Hd = [a, b, c], Tl = []. ?- prolog_source:term_position_list_tail([a,b|X], Hd, Tl). X = Tl, Hd = [a, b].
1305:- det(term_position_list_tail/3). 1306term_position_list_tail([X|Xs], HdPart, Tail) => 1307 HdPart = [X|HdPart2], 1308 term_position_list_tail(Xs, HdPart2, Tail). 1309term_position_list_tail(Tail0, HdPart, Tail) => 1310 HdPart = [], 1311 Tail0 = Tail. 1312 1313 1314 /******************************* 1315 * MESSAGES * 1316 *******************************/ 1317 1318:- multifile 1319 prolog:message//1. 1320 1321prologmessage(quasi_quotation(undeclared, Syntax)) --> 1322 [ 'Undeclared quasi quotation syntax: ~w'-[Syntax], nl, 1323 'Autoloading can be defined using prolog:quasi_quotation_syntax/2' 1324 ]
Examine Prolog source-files
This module provides predicates to open, close and read terms from Prolog source-files. This may seem easy, but there are a couple of problems that must be taken care of.
This module concentrates these issues in a single library. Intended users of the library are:
prolog_xref.plprolog_clause.plprolog_colour.pl