logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

prolog.lua (20409B)


  1. -- Copyright 2006-2024 Mitchell. See LICENSE.
  2. -- Lexer enhanced to conform to the realities of Prologs on the ground by
  3. -- Michael T. Richter. Copyright is explicitly assigned back to Mitchell.
  4. -- Prolog LPeg lexer.
  5. --[[
  6. Prologs are notoriously fractious with many barely-compatible dialects. To
  7. make Textadept more useful for these cases, directives and keywords are
  8. grouped by dialect. Selecting a dialect is a simple matter of setting the
  9. buffer/lexer property "prolog.dialect" in init.lua. Dialects currently in
  10. the lexer file are:
  11. - 'iso': the generic ISO standard without modules.
  12. - 'gprolog': GNU Prolog.
  13. - 'swipl': SWI-Prolog.
  14. The default dialect is 'iso' if none is defined. (You probably don't want
  15. this.)
  16. Note that there will be undoubtedly duplicated entries in various categories
  17. because of the flexibility of Prolog and the automated tools used to gather
  18. most information. This is not an issue, however, because directives override
  19. arity-0 predicates which override arity-1+ predicates which override bifs
  20. which override operators.
  21. ]]
  22. local lexer = require('lexer')
  23. local token, word_match = lexer.token, lexer.word_match
  24. local P, S = lpeg.P, lpeg.S
  25. local lex = lexer.new('prolog')
  26. local dialect = lexer.property['prolog.dialect']
  27. if dialect ~= 'gprolog' and dialog ~= 'swipl' then dialect = 'iso' end
  28. -- Directives.
  29. local directives = {}
  30. directives.iso = [[
  31. -- Gathered by inspection of GNU Prolog documentation.
  32. dynamic multifile discontiguous include ensure_loaded op char_conversion
  33. set_prolog_flag initialization
  34. ]]
  35. directives.gprolog = directives.iso .. [[
  36. -- Gathered by inspection of GNU Prolog documentation.
  37. public ensure_linked built_in if else endif elif foreign
  38. ]]
  39. directives.swipl = directives.iso .. [[
  40. -- Gathered by liberal use of grep on the SWI source and libraries.
  41. coinductive current_predicate_option expects_dialect http_handler listen
  42. module multifile use_foreign_library use_module dynamic http_handler
  43. initialization json_object multifile record use_module abolish
  44. arithmetic_function asserta at_halt begin_tests chr_constraint chr_option
  45. chr_type clear_cache constraints consult create_prolog_flag
  46. current_prolog_flag debug discontiguous dynamic elif else encoding end_tests
  47. endif expects_dialect export forall format format_predicate html_meta
  48. html_resource http_handler http_request_expansion if include
  49. init_color_term_flag init_options initialization json_object
  50. lazy_list_iterator license listen load_extensions load_files
  51. load_foreign_library meta_predicate mode module module_transparent multifile
  52. noprofile op pce_begin_class pce_end_class pce_global pce_group persistent
  53. pop_operators pred predicate_options print_message prolog_load_context prompt
  54. public push_hprolog_library push_ifprolog_library, push_operators
  55. push_sicstus_library push_xsb_library push_yap_library, quasi_quotation_syntax
  56. record redefine_system_predicate reexport register_iri_scheme residual_goals
  57. retract set_module set_prolog_flag set_script_dir set_test_options setenv
  58. setting style_check table thread_local thread_local message type
  59. use_class_template use_foreign_library use_module utter volatile build_schema
  60. chr_constraint chr_option chr_type cql_option determinate discontiguous
  61. dynamic endif format_predicate if initialization license meta_predicate mode
  62. module multifile op reexport thread_local use_module volatile
  63. ]]
  64. lex:add_rule('directive',
  65. token(lexer.WHITESPACE, lexer.starts_line(S(' \t'))^0) *
  66. token(lexer.OPERATOR, ':-') *
  67. token(lexer.WHITESPACE, S(' \t')^0) *
  68. token(lexer.PREPROCESSOR, word_match(directives[dialect])))
  69. -- Whitespace.
  70. lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1))
  71. -- Keywords.
  72. local zero_arity_keywords = {}
  73. zero_arity_keywords.iso = [[
  74. -- eyeballed from GNU Prolog documentation
  75. true fail pi float_overflow int_overflow int_underflow undefined asserta
  76. assertz retract retractall clause abolish current_predicate findall bagof
  77. setof at_end_of_stream flush_output nl halt false
  78. ]]
  79. zero_arity_keywords.gprolog = [[
  80. -- Collected automatically via current_predicate/1 with some cleanup.
  81. at_end_of_stream wam_debug listing flush_output fail told false top_level
  82. shell trace debugging seen repeat abort nl statistics halt notrace randomize
  83. true nospyall nodebug debug stop break
  84. ]]
  85. zero_arity_keywords.swipl = [[
  86. -- Collected automatically via current_predicate/1 with some cleanup.
  87. noprotocol compiling ttyflush true abort license known_licenses
  88. print_toplevel_variables initialize mutex_statistics break reset_profiler
  89. win_has_menu version prolog abolish_nonincremental_tables false halt undefined
  90. abolish_all_tables reload_library_index garbage_collect repeat nospyall
  91. tracing trace notrace trim_stacks garbage_collect_clauses
  92. garbage_collect_atoms mutex_unlock_all seen told nl debugging fail
  93. at_end_of_stream attach_packs flush_output true
  94. ]]
  95. local one_plus_arity_keywords = {}
  96. one_plus_arity_keywords.iso = [[
  97. -- eyeballed from GNU Prolog documentation
  98. call catch throw var nonvar atom integer float number atomic compound
  99. callable ground unify_with_occurs_check compare functor arg copy_term
  100. term_variables subsumes_term acyclic_term predicate_property current_input
  101. current_output set_input set_output open close current_stream stream_property
  102. set_stream_position get_char get_code is peek_char peek_code put_char putcode
  103. get_byte peek_byte read_term read write_term write writeq write_canonical
  104. char_conversion current_char_conversion call once repeat atom_length
  105. atom_concat sub_atom char_code atom_chars atom_codes
  106. ]]
  107. one_plus_arity_keywords.gprolog = [[
  108. -- Collected automatically via current_predicate/1 with some cleanup.
  109. abolish absolute_file_name acyclic_term add_linedit_completion
  110. add_stream_alias add_stream_mirror append architecture arg argument_counter
  111. argument_list argument_value asserta assertz at_end_of_stream atom atom_chars
  112. atom_codes atom_concat atom_length atom_property atomic bagof between
  113. bind_variables call call_det call_with_args callable catch change_directory
  114. char_code char_conversion character_count clause close close_input_atom_stream
  115. close_input_chars_stream close_input_codes_stream close_output_atom_stream
  116. close_output_chars_stream close_output_codes_stream compare compound consult
  117. copy_term cpu_time create_pipe current_alias current_atom current_bip_name
  118. current_char_conversion current_input current_mirror current_op current_output
  119. current_predicate current_prolog_flag current_stream date_time
  120. decompose_file_name delete delete_directory delete_file directory_files
  121. display display_to_atom display_to_chars display_to_codes environ exec
  122. expand_term fd_all_different fd_at_least_one fd_at_most_one fd_atleast
  123. fd_atmost fd_cardinality fd_dom fd_domain fd_domain_bool fd_element
  124. fd_element_var fd_exactly fd_has_extra_cstr fd_has_vector fd_labeling
  125. fd_labelingff fd_max fd_max_integer fd_maximize fd_min fd_minimize
  126. fd_not_prime fd_only_one fd_prime fd_reified_in fd_relation fd_relationc
  127. fd_set_vector_max fd_size fd_use_vector fd_var fd_vector_max file_exists
  128. file_permission file_property find_linedit_completion findall flatten float
  129. flush_output for forall fork_prolog format format_to_atom format_to_chars
  130. format_to_codes functor g_array_size g_assign g_assignb g_dec g_deco g_inc
  131. g_inco g_link g_read g_reset_bit g_set_bit g_test_reset_bit g_test_set_bit
  132. generic_var get get_byte get_char get_code get_key get_key_no_echo
  133. get_linedit_prompt get_print_stream get_seed get0 ground halt host_name
  134. hostname_address integer is_absolute_file_name is_list is_relative_file_name
  135. keysort last last_read_start_line_column leash length line_count line_position
  136. list list_or_partial_list listing load lower_upper make_directory maplist
  137. max_list member memberchk min_list msort name name_query_vars
  138. name_singleton_vars new_atom nl non_fd_var non_generic_var nonvar nospy nth
  139. nth0 nth1 number number_atom number_chars number_codes numbervars once op open
  140. open_input_atom_stream open_input_chars_stream open_input_codes_stream
  141. open_output_atom_stream open_output_chars_stream open_output_codes_stream
  142. os_version partial_list peek_byte peek_char peek_code permutation phrase popen
  143. portray_clause predicate_property prefix print print_to_atom print_to_chars
  144. print_to_codes prolog_file_name prolog_pid put put_byte put_char put_code
  145. random read read_atom read_from_atom read_from_chars read_from_codes
  146. read_integer read_number read_pl_state_file read_term read_term_from_atom
  147. read_term_from_chars read_term_from_codes read_token read_token_from_atom
  148. read_token_from_chars read_token_from_codes real_time remove_stream_mirror
  149. rename_file retract retractall reverse see seeing seek select send_signal
  150. set_bip_name set_input set_linedit_prompt set_output set_prolog_flag set_seed
  151. set_stream_buffering set_stream_eof_action set_stream_line_column
  152. set_stream_position set_stream_type setarg setof shell skip sleep socket
  153. socket_accept socket_bind socket_close socket_connect socket_listen sort spawn
  154. spy spypoint_condition sr_change_options sr_close sr_current_descriptor
  155. sr_error_from_exception sr_get_error_counters sr_get_file_name
  156. sr_get_include_list sr_get_include_stream_list sr_get_module sr_get_position
  157. sr_get_size_counters sr_get_stream sr_new_pass sr_open sr_read_term
  158. sr_set_error_counters sr_write_error sr_write_message statistics
  159. stream_line_column stream_position stream_property sub_atom sublist
  160. subsumes_term subtract succ suffix sum_list syntax_error_info system
  161. system_time tab tell telling temporary_file temporary_name term_hash term_ref
  162. term_variables throw unget_byte unget_char unget_code unify_with_occurs_check
  163. unlink user_time var wait working_directory write write_canonical
  164. write_canonical_to_atom write_canonical_to_chars write_canonical_to_codes
  165. write_pl_state_file write_term write_term_to_atom write_term_to_chars
  166. write_term_to_codes write_to_atom write_to_chars write_to_codes writeq
  167. writeq_to_atom writeq_to_chars writeq_to_codes
  168. ]]
  169. one_plus_arity_keywords.swipl = [[
  170. -- Collected automatically via current_predicate/1 with some cleanup.
  171. prolog_exception_hook term_expansion expand_answer message_property resource
  172. help goal_expansion file_search_path prolog_clause_name thread_message_hook
  173. prolog_file_type goal_expansion prolog_predicate_name exception writeln
  174. term_expansion expand_query url_path message_hook library_directory resource
  175. portray prolog_load_file prolog_list_goal ansi_format source_file_property
  176. asserta call_dcg source_location wait_for_input locale_destroy set_locale
  177. read_pending_codes thread_join open_dde_conversation win_folder protocol
  178. copy_stream_data current_locale read_pending_chars win_add_dll_directory
  179. protocola thread_property win_shell goal_expansion phrase gc_file_search_cache
  180. dcg_translate_rule protocolling win_registry_get_value term_expansion
  181. dcg_translate_rule assert copy_stream_data once bagof prompt1 tnot assertz
  182. phrase sort ignore thread_statistics assert locale_create
  183. win_remove_dll_directory term_expansion read_term asserta clause assertz
  184. predicate_option_type is_thread get_single_char set_prolog_IO expand_goal
  185. ground message_queue_create locale_property close_dde_conversation
  186. goal_expansion clause zipper_open_new_file_in_zip term_to_atom with_output_to
  187. module expand_term redefine_system_predicate thread_detach dde_execute
  188. term_string read_clause compile_predicates predicate_option_mode noprofile
  189. read_term_from_atom cancel_halt non_terminal atom_to_term line_position frozen
  190. dde_request findnsols prolog_skip_level prolog_current_choice get get_attrs
  191. license var_property nb_delete unwrap_predicate zipper_open_current put_attrs
  192. dde_poke set_stream read_term zip_file_info_ memberchk seek expand_goal get0
  193. call var integer attach_packs byte_count zipper_goto findnsols character_count
  194. expand_term get_flag atom line_count set_flag atomic tab create_prolog_flag
  195. copy_term import_module verbose_expansion b_setval duplicate_term
  196. prolog_load_context attach_packs prolog_listen b_getval prolog_frame_attribute
  197. prompt copy_term_nat nb_linkval tab prolog_choice_attribute set_prolog_flag
  198. nb_getval prolog_skip_frame del_attrs skip sort license open_null_stream
  199. nb_current prolog_listen msort is_list is_stream get keysort win_shell
  200. prolog_unlisten notrace get0 add_import_module wildcard_match profiler
  201. delete_directory trie_gen_compiled expand_file_name file_name_extension
  202. delete_file writeq win_module_file call write get_dict win_exec
  203. directory_files trie_insert make_directory engine_next_reified del_dict sleep
  204. getenv call_continuation trie_gen_compiled prolog_to_os_filename
  205. is_absolute_file_name trie_insert engine_fetch engine_create strip_module call
  206. delete_import_module write_canonical compile_aux_clauses setenv callable
  207. is_engine write_term call set_module call halt catch findall trie_gen
  208. trie_destroy rename_file shift unify_with_occurs_check engine_yield forall
  209. unsetenv trie_term file_directory_name version current_engine file_base_name
  210. engine_self import trie_gen trie_lookup write_term trie_update freeze
  211. engine_post export put_dict same_file trie_new call trie_delete start_tabling
  212. is_trie residual_goals thread_peek_message thread_get_message dict_pairs
  213. set_end_of_stream call_cleanup current_predicate arg dict_create
  214. thread_setconcurrency read_link is_dict at_halt tmp_file not put_dict
  215. setup_call_cleanup abolish_nonincremental_tables time_file
  216. start_subsumptive_tabling char_conversion compound sub_atom access_file call
  217. call_cleanup abolish nonvar current_functor abolish_module_tables
  218. subsumes_term engine_post call retractall compare engine_next prolog_cut_to
  219. size_file current_char_conversion predicate_property nonground engine_destroy
  220. message_queue_property format abolish qcompile thread_send_message stream_pair
  221. message_queue_create same_term number select_dict catch_with_backtrace
  222. thread_get_message thread_send_message win_insert_menu_item message_queue_set
  223. <meta-call> exists_directory copy_term nb_set_dict prolog_nodebug functor
  224. current_table cyclic_term untable read exists_file thread_peek_message
  225. b_set_dict engine_create prolog_debug acyclic_term writeln get_dict
  226. compound_name_arity abolish_table_subgoals start_tabling trie_insert
  227. nb_link_dict message_queue_destroy thread_get_message is_dict nth_clause
  228. absolute_file_name term_singletons make_library_index set_output retract
  229. context_module current_trie term_attvars load_files get_char ensure_loaded
  230. current_input prolog_current_frame make_library_index term_variables
  231. compound_name_arguments reexport autoload_path get_code set_input flag
  232. thread_create use_module findall thread_join call_with_inference_limit
  233. var_number dwim_match consult peek_code close nospy print_message
  234. term_variables trie_property read_history get_byte default_module get_byte
  235. print on_signal get_char call_residue_vars dwim_match atom_prefix unifiable
  236. use_module numbervars load_files get_code open format_time
  237. copy_predicate_clauses reexport leash current_output sub_string close
  238. format_time atom_codes stamp_date_time require name open_shared_object open
  239. atom_chars current_predicate format tmp_file_stream term_hash rational
  240. source_file reset atom_concat atom_length current_prolog_flag rational
  241. dwim_predicate date_time_stamp stream_property string_upper setlocale format
  242. writeln current_module normalize_space writeq current_flag shell upcase_atom
  243. qcompile char_code atomic_concat read string_lower write term_string
  244. numbervars working_directory number_codes set_prolog_gc_thread downcase_atom
  245. format_predicate number_string open_shared_object style_check char_type print
  246. stream_position_data code_type write_canonical number_chars length
  247. current_arithmetic_function atomic_list_concat del_attr read_string zip_unlock
  248. open_resource string_length zip_lock see erase open_resource setof
  249. atomic_list_concat current_format_predicate current_resource with_mutex
  250. atomics_to_string term_hash absolute_file_name deterministic current_atom
  251. thread_create collation_key get_attr variant_hash string_concat atom_number
  252. put put_attr variant_sha1 thread_signal mutex_unlock tty_size current_key
  253. mutex_create fill_buffer expand_file_search_path blob shell
  254. register_iri_scheme skip fast_read divmod mutex_trylock thread_self put
  255. mutex_property fast_write mutex_lock current_blob sub_atom_icasechk
  256. mutex_destroy fast_term_serialized split_string set_stream_position recorda
  257. telling setarg thread_exit zip_open_stream instance mutex_create statistics
  258. append get_time zip_close_ tell atomics_to_string clause_property attvar
  259. zip_clone seeing nth_integer_root_and_remainder recorda put_byte string_chars
  260. spy recordz print_message_lines current_op put_char nl source_file
  261. string_codes op setup_call_catcher_cleanup nb_linkarg recorded put_code
  262. peek_byte apply module_property atom_string nb_setarg succ recordz
  263. message_to_string close_shared_object peek_char between recorded visible plus
  264. call_shared_object_function peek_code peek_byte set_prolog_stack float throw
  265. at_end_of_stream get_string_code call_with_depth_limit random_property
  266. flush_output peek_string open_xterm peek_char open_string string_code
  267. set_random prolog_stack_property put_char unload_file nb_setval put_byte
  268. current_signal put_code write_length string read_string text_to_string
  269. ]]
  270. lex:add_rule('keyword', token(lexer.KEYWORD,
  271. word_match(zero_arity_keywords[dialect]) +
  272. word_match(one_plus_arity_keywords[dialect]) * #P('(')))
  273. -- BIFs.
  274. local bifs = {}
  275. bifs.iso = [[
  276. -- eyeballed from GNU Prolog documentation
  277. xor abs sign min max sqrt tan atan atan2 cos acos sin asin exp log float
  278. ceiling floor round truncate float_fractional_part float_integer_part rem div
  279. mod
  280. ]]
  281. bifs.gprolog = bifs.iso .. [[
  282. -- eyeballed from GNU Prolog documentation
  283. inc dec lsb msb popcount gcd tanh atanh cosh acosh sinh asinh log10 rnd
  284. ]]
  285. bifs.swipl = [[
  286. -- Collected automatically via current_arithmetic_function/1 with some
  287. -- cleanup.
  288. abs acos acosh asinh atan atan atanh atan2 ceil ceiling copysign cos cosh
  289. cputime div getbit e epsilon erf erfc eval exp float float_fractional_part
  290. float_integer_part floor gcd inf integer lgamma log log10 lsb max min mod msb
  291. nan pi popcount powm random random_float rational rationalize rdiv rem round
  292. sign sin sinh sqrt tan tanh truncate xor
  293. ]]
  294. lex:add_rule('bif', token(lexer.FUNCTION, word_match(bifs[dialect]) * #P('(')))
  295. -- Numbers.
  296. local decimal_group = S('+-')^-1 * (lexer.digit + '_')^1
  297. local binary_number = '0b' * (S('01') + '_')^1
  298. local character_code = '0\'' * S('\\')^-1 * lexer.graph
  299. local decimal_number = decimal_group * ('.' * decimal_group)^-1 *
  300. ('e' * decimal_group)^-1
  301. local hexadecimal_number = '0x' * (lexer.xdigit + '_')^1
  302. local octal_number = '0o' * (S('01234567') + '_')^1
  303. lex:add_rule('number', token(lexer.NUMBER, character_code + binary_number +
  304. hexadecimal_number + octal_number + decimal_number))
  305. -- Comments.
  306. local line_comment = lexer.to_eol('%')
  307. local block_comment = lexer.range('/*', '*/')
  308. lex:add_rule('comment', token(lexer.COMMENT, line_comment + block_comment))
  309. -- Operators.
  310. local operators = {}
  311. operators.iso = [[
  312. -- Collected automatically via current_op/3 with some cleanup and comparison
  313. -- to docs.
  314. rem div mod is
  315. ]]
  316. operators.gprolog = operators.iso -- GNU Prolog's textual operators are the same
  317. operators.swipl = [[
  318. -- Collected automatically via current_op/3 with some cleanup.
  319. is as volatile mod discontiguous div rdiv meta_predicate public xor
  320. module_transparent multifile table dynamic thread_initialization thread_local
  321. initialization rem
  322. ]]
  323. lex:add_rule('operator', token(lexer.OPERATOR, word_match(operators[dialect]) +
  324. S('-!+\\|=:;&<>()[]{}/*^@?.')))
  325. -- Variables.
  326. lex:add_rule('variable', token(lexer.VARIABLE, (lexer.upper + '_') *
  327. (lexer.word^1 + lexer.digit^1 + P('_')^1)^0))
  328. -- Identifiers.
  329. lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word))
  330. -- Strings.
  331. local sq_str = lexer.range("'", true)
  332. local dq_str = lexer.range('"', true)
  333. lex:add_rule('string', token(lexer.STRING, sq_str + dq_str))
  334. lexer.property['scintillua.comment'] = '%'
  335. return lex