itp-interface 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (485) hide show
  1. itp_interface/__init__.py +0 -0
  2. itp_interface/agent/__init__.py +0 -0
  3. itp_interface/agent/simple_proof_agent.py +100 -0
  4. itp_interface/coq_ser_api/__init__.py +165 -0
  5. itp_interface/coq_ser_api/contexts.py +283 -0
  6. itp_interface/coq_ser_api/coq_agent.py +459 -0
  7. itp_interface/coq_ser_api/coq_backend.py +135 -0
  8. itp_interface/coq_ser_api/coq_util.py +839 -0
  9. itp_interface/coq_ser_api/example.py +67 -0
  10. itp_interface/coq_ser_api/lsp_backend.py +375 -0
  11. itp_interface/coq_ser_api/py.typed +0 -0
  12. itp_interface/coq_ser_api/serapi_backend.py +841 -0
  13. itp_interface/coq_ser_api/util.py +145 -0
  14. itp_interface/coq_ser_api_old/__init__.py +2583 -0
  15. itp_interface/coq_ser_api_old/contexts.py +172 -0
  16. itp_interface/coq_ser_api_old/util.py +146 -0
  17. itp_interface/lean_server/__init__.py +0 -0
  18. itp_interface/lean_server/commands.py +484 -0
  19. itp_interface/lean_server/lean3_search_tool.py +358 -0
  20. itp_interface/lean_server/lean4_repl_interface.py +151 -0
  21. itp_interface/lean_server/lean4_utils.py +255 -0
  22. itp_interface/lean_server/lean_cmd_server.py +111 -0
  23. itp_interface/lean_server/lean_context.py +60 -0
  24. itp_interface/lean_server/lean_sync_server.py +174 -0
  25. itp_interface/lean_server/lean_utils.py +199 -0
  26. itp_interface/lean_server/py.typed +1 -0
  27. itp_interface/main/__init__.py +0 -0
  28. itp_interface/main/config/afp_data_gen.yaml +14 -0
  29. itp_interface/main/config/benchmark/CompCert.yaml +366 -0
  30. itp_interface/main/config/benchmark/GeoCoq.yaml +930 -0
  31. itp_interface/main/config/benchmark/UniMath.yaml +2690 -0
  32. itp_interface/main/config/benchmark/afp_isabelle.yaml +29200 -0
  33. itp_interface/main/config/benchmark/agent_proverbot_hard.yaml +247 -0
  34. itp_interface/main/config/benchmark/category-theory.yaml +470 -0
  35. itp_interface/main/config/benchmark/compcert_118_subset.yaml +148 -0
  36. itp_interface/main/config/benchmark/compcert_benchmark.yaml +36 -0
  37. itp_interface/main/config/benchmark/compcert_benchmark_hard.yaml +498 -0
  38. itp_interface/main/config/benchmark/compcert_benchmark_hard_1.yaml +55 -0
  39. itp_interface/main/config/benchmark/compcert_benchmark_hard_2.yaml +24 -0
  40. itp_interface/main/config/benchmark/compcert_benchmark_hard_3.yaml +95 -0
  41. itp_interface/main/config/benchmark/compcert_benchmark_hard_7_per_cent.yaml +78 -0
  42. itp_interface/main/config/benchmark/compcert_benchmark_test.yaml +38 -0
  43. itp_interface/main/config/benchmark/compcert_benchmark_train.yaml +340 -0
  44. itp_interface/main/config/benchmark/leandojo_novel_premises_test.yaml +2908 -0
  45. itp_interface/main/config/benchmark/leandojo_novel_premises_train.yaml +98645 -0
  46. itp_interface/main/config/benchmark/leandojo_novel_premises_val.yaml +2912 -0
  47. itp_interface/main/config/benchmark/leandojo_random.yaml +2889 -0
  48. itp_interface/main/config/benchmark/leandojo_random_test.yaml +2421 -0
  49. itp_interface/main/config/benchmark/leandojo_random_train.yaml +62729 -0
  50. itp_interface/main/config/benchmark/leandojo_random_val.yaml +2504 -0
  51. itp_interface/main/config/benchmark/math-comp.yaml +200 -0
  52. itp_interface/main/config/benchmark/miniF2F_test.yaml +12 -0
  53. itp_interface/main/config/benchmark/miniF2F_test_aime.yaml +27 -0
  54. itp_interface/main/config/benchmark/miniF2F_test_algebra.yaml +30 -0
  55. itp_interface/main/config/benchmark/miniF2F_test_amc12.yaml +57 -0
  56. itp_interface/main/config/benchmark/miniF2F_test_few_shot_hard.yaml +231 -0
  57. itp_interface/main/config/benchmark/miniF2F_test_imo.yaml +32 -0
  58. itp_interface/main/config/benchmark/miniF2F_test_induction.yaml +20 -0
  59. itp_interface/main/config/benchmark/miniF2F_test_mathd_algebra.yaml +82 -0
  60. itp_interface/main/config/benchmark/miniF2F_test_mathd_algebra_hard.yaml +72 -0
  61. itp_interface/main/config/benchmark/miniF2F_test_mathd_numbertheory.yaml +72 -0
  62. itp_interface/main/config/benchmark/miniF2F_test_numbertheory.yaml +20 -0
  63. itp_interface/main/config/benchmark/minicompcert_benchmark_1.yaml +14 -0
  64. itp_interface/main/config/benchmark/proverbot_hard.yaml +104 -0
  65. itp_interface/main/config/benchmark/re_prover.yaml +66 -0
  66. itp_interface/main/config/benchmark/re_prover_hard.yaml +41 -0
  67. itp_interface/main/config/benchmark/re_prover_very_hard.yaml +22 -0
  68. itp_interface/main/config/benchmark/reprover_with_retrieval.yaml +73 -0
  69. itp_interface/main/config/benchmark/reprover_with_retrieval_hard.yaml +30 -0
  70. itp_interface/main/config/benchmark/reprover_with_retrieval_neg.yaml +195 -0
  71. itp_interface/main/config/benchmark/simple_benchmark_1.yaml +24 -0
  72. itp_interface/main/config/benchmark/simple_benchmark_8.yaml +50 -0
  73. itp_interface/main/config/benchmark/simple_benchmark_9.yaml +65 -0
  74. itp_interface/main/config/benchmark/simple_benchmark_isabelle.yaml +18 -0
  75. itp_interface/main/config/benchmark/simple_benchmark_lean.yaml +12 -0
  76. itp_interface/main/config/benchmark/simple_benchmark_lean_training_data.yaml +12 -0
  77. itp_interface/main/config/benchmark/simple_rl_benchmark_lean.yaml +14 -0
  78. itp_interface/main/config/benchmark/stack_machine.yaml +13 -0
  79. itp_interface/main/config/benchmark/stack_machine_hard.yaml +15 -0
  80. itp_interface/main/config/category_theory_data_gen.yaml +14 -0
  81. itp_interface/main/config/category_theory_data_gen_random.yaml +16 -0
  82. itp_interface/main/config/compcert_data_gen_test.yaml +10 -0
  83. itp_interface/main/config/compcert_data_gen_train.yaml +7 -0
  84. itp_interface/main/config/env_settings/bm25_retrieval.yaml +2 -0
  85. itp_interface/main/config/env_settings/bm25_retrieval_no_dfns.yaml +2 -0
  86. itp_interface/main/config/env_settings/bm25_retrieval_only_local_no_dfns.yaml +2 -0
  87. itp_interface/main/config/env_settings/bm25_retrieval_with_print.yaml +2 -0
  88. itp_interface/main/config/env_settings/bm25_retrieval_with_print_only_local.yaml +2 -0
  89. itp_interface/main/config/env_settings/bm25_retrieval_with_print_only_local_no_dfns.yaml +2 -0
  90. itp_interface/main/config/env_settings/no_retrieval.yaml +2 -0
  91. itp_interface/main/config/experiments.yaml +12 -0
  92. itp_interface/main/config/geo_coq_data_gen.yaml +14 -0
  93. itp_interface/main/config/geo_coq_data_gen_random.yaml +16 -0
  94. itp_interface/main/config/leandojo_random_data_gen.yaml +16 -0
  95. itp_interface/main/config/math_comp_data_gen.yaml +14 -0
  96. itp_interface/main/config/math_comp_data_gen_random.yaml +16 -0
  97. itp_interface/main/config/mathlib_data_gen.yaml +14 -0
  98. itp_interface/main/config/repo/coq_repos.yaml +191 -0
  99. itp_interface/main/config/run_settings/default_coq_data_generation_transforms.yaml +24 -0
  100. itp_interface/main/config/run_settings/default_isabelle_data_generation_transforms.yaml +24 -0
  101. itp_interface/main/config/run_settings/default_lean4_data_generation_transforms.yaml +24 -0
  102. itp_interface/main/config/run_settings/default_lean_data_generation_transforms.yaml +24 -0
  103. itp_interface/main/config/simple_coq_data_gen.yaml +12 -0
  104. itp_interface/main/config/simple_coq_data_gen_random.yaml +17 -0
  105. itp_interface/main/config/simple_lean_data_gen.yaml +12 -0
  106. itp_interface/main/config/simple_rl_lean_data_gen.yaml +12 -0
  107. itp_interface/main/config/uni_math_data_gen.yaml +14 -0
  108. itp_interface/main/config.py +192 -0
  109. itp_interface/main/extract_benchmark_dataset.py +106 -0
  110. itp_interface/main/filter_dataset.py +107 -0
  111. itp_interface/main/install.py +92 -0
  112. itp_interface/main/merge_dataset.py +96 -0
  113. itp_interface/main/run_tool.py +444 -0
  114. itp_interface/pisa/.git +1 -0
  115. itp_interface/pisa/.gitignore +125 -0
  116. itp_interface/pisa/.idea/.gitignore +8 -0
  117. itp_interface/pisa/.idea/ClojureProjectResolveSettings.xml +6 -0
  118. itp_interface/pisa/.idea/codeStyles/Project.xml +7 -0
  119. itp_interface/pisa/.idea/codeStyles/codeStyleConfig.xml +5 -0
  120. itp_interface/pisa/.idea/inspectionProfiles/Project_Default.xml +16 -0
  121. itp_interface/pisa/.idea/libraries/sbt__com_google_android_annotations_4_1_1_4_jar.xml +13 -0
  122. itp_interface/pisa/.idea/libraries/sbt__com_google_api_grpc_proto_google_common_protos_1_17_0_jar.xml +13 -0
  123. itp_interface/pisa/.idea/libraries/sbt__com_google_code_findbugs_jsr305_3_0_2_jar.xml +13 -0
  124. itp_interface/pisa/.idea/libraries/sbt__com_google_code_gson_gson_2_8_6_jar.xml +13 -0
  125. itp_interface/pisa/.idea/libraries/sbt__com_google_errorprone_error_prone_annotations_2_3_4_jar.xml +13 -0
  126. itp_interface/pisa/.idea/libraries/sbt__com_google_guava_failureaccess_1_0_1_jar.xml +13 -0
  127. itp_interface/pisa/.idea/libraries/sbt__com_google_guava_guava_30_0_jre_jar.xml +13 -0
  128. itp_interface/pisa/.idea/libraries/sbt__com_google_guava_listenablefuture_9999_0_empty_to_avoid_conflict_with_guava_jar.xml +9 -0
  129. itp_interface/pisa/.idea/libraries/sbt__com_google_j2objc_j2objc_annotations_1_3_jar.xml +13 -0
  130. itp_interface/pisa/.idea/libraries/sbt__com_google_protobuf_protobuf_java_3_12_0_jar.xml +13 -0
  131. itp_interface/pisa/.idea/libraries/sbt__com_google_protobuf_protobuf_java_util_3_12_0_jar.xml +13 -0
  132. itp_interface/pisa/.idea/libraries/sbt__com_lihaoyi_fastparse_2_13_2_3_0_jar.xml +13 -0
  133. itp_interface/pisa/.idea/libraries/sbt__com_lihaoyi_geny_2_13_0_6_0_jar.xml +13 -0
  134. itp_interface/pisa/.idea/libraries/sbt__com_lihaoyi_sourcecode_2_13_0_2_1_jar.xml +13 -0
  135. itp_interface/pisa/.idea/libraries/sbt__com_thesamet_scalapb_lenses_2_13_0_10_9_jar.xml +13 -0
  136. itp_interface/pisa/.idea/libraries/sbt__com_thesamet_scalapb_scalapb_runtime_2_13_0_10_9_jar.xml +13 -0
  137. itp_interface/pisa/.idea/libraries/sbt__com_thesamet_scalapb_scalapb_runtime_grpc_2_13_0_10_9_jar.xml +13 -0
  138. itp_interface/pisa/.idea/libraries/sbt__com_thesamet_scalapb_zio_grpc_zio_grpc_core_2_13_0_4_2_jar.xml +13 -0
  139. itp_interface/pisa/.idea/libraries/sbt__com_thoughtworks_paranamer_paranamer_2_8_jar.xml +13 -0
  140. itp_interface/pisa/.idea/libraries/sbt__commons_io_commons_io_2_8_0_jar.xml +13 -0
  141. itp_interface/pisa/.idea/libraries/sbt__de_unruh_java_patterns_0_1_0_jar.xml +13 -0
  142. itp_interface/pisa/.idea/libraries/sbt__de_unruh_scala_isabelle_2_13_master_SNAPSHOT_jar.xml +13 -0
  143. itp_interface/pisa/.idea/libraries/sbt__dev_zio_izumi_reflect_2_13_1_0_0_M9_jar.xml +13 -0
  144. itp_interface/pisa/.idea/libraries/sbt__dev_zio_izumi_reflect_thirdparty_boopickle_shaded_2_13_1_0_0_M9_jar.xml +13 -0
  145. itp_interface/pisa/.idea/libraries/sbt__dev_zio_zio_2_13_1_0_3_jar.xml +13 -0
  146. itp_interface/pisa/.idea/libraries/sbt__dev_zio_zio_stacktracer_2_13_1_0_3_jar.xml +13 -0
  147. itp_interface/pisa/.idea/libraries/sbt__dev_zio_zio_streams_2_13_1_0_3_jar.xml +13 -0
  148. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_api_1_34_0_jar.xml +13 -0
  149. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_context_1_34_0_jar.xml +13 -0
  150. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_core_1_34_0_jar.xml +13 -0
  151. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_netty_1_34_0_jar.xml +13 -0
  152. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_protobuf_1_34_0_jar.xml +13 -0
  153. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_protobuf_lite_1_34_0_jar.xml +13 -0
  154. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_services_1_34_0_jar.xml +13 -0
  155. itp_interface/pisa/.idea/libraries/sbt__io_grpc_grpc_stub_1_34_0_jar.xml +13 -0
  156. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_buffer_4_1_51_Final_jar.xml +13 -0
  157. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_codec_4_1_51_Final_jar.xml +13 -0
  158. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_codec_http2_4_1_51_Final_jar.xml +13 -0
  159. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_codec_http_4_1_51_Final_jar.xml +13 -0
  160. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_codec_socks_4_1_51_Final_jar.xml +13 -0
  161. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_common_4_1_51_Final_jar.xml +13 -0
  162. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_handler_4_1_51_Final_jar.xml +13 -0
  163. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_handler_proxy_4_1_51_Final_jar.xml +13 -0
  164. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_resolver_4_1_51_Final_jar.xml +13 -0
  165. itp_interface/pisa/.idea/libraries/sbt__io_netty_netty_transport_4_1_51_Final_jar.xml +13 -0
  166. itp_interface/pisa/.idea/libraries/sbt__io_perfmark_perfmark_api_0_19_0_jar.xml +13 -0
  167. itp_interface/pisa/.idea/libraries/sbt__net_java_dev_jna_jna_5_3_1_jar.xml +13 -0
  168. itp_interface/pisa/.idea/libraries/sbt__net_liftweb_lift_json_2_13_3_4_3_jar.xml +13 -0
  169. itp_interface/pisa/.idea/libraries/sbt__org_apache_commons_commons_lang3_3_11_jar.xml +13 -0
  170. itp_interface/pisa/.idea/libraries/sbt__org_apache_commons_commons_text_1_9_jar.xml +13 -0
  171. itp_interface/pisa/.idea/libraries/sbt__org_checkerframework_checker_qual_3_5_0_jar.xml +13 -0
  172. itp_interface/pisa/.idea/libraries/sbt__org_codehaus_mojo_animal_sniffer_annotations_1_18_jar.xml +13 -0
  173. itp_interface/pisa/.idea/libraries/sbt__org_jetbrains_annotations_20_1_0_jar.xml +13 -0
  174. itp_interface/pisa/.idea/libraries/sbt__org_jline_jline_3_16_0_jar.xml +13 -0
  175. itp_interface/pisa/.idea/libraries/sbt__org_log4s_log4s_2_13_1_9_0_jar.xml +13 -0
  176. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_modules_scala_collection_compat_2_13_2_1_6_jar.xml +13 -0
  177. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_modules_scala_xml_2_13_1_3_0_jar.xml +13 -0
  178. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_scala_compiler_2_13_4_jar.xml +13 -0
  179. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_scala_library_2_13_4_jar.xml +23 -0
  180. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_scala_reflect_2_13_4_jar.xml +13 -0
  181. itp_interface/pisa/.idea/libraries/sbt__org_scala_lang_scalap_2_13_4_jar.xml +13 -0
  182. itp_interface/pisa/.idea/libraries/sbt__org_scalaz_scalaz_core_2_13_7_3_2_jar.xml +13 -0
  183. itp_interface/pisa/.idea/libraries/sbt__org_slf4j_slf4j_api_1_7_30_jar.xml +13 -0
  184. itp_interface/pisa/.idea/libraries/sbt__org_slf4j_slf4j_simple_1_7_30_jar.xml +13 -0
  185. itp_interface/pisa/.idea/misc.xml +7 -0
  186. itp_interface/pisa/.idea/modules/PISA-build.iml +127 -0
  187. itp_interface/pisa/.idea/modules/PISA.iml +94 -0
  188. itp_interface/pisa/.idea/modules.xml +9 -0
  189. itp_interface/pisa/.idea/other.xml +6 -0
  190. itp_interface/pisa/.idea/sbt.xml +20 -0
  191. itp_interface/pisa/.idea/scala_compiler.xml +6 -0
  192. itp_interface/pisa/.idea/uiDesigner.xml +124 -0
  193. itp_interface/pisa/.idea/vcs.xml +6 -0
  194. itp_interface/pisa/.scalafmt.conf +2 -0
  195. itp_interface/pisa/LICENSE +29 -0
  196. itp_interface/pisa/README.md +262 -0
  197. itp_interface/pisa/build.sbt +49 -0
  198. itp_interface/pisa/build.sh +26 -0
  199. itp_interface/pisa/command_generation/close_gaps.py +44 -0
  200. itp_interface/pisa/command_generation/conjecture_normal_order.py +62 -0
  201. itp_interface/pisa/command_generation/conjecturer_command_generator.py +36 -0
  202. itp_interface/pisa/command_generation/create_dirs.py +11 -0
  203. itp_interface/pisa/command_generation/find_std.py +67 -0
  204. itp_interface/pisa/command_generation/generate_build_commands_afp.py +15 -0
  205. itp_interface/pisa/command_generation/generate_build_commands_std.py +15 -0
  206. itp_interface/pisa/command_generation/generate_commands_afp.py +103 -0
  207. itp_interface/pisa/command_generation/generate_commands_mini.py +73 -0
  208. itp_interface/pisa/command_generation/generate_commands_std.py +69 -0
  209. itp_interface/pisa/command_generation/generate_hammer_extraction_text.py +5 -0
  210. itp_interface/pisa/command_generation/hammer_command_generator.py +40 -0
  211. itp_interface/pisa/command_generation/hp_search_command_generator.py +63 -0
  212. itp_interface/pisa/command_generation/oracle_command_generator.py +56 -0
  213. itp_interface/pisa/command_generation/search_command_generator.py +69 -0
  214. itp_interface/pisa/command_generation/summarise_problem_names.py +45 -0
  215. itp_interface/pisa/command_generation/tpu_hp_search.py +75 -0
  216. itp_interface/pisa/docker/Dockerfile +34 -0
  217. itp_interface/pisa/docker/docker_tutorial.md +64 -0
  218. itp_interface/pisa/eval_setup/copy_isabelle.py +42 -0
  219. itp_interface/pisa/eval_setup/copy_pisa_jars.py +18 -0
  220. itp_interface/pisa/mesh_transformer_utils/tokenization.py +86 -0
  221. itp_interface/pisa/project/build.properties +1 -0
  222. itp_interface/pisa/project/plugins.sbt +5 -0
  223. itp_interface/pisa/requirements.txt +4 -0
  224. itp_interface/pisa/scripts/extract_last_k_steps.py +28 -0
  225. itp_interface/pisa/scripts/extract_proof_corpus.py +26 -0
  226. itp_interface/pisa/scripts/gather_hammer_results.py +27 -0
  227. itp_interface/pisa/scripts/length_in_char_stats.py +20 -0
  228. itp_interface/pisa/scripts/mix.py +127 -0
  229. itp_interface/pisa/scripts/results_stat.py +52 -0
  230. itp_interface/pisa/scripts/test_array_job.sh +34 -0
  231. itp_interface/pisa/setup.sh +25 -0
  232. itp_interface/pisa/src/main/protobuf/server.proto +60 -0
  233. itp_interface/pisa/src/main/python/.idea/.gitignore +8 -0
  234. itp_interface/pisa/src/main/python/.idea/inspectionProfiles/Project_Default.xml +18 -0
  235. itp_interface/pisa/src/main/python/.idea/inspectionProfiles/profiles_settings.xml +6 -0
  236. itp_interface/pisa/src/main/python/.idea/misc.xml +4 -0
  237. itp_interface/pisa/src/main/python/.idea/modules.xml +8 -0
  238. itp_interface/pisa/src/main/python/.idea/python.iml +12 -0
  239. itp_interface/pisa/src/main/python/.idea/vcs.xml +6 -0
  240. itp_interface/pisa/src/main/python/conjecturing_parsing/conjecturer_postprocessing.py +59 -0
  241. itp_interface/pisa/src/main/python/data_extraction/extract_data.py +184 -0
  242. itp_interface/pisa/src/main/python/data_extraction/find_premises.py +221 -0
  243. itp_interface/pisa/src/main/python/data_extraction/process_data.py +129 -0
  244. itp_interface/pisa/src/main/python/legacy/PisaFlexibleClient.py +167 -0
  245. itp_interface/pisa/src/main/python/legacy/autof_test.py +74 -0
  246. itp_interface/pisa/src/main/python/legacy/cmd_client.py +23 -0
  247. itp_interface/pisa/src/main/python/legacy/convert_scala_dump_to_test_name_jsons.py +14 -0
  248. itp_interface/pisa/src/main/python/legacy/create_data_txt.py +72 -0
  249. itp_interface/pisa/src/main/python/legacy/create_finetune_tfrecords.py +311 -0
  250. itp_interface/pisa/src/main/python/legacy/demo.py +49 -0
  251. itp_interface/pisa/src/main/python/legacy/evaluate.py +108 -0
  252. itp_interface/pisa/src/main/python/legacy/extract_first_step.py +25 -0
  253. itp_interface/pisa/src/main/python/legacy/get_global_facts.py +35 -0
  254. itp_interface/pisa/src/main/python/legacy/mix_data.py +19 -0
  255. itp_interface/pisa/src/main/python/legacy/one_stage_extraction.py +111 -0
  256. itp_interface/pisa/src/main/python/legacy/prepare_episodic_transitions.py +137 -0
  257. itp_interface/pisa/src/main/python/legacy/prepare_translation_pairs.py +277 -0
  258. itp_interface/pisa/src/main/python/pisa_client.py +322 -0
  259. itp_interface/pisa/src/main/python/server_pb2.py +394 -0
  260. itp_interface/pisa/src/main/python/server_pb2_grpc.py +230 -0
  261. itp_interface/pisa/src/main/python/test_client.py +17 -0
  262. itp_interface/pisa/src/main/python/test_client2.py +79 -0
  263. itp_interface/pisa/src/main/python/utils/filters.py +59 -0
  264. itp_interface/pisa/src/main/python/utils/pisa_server_control.py +29 -0
  265. itp_interface/pisa/src/main/scala/pisa/agent/CheckSyntax.scala +257 -0
  266. itp_interface/pisa/src/main/scala/pisa/agent/DepThms.scala +29 -0
  267. itp_interface/pisa/src/main/scala/pisa/agent/PisaStat.scala +46 -0
  268. itp_interface/pisa/src/main/scala/pisa/agent/RefactorTest.scala +40 -0
  269. itp_interface/pisa/src/main/scala/pisa/agent/RepHammer.scala +95 -0
  270. itp_interface/pisa/src/main/scala/pisa/server/HammFacts.scala +63 -0
  271. itp_interface/pisa/src/main/scala/pisa/server/PisaOS.scala +881 -0
  272. itp_interface/pisa/src/main/scala/pisa/server/PisaOneStage.scala +540 -0
  273. itp_interface/pisa/src/main/scala/pisa/server/PisaOneStageServers.scala +1048 -0
  274. itp_interface/pisa/src/main/scala/pisa/utils/TheoryManager.scala +95 -0
  275. itp_interface/pisa/src/test/python/analyse_debug.py +33 -0
  276. itp_interface/pisa/src/test/python/extract_test_seq2seq.py +53 -0
  277. itp_interface/pisa/src/test/python/extract_test_theorem_ground_truth_indices.py +31 -0
  278. itp_interface/pisa/src/test/python/proof_originality.py +24 -0
  279. itp_interface/pisa/src/test/python/test_command_generator.py +25 -0
  280. itp_interface/pisa/src/test/python/test_model_sequence_accuracy.py +70 -0
  281. itp_interface/pisa/src/test/scala/pisa/Easy.scala +26 -0
  282. itp_interface/pisa/src/test/scala/pisa/TestCurl.scala +82 -0
  283. itp_interface/pisa/src/test/scala/pisa/TestIsa.scala +27 -0
  284. itp_interface/pisa/test.sh +19 -0
  285. itp_interface/pisa/universal_test_theorems.tar.gz +0 -0
  286. itp_interface/repo/build.py +78 -0
  287. itp_interface/repo/clone.py +79 -0
  288. itp_interface/repo/dataset_discovery.py +99 -0
  289. itp_interface/retrieval/__init__.py +0 -0
  290. itp_interface/retrieval/abstraction.py +35 -0
  291. itp_interface/retrieval/coq_bm25_reranker.py +153 -0
  292. itp_interface/retrieval/isabelle_bm25_reranker.py +86 -0
  293. itp_interface/retrieval/lean3_bm25_reranker.py +86 -0
  294. itp_interface/rl/__init__.py +0 -0
  295. itp_interface/rl/abstraction.py +168 -0
  296. itp_interface/rl/proof_action.py +172 -0
  297. itp_interface/rl/proof_state.py +149 -0
  298. itp_interface/rl/proof_tree.py +109 -0
  299. itp_interface/rl/simpl_proof_env_pool.py +16 -0
  300. itp_interface/rl/simple_proof_env.py +713 -0
  301. itp_interface/rl/simple_proof_env_pool.py +591 -0
  302. itp_interface/scripts/setup.sh +228 -0
  303. itp_interface/tools/__init__.py +0 -0
  304. itp_interface/tools/basic_utils.py +172 -0
  305. itp_interface/tools/bin_packing.py +61 -0
  306. itp_interface/tools/cache.py +93 -0
  307. itp_interface/tools/coq_build_spec.py +31 -0
  308. itp_interface/tools/coq_build_tool.py +319 -0
  309. itp_interface/tools/coq_context_helper.py +354 -0
  310. itp_interface/tools/coq_executor.py +508 -0
  311. itp_interface/tools/coq_local_data_generation_transform.py +158 -0
  312. itp_interface/tools/coq_parse_utils.py +154 -0
  313. itp_interface/tools/coq_raw_proofs.py +193 -0
  314. itp_interface/tools/coq_theorem_proof_pair_generation_transform.py +146 -0
  315. itp_interface/tools/coq_training_data_generator.py +76 -0
  316. itp_interface/tools/dynamic_coq_proof_exec.py +220 -0
  317. itp_interface/tools/dynamic_isabelle_proof_exec.py +229 -0
  318. itp_interface/tools/dynamic_lean4_proof_exec.py +236 -0
  319. itp_interface/tools/dynamic_lean_proof_exec.py +228 -0
  320. itp_interface/tools/isabelle_context_helper.py +66 -0
  321. itp_interface/tools/isabelle_executor.py +862 -0
  322. itp_interface/tools/isabelle_local_data_generation_transform.py +149 -0
  323. itp_interface/tools/isabelle_parse_utils.py +131 -0
  324. itp_interface/tools/isabelle_server.py +106 -0
  325. itp_interface/tools/lean4_context_helper.py +72 -0
  326. itp_interface/tools/lean4_local_data_generation_transform.py +122 -0
  327. itp_interface/tools/lean4_sync_executor.py +1193 -0
  328. itp_interface/tools/lean_cmd_executor.py +804 -0
  329. itp_interface/tools/lean_context_helper.py +327 -0
  330. itp_interface/tools/lean_dojo_data_generation_transform.py +206 -0
  331. itp_interface/tools/lean_executor.py +687 -0
  332. itp_interface/tools/lean_local_data_generation_transform.py +136 -0
  333. itp_interface/tools/lean_parse_utils.py +32 -0
  334. itp_interface/tools/log_utils.py +20 -0
  335. itp_interface/tools/proof_exec_callback.py +76 -0
  336. itp_interface/tools/ray_utils.py +265 -0
  337. itp_interface/tools/repl/.git +1 -0
  338. itp_interface/tools/repl/.github/workflows/ci.yml +24 -0
  339. itp_interface/tools/repl/.gitignore +7 -0
  340. itp_interface/tools/repl/.vscode/copyright.code-snippets +13 -0
  341. itp_interface/tools/repl/.vscode/extensions.json +13 -0
  342. itp_interface/tools/repl/.vscode/module-docstring.code-snippets +35 -0
  343. itp_interface/tools/repl/.vscode/settings.json +11 -0
  344. itp_interface/tools/repl/README.md +174 -0
  345. itp_interface/tools/repl/REPL/Frontend.lean +47 -0
  346. itp_interface/tools/repl/REPL/JSON.lean +186 -0
  347. itp_interface/tools/repl/REPL/Lean/ContextInfo.lean +9 -0
  348. itp_interface/tools/repl/REPL/Lean/Environment.lean +31 -0
  349. itp_interface/tools/repl/REPL/Lean/InfoTree/ToJson.lean +114 -0
  350. itp_interface/tools/repl/REPL/Lean/InfoTree.lean +272 -0
  351. itp_interface/tools/repl/REPL/Main.lean +323 -0
  352. itp_interface/tools/repl/REPL/Snapshots.lean +306 -0
  353. itp_interface/tools/repl/REPL/Util/Path.lean +36 -0
  354. itp_interface/tools/repl/REPL/Util/Pickle.lean +44 -0
  355. itp_interface/tools/repl/REPL.lean +4 -0
  356. itp_interface/tools/repl/lake-manifest.json +5 -0
  357. itp_interface/tools/repl/lakefile.lean +15 -0
  358. itp_interface/tools/repl/lean-toolchain +1 -0
  359. itp_interface/tools/repl/test/Mathlib/.gitignore +5 -0
  360. itp_interface/tools/repl/test/Mathlib/H20231110.sh +2 -0
  361. itp_interface/tools/repl/test/Mathlib/ReplMathlibTests.lean +1 -0
  362. itp_interface/tools/repl/test/Mathlib/lake-manifest.json +68 -0
  363. itp_interface/tools/repl/test/Mathlib/lakefile.lean +11 -0
  364. itp_interface/tools/repl/test/Mathlib/lean-toolchain +1 -0
  365. itp_interface/tools/repl/test/Mathlib/test/20240209.expected.out +20 -0
  366. itp_interface/tools/repl/test/Mathlib/test/20240209.in +3 -0
  367. itp_interface/tools/repl/test/Mathlib/test/20240209.lean +4 -0
  368. itp_interface/tools/repl/test/Mathlib/test/H20231020.expected.out +8 -0
  369. itp_interface/tools/repl/test/Mathlib/test/H20231020.in +8 -0
  370. itp_interface/tools/repl/test/Mathlib/test/H20231020.lean +22 -0
  371. itp_interface/tools/repl/test/Mathlib/test/H20231110.expected.out +4 -0
  372. itp_interface/tools/repl/test/Mathlib/test/H20231110.in +4 -0
  373. itp_interface/tools/repl/test/Mathlib/test/H20231115.expected.out +19 -0
  374. itp_interface/tools/repl/test/Mathlib/test/H20231115.in +5 -0
  375. itp_interface/tools/repl/test/Mathlib/test/H20231115_2.expected.out +18 -0
  376. itp_interface/tools/repl/test/Mathlib/test/H20231115_2.in +4 -0
  377. itp_interface/tools/repl/test/Mathlib/test/H20231115_3.expected.out +10 -0
  378. itp_interface/tools/repl/test/Mathlib/test/H20231115_3.in +4 -0
  379. itp_interface/tools/repl/test/Mathlib/test/H20231214.in +9 -0
  380. itp_interface/tools/repl/test/Mathlib/test/H20231214.lean +30 -0
  381. itp_interface/tools/repl/test/Mathlib/test/H20231215.expected.out +4 -0
  382. itp_interface/tools/repl/test/Mathlib/test/H20231215.in +4 -0
  383. itp_interface/tools/repl/test/Mathlib/test/H20231215_2.expected.out +14 -0
  384. itp_interface/tools/repl/test/Mathlib/test/H20231215_2.in +3 -0
  385. itp_interface/tools/repl/test/Mathlib/test/exact.expected.out +37 -0
  386. itp_interface/tools/repl/test/Mathlib/test/exact.in +10 -0
  387. itp_interface/tools/repl/test/Mathlib/test/import_Mathlib.lean +1 -0
  388. itp_interface/tools/repl/test/Mathlib/test/induction.expected.out +29 -0
  389. itp_interface/tools/repl/test/Mathlib/test/induction.in +10 -0
  390. itp_interface/tools/repl/test/Mathlib/test/induction.lean +6 -0
  391. itp_interface/tools/repl/test/Mathlib/test/on_goal.expected.out +22 -0
  392. itp_interface/tools/repl/test/Mathlib/test/on_goal.in +5 -0
  393. itp_interface/tools/repl/test/Mathlib/test/pickle.expected.out +16 -0
  394. itp_interface/tools/repl/test/Mathlib/test/pickle.in +6 -0
  395. itp_interface/tools/repl/test/Mathlib/test/pickle_2.expected.out +4 -0
  396. itp_interface/tools/repl/test/Mathlib/test/pickle_2.in +4 -0
  397. itp_interface/tools/repl/test/Mathlib/test.sh +41 -0
  398. itp_interface/tools/repl/test/all_tactics.expected.out +13 -0
  399. itp_interface/tools/repl/test/all_tactics.in +1 -0
  400. itp_interface/tools/repl/test/by_cases.expected.out +25 -0
  401. itp_interface/tools/repl/test/by_cases.in +8 -0
  402. itp_interface/tools/repl/test/by_cases.lean +4 -0
  403. itp_interface/tools/repl/test/calc.expected.out +32 -0
  404. itp_interface/tools/repl/test/calc.in +1 -0
  405. itp_interface/tools/repl/test/def_eval.expected.out +9 -0
  406. itp_interface/tools/repl/test/def_eval.in +3 -0
  407. itp_interface/tools/repl/test/enableInitializersExecution.expected.out +2 -0
  408. itp_interface/tools/repl/test/enableInitializersExecution.in +1 -0
  409. itp_interface/tools/repl/test/file.expected.out +8 -0
  410. itp_interface/tools/repl/test/file.in +1 -0
  411. itp_interface/tools/repl/test/file.lean +5 -0
  412. itp_interface/tools/repl/test/have_by_sorry.expected.out +28 -0
  413. itp_interface/tools/repl/test/have_by_sorry.in +6 -0
  414. itp_interface/tools/repl/test/import_lean.in +1 -0
  415. itp_interface/tools/repl/test/incomplete.expected.out +18 -0
  416. itp_interface/tools/repl/test/incomplete.in +3 -0
  417. itp_interface/tools/repl/test/incomplete.lean +0 -0
  418. itp_interface/tools/repl/test/infotree.expected.out +20 -0
  419. itp_interface/tools/repl/test/infotree.in +2 -0
  420. itp_interface/tools/repl/test/invalid_tactic.expected.out +20 -0
  421. itp_interface/tools/repl/test/invalid_tactic.in +3 -0
  422. itp_interface/tools/repl/test/name_generator.expected.out +53 -0
  423. itp_interface/tools/repl/test/name_generator.in +18 -0
  424. itp_interface/tools/repl/test/no_goal_sorry.expected.out +11 -0
  425. itp_interface/tools/repl/test/no_goal_sorry.in +1 -0
  426. itp_interface/tools/repl/test/no_goal_sorry_2.expected.out +12 -0
  427. itp_interface/tools/repl/test/no_goal_sorry_2.in +1 -0
  428. itp_interface/tools/repl/test/options.expected.out +17 -0
  429. itp_interface/tools/repl/test/options.in +6 -0
  430. itp_interface/tools/repl/test/pickle_environment.expected.out +8 -0
  431. itp_interface/tools/repl/test/pickle_environment.in +7 -0
  432. itp_interface/tools/repl/test/pickle_environment_with_imports.expected.out +10 -0
  433. itp_interface/tools/repl/test/pickle_environment_with_imports.in +9 -0
  434. itp_interface/tools/repl/test/pickle_open.expected.out +8 -0
  435. itp_interface/tools/repl/test/pickle_open.in +7 -0
  436. itp_interface/tools/repl/test/pickle_open_2.expected.out +4 -0
  437. itp_interface/tools/repl/test/pickle_open_2.in +3 -0
  438. itp_interface/tools/repl/test/pickle_open_scoped.expected.out +18 -0
  439. itp_interface/tools/repl/test/pickle_open_scoped.in +8 -0
  440. itp_interface/tools/repl/test/pickle_open_scoped_2.expected.out +14 -0
  441. itp_interface/tools/repl/test/pickle_open_scoped_2.in +3 -0
  442. itp_interface/tools/repl/test/pickle_proof_state_1.expected.out +26 -0
  443. itp_interface/tools/repl/test/pickle_proof_state_1.in +15 -0
  444. itp_interface/tools/repl/test/pickle_proof_state_2.expected.out +4 -0
  445. itp_interface/tools/repl/test/pickle_proof_state_2.in +3 -0
  446. itp_interface/tools/repl/test/pickle_proof_state_env.expected.out +26 -0
  447. itp_interface/tools/repl/test/pickle_proof_state_env.in +15 -0
  448. itp_interface/tools/repl/test/pickle_scoped_notation.in +16 -0
  449. itp_interface/tools/repl/test/pickle_scoped_notation_2.in +3 -0
  450. itp_interface/tools/repl/test/proof_step.expected.out +18 -0
  451. itp_interface/tools/repl/test/proof_step.in +7 -0
  452. itp_interface/tools/repl/test/readme.expected.out +16 -0
  453. itp_interface/tools/repl/test/readme.in +5 -0
  454. itp_interface/tools/repl/test/sorry_hypotheses.expected.out +16 -0
  455. itp_interface/tools/repl/test/sorry_hypotheses.in +4 -0
  456. itp_interface/tools/repl/test/synthesize_placeholder.expected.out +7 -0
  457. itp_interface/tools/repl/test/synthesize_placeholder.in +1 -0
  458. itp_interface/tools/repl/test/tactic_mode_sorry.expected.out +14 -0
  459. itp_interface/tools/repl/test/tactic_mode_sorry.in +3 -0
  460. itp_interface/tools/repl/test/tactic_sorry.expected.out +12 -0
  461. itp_interface/tools/repl/test/tactic_sorry.in +1 -0
  462. itp_interface/tools/repl/test/term_sorry.expected.out +12 -0
  463. itp_interface/tools/repl/test/term_sorry.in +1 -0
  464. itp_interface/tools/repl/test/trace_simp.expected.out +41 -0
  465. itp_interface/tools/repl/test/trace_simp.in +15 -0
  466. itp_interface/tools/repl/test/unfinished_tactic_block.expected.out +11 -0
  467. itp_interface/tools/repl/test/unfinished_tactic_block.in +1 -0
  468. itp_interface/tools/repl/test/unknown_environment.expected.out +2 -0
  469. itp_interface/tools/repl/test/unknown_environment.in +1 -0
  470. itp_interface/tools/repl/test/unknown_proof_state.expected.out +14 -0
  471. itp_interface/tools/repl/test/unknown_proof_state.in +3 -0
  472. itp_interface/tools/repl/test/unknown_tactic.expected.out +14 -0
  473. itp_interface/tools/repl/test/unknown_tactic.in +3 -0
  474. itp_interface/tools/repl/test/variables.expected.out +26 -0
  475. itp_interface/tools/repl/test/variables.in +5 -0
  476. itp_interface/tools/repl/test.sh +43 -0
  477. itp_interface/tools/run_data_generation_transforms.py +350 -0
  478. itp_interface/tools/theorem_details.py +25 -0
  479. itp_interface/tools/training_data.py +358 -0
  480. itp_interface/tools/training_data_format.py +599 -0
  481. itp_interface-1.0.0.dist-info/METADATA +78 -0
  482. itp_interface-1.0.0.dist-info/RECORD +485 -0
  483. itp_interface-1.0.0.dist-info/WHEEL +4 -0
  484. itp_interface-1.0.0.dist-info/entry_points.txt +3 -0
  485. itp_interface-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,841 @@
1
+
2
+ import threading
3
+ import re
4
+ import subprocess
5
+ import queue
6
+ import signal
7
+ import functools
8
+ import os
9
+ import os.path
10
+ from typing import Optional, List, Any, TYPE_CHECKING, cast
11
+
12
+ from sexpdata import Symbol, loads, dumps, ExpectClosingBracket
13
+ from pampy import match, _, TAIL
14
+
15
+ from .coq_backend import (CoqBackend, CoqAnomaly, CompletedError,
16
+ AckError, CoqExn, BadResponse,
17
+ CoqTimeoutError, ParseError,
18
+ UnrecognizedError, CoqException,
19
+ NoSuchGoalError)
20
+ from .contexts import ProofContext, Obligation, SexpObligation
21
+ from .coq_util import raise_, parsePPSubgoal, setup_opam_env, get_module_from_filename
22
+ from .util import (eprint, parseSexpOneLevel, unwrap, progn)
23
+ if TYPE_CHECKING:
24
+ from sexpdata import Sexp
25
+
26
+ class CoqSeraPyInstance(CoqBackend, threading.Thread):
27
+
28
+ def __init__(self, coq_command: List[str],
29
+ timeout: int = 30, set_env: bool = True) -> None:
30
+
31
+ if set_env:
32
+ setup_opam_env()
33
+ self.__sema = threading.Semaphore(value=0)
34
+ threading.Thread.__init__(self, daemon=True)
35
+ self.version_string = subprocess.run(["sertop", "--version"], stdout=subprocess.PIPE,
36
+ text=True, check=True).stdout
37
+ if self.version_string.strip() == "":
38
+ self.version_string = "8.10.0"
39
+ print(f"Using dev version of sertop, setting version string to {self.version_string}")
40
+ assert self.coq_minor_version() >= 10, \
41
+ "Versions of Coq before 8.10 are not supported! "\
42
+ f"Currently installed coq is {self.version_string}"
43
+ if self.coq_minor_version() <= 12:
44
+ self.all_goals_regex = all_goals_regex_10
45
+ else:
46
+ self.all_goals_regex = all_goals_regex_13
47
+
48
+ # Open a process to coq, with streams for communicating with
49
+ # it.
50
+ self.root_dir = "."
51
+ self._proc = subprocess.Popen(coq_command,
52
+ # " ".join(coq_command) if isinstance(coq_command, list) else coq_command,
53
+ # shell=True,
54
+ cwd=".",
55
+ stdin=subprocess.PIPE,
56
+ stdout=subprocess.PIPE,
57
+ stderr=subprocess.PIPE)
58
+ self._fout = self._proc.stdout
59
+ self._fin = self._proc.stdin
60
+
61
+ # Initialize some state that we'll use to keep track of the
62
+ # coq state. This way we don't have to do expensive queries to
63
+ # the other process to answer simple questions.
64
+ self.proof_context: Optional[ProofContext] = None
65
+ self.cur_state = 0
66
+ self.timeout = timeout
67
+
68
+ # Set up the message queue, which we'll populate with the
69
+ # messages from serapi.
70
+ self.message_queue = queue.Queue() # type: queue.Queue[str]
71
+ # Verbosity is zero until set otherwise
72
+ self.verbosity = 0
73
+ # Set the "extra quiet" flag (don't print on failures) to false
74
+ self.quiet = False
75
+ # The messages printed to the *response* buffer by the command
76
+ self.feedbacks: List[Any] = []
77
+ # Start the message queue thread
78
+ self.start()
79
+ # Go through the messages and throw away the initial feedback.
80
+ self._discard_feedback()
81
+
82
+ def addStmt_noupdate(self, stmt: str, timeout:Optional[int] = None) -> None:
83
+ assert self.proof_context
84
+ if stmt.strip() == "":
85
+ return
86
+ if timeout:
87
+ old_timeout = self.timeout
88
+ self.timeout = timeout
89
+ self._flush_queue()
90
+ assert self.message_queue.empty(), self.messages
91
+ stmt = stmt.replace("\\", "\\\\")
92
+ stmt = stmt.replace("\"", "\\\"")
93
+ self._send_acked(f"(Add () \"{stmt}\")\n")
94
+ # Get the response, which indicates what state we put
95
+ # serapi in.
96
+ self._update_state()
97
+ self._get_completed()
98
+ if timeout:
99
+ self.timeout = old_timeout
100
+ assert self.message_queue.empty()
101
+ def updateState(self) -> None:
102
+ # Execute the statement.
103
+ self._send_acked("(Exec {})\n".format(self.cur_state))
104
+ # Finally, get the result of the command
105
+ self.feedbacks = self._get_feedbacks()
106
+ # Get a new proof context, if it exists
107
+ self._get_proof_context(update_nonfg_goals=True)
108
+
109
+ def addStmt(self, stmt: str, timeout:Optional[int] = None,
110
+ force_update_nonfg_goals: bool = False) -> None:
111
+ if stmt.strip() == "":
112
+ return
113
+ if timeout:
114
+ old_timeout = self.timeout
115
+ self.timeout = timeout
116
+ try:
117
+ self._flush_queue()
118
+ assert self.message_queue.empty(), self.messages
119
+ stmt = stmt.replace("\\", "\\\\")
120
+ stmt = stmt.replace("\"", "\\\"")
121
+ self._send_acked(f"(Add () \"{stmt}\")\n")
122
+ # Get the response, which indicates what state we put
123
+ # serapi in.
124
+ self._update_state()
125
+ self._get_completed()
126
+ assert self.message_queue.empty()
127
+ # Track goal opening/closing
128
+ is_goal_open = re.match(r"\s*(?:\d+\s*:)?\s*[{]\s*", stmt)
129
+ is_goal_close = re.match(r"\s*[}]\s*", stmt)
130
+ is_unshelve = re.match(r"\s*Unshelve\s*\.\s*", stmt)
131
+ is_bullet = re.match(r"\s*[-+*]+", stmt)
132
+
133
+ # Execute the statement.
134
+ self._send_acked(f"(Exec {self.cur_state})\n")
135
+ # Finally, get the result of the command
136
+ self.feedbacks = self._get_feedbacks()
137
+ # Get a new proof context, if it exists
138
+ if is_goal_open:
139
+ self._get_enter_goal_context()
140
+ elif is_goal_close or is_unshelve or is_bullet:
141
+ self._get_proof_context(update_nonfg_goals=True)
142
+ else:
143
+ self._get_proof_context(update_nonfg_goals=force_update_nonfg_goals)
144
+ except (CoqExn, BadResponse, AckError,
145
+ CompletedError, CoqTimeoutError) as e:
146
+ self._handle_exception(e, stmt)
147
+ finally:
148
+ if timeout:
149
+ self.timeout = old_timeout
150
+ def cancelLastStmt_noupdate(self, cancelled: str) -> None:
151
+ self._flush_queue()
152
+ assert self.message_queue.empty(), self.messages
153
+ # Run the cancel
154
+ self._send_acked("(Cancel ({}))".format(self.cur_state))
155
+ # Get the response from cancelling
156
+ self.cur_state = self._get_cancelled()
157
+
158
+ def cancelLastStmt(self, cancelled: str, force_update_nonfg_goals: bool = False) -> None:
159
+ is_goal_open = re.match(r"\s*(?:\d+\s*:)?\s*[{]\s*", cancelled)
160
+ is_goal_close = re.match(r"\s*[}]\s*", cancelled)
161
+ is_unshelve = re.match(r"\s*Unshelve\s*\.\s*", cancelled)
162
+ is_bullet = re.match(r"\s*[-+*]+", cancelled)
163
+ self.__cancel()
164
+ # Get a new proof context, if it exists
165
+ self._get_proof_context(update_nonfg_goals=
166
+ bool(is_goal_open or is_goal_close or
167
+ is_unshelve or is_bullet or
168
+ force_update_nonfg_goals))
169
+
170
+ def getProofContext(self) -> Optional[ProofContext]:
171
+ return self.proof_context
172
+
173
+ def close(self) -> None:
174
+ assert self._proc.stdout
175
+ self._proc.terminate()
176
+ self._proc.kill()
177
+ self.__sema.release()
178
+ def isInProof(self) -> bool:
179
+ return self.proof_context is not None
180
+ def queryVernac(self, vernac: str) -> List[str]:
181
+ self._send_acked(f"(Query () (Vernac \"{vernac}\"))")
182
+ next_msg = self._get_message()
183
+ while isProgressMessage(next_msg):
184
+ next_msg = self._get_message()
185
+ feedbacks = []
186
+ while self._isFeedbackMessage(next_msg):
187
+ feedbacks.append(next_msg)
188
+ next_msg = self._get_message()
189
+ # Only for older coq versions?
190
+ # This case is here because older versions of Coq/Serapi send an
191
+ # extra message after the feedbacks when the response is bad.
192
+ if self.coq_minor_version() <= 12:
193
+ def handle_bad_response(_: Any):
194
+ # All (Answer {int} (ObjList ...)) messages are followed by
195
+ # an (Answer {int} Completed) message.
196
+ # in order to keep future commands from failing, we need to
197
+ # consume the Completed message.
198
+ self._get_completed()
199
+ raise BadResponse(next_msg)
200
+
201
+ match(normalizeMessage(next_msg),
202
+ ["Answer", int, ["ObjList", []]], lambda state: None,
203
+ _, handle_bad_response)
204
+
205
+ self._get_completed()
206
+ return ["\n".join(searchStrsInMsg(msg)) for msg in feedbacks]
207
+ def interrupt(self) -> None:
208
+ self._proc.send_signal(signal.SIGINT)
209
+ self._flush_queue()
210
+ def enterDirectory(self, new_dir: str) -> None:
211
+ self.root_dir = os.path.join(self.root_dir, new_dir)
212
+ try:
213
+ with open(self.root_dir + "/_CoqProject", 'r') as includesfile:
214
+ includes_string = includesfile.read()
215
+ except FileNotFoundError:
216
+ try:
217
+ with open(self.root_dir + "/Make", 'r') as includesfile:
218
+ includes_string = includesfile.read()
219
+ except FileNotFoundError:
220
+ eprint(f"Didn't find _CoqProject or Make for {self.root_dir}",
221
+ guard=self.verbosity)
222
+ includes_string = ""
223
+
224
+ self.addStmt(f"Cd \"{new_dir}\".")
225
+
226
+ q_pattern = r"-Q\s*(\S+)\s+(\S+)\s*"
227
+ r_pattern = r"-R\s*(\S+)\s+(\S+)\s*"
228
+ i_pattern = r"-I\s*(\S+)\s*"
229
+ for includematch in re.finditer(rf"({q_pattern})|({r_pattern})|({i_pattern})",
230
+ includes_string):
231
+ q_match = re.fullmatch(r"-Q\s*(\S*)\s*(\S*)\s*", includematch.group(0))
232
+ if q_match:
233
+ if q_match.group(2) == "\"\"":
234
+ self.addStmt(
235
+ f"Add LoadPath \"{q_match.group(1)}\".")
236
+ else:
237
+ self.addStmt(
238
+ f"Add LoadPath \"{q_match.group(1)}\" as {q_match.group(2)}.")
239
+ continue
240
+ r_match = re.match(r"-R\s*(\S*)\s*(\S*)\s*", includematch.group(0))
241
+ if r_match:
242
+ self.addStmt(
243
+ f"Add Rec LoadPath \"{r_match.group(1)}\" as {r_match.group(2)}.")
244
+ continue
245
+ i_match = re.match(r"-I\s*(\S*)", includematch.group(0))
246
+ if i_match:
247
+ self.addStmt(
248
+ f"Add ML Path \"{i_match.group(1)}\".")
249
+ continue
250
+ def setFilename(self, filename: str) -> None:
251
+ module_name = get_module_from_filename(filename)
252
+ self.addStmt(f"Module {module_name}.")
253
+ def resetCommandState(self) -> None:
254
+ self.addStmt("Reset Initial.")
255
+ self.addStmt("Optimize Heap.", timeout=15)
256
+ self.enterDirectory(".")
257
+
258
+ def coq_minor_version(self) -> int:
259
+ version_match = re.fullmatch(r"\d+\.(\d+).*", self.version_string,
260
+ flags=re.DOTALL)
261
+ assert version_match, f"Version {self.version_string} doesn't match regex"
262
+ return int(version_match.group(1))
263
+ @property
264
+ def messages(self):
265
+ return [dumps(msg) for msg in list(self.message_queue.queue)]
266
+ @property
267
+ def feedback_string(self):
268
+ if len(self.feedbacks) < 4:
269
+ return ""
270
+ string_lists = [searchStrsInMsg(f) for f in self.feedbacks]
271
+ nonempty_string_lists = [l for l in string_lists if len(l) > 0]
272
+ return "\n".join([slist[0] for slist in nonempty_string_lists])
273
+ def getSexpProofContext(self) -> List[SexpObligation]:
274
+ assert self.proof_context, "Can only call get_all_sexp_goals when you're in a proof!"
275
+ text_response = self._ask_text("(Query () Goals)")
276
+ context_match = re.fullmatch(
277
+ r"\(Answer\s+\d+\s*\(ObjList\s*(.*)\)\)\n",
278
+ text_response)
279
+ if not context_match:
280
+ if "Stack overflow" in text_response:
281
+ raise CoqAnomaly(f"\"{text_response}\"")
282
+ else:
283
+ raise BadResponse(f"\"{text_response}\"")
284
+ context_str = context_match.group(1)
285
+ assert context_str != "()"
286
+ goals_match = self.all_goals_regex.match(context_str)
287
+ if not goals_match:
288
+ raise BadResponse(context_str)
289
+ fg_goals_str, bg_goals_str, \
290
+ shelved_goals_str, given_up_goals_str = \
291
+ goals_match.groups()
292
+ fg_goal_strs = cast(List[str], parseSexpOneLevel(fg_goals_str))
293
+ bg_goal_strs = [uuulevel for ulevel in cast(List[str],
294
+ parseSexpOneLevel(bg_goals_str))
295
+ for uulevel in cast(List[str], parseSexpOneLevel(ulevel))
296
+ for uuulevel in cast(List[str], parseSexpOneLevel(uulevel))]
297
+ if len(fg_goal_strs) > 0 or len(bg_goal_strs) > 0:
298
+ goals: List[SexpObligation] = []
299
+ for goal_str in fg_goal_strs + bg_goal_strs:
300
+ loaded = loads(goal_str)
301
+ goals.append(SexpObligation([['CoqConstr', ty[2]] for ty in loaded[2][1]],
302
+ ['CoqConstr', loaded[1][1]]))
303
+ return goals
304
+ else:
305
+ return []
306
+ def backToState(self, state_num: int) -> None:
307
+ self.addStmt(f"BackTo {state_num}.")
308
+ def backToState_noupdate(self, state_num: int) -> None:
309
+ self.addStmt_noupdate(f"BackTo {state_num}.")
310
+ def _isFeedbackMessage(self, msg: str) -> bool:
311
+ # if self.coq_minor_version() > 12:
312
+ return isFeedbackMessage(msg)
313
+ # return isFeedbackMessageOld(msg)
314
+ def _flush_queue(self) -> None:
315
+ while not self.message_queue.empty():
316
+ self._get_message()
317
+ def _discard_feedback(self) -> None:
318
+ try:
319
+ feedback_message = self._get_message()
320
+ while feedback_message[1][3][1] != Symbol("Processed"):
321
+ feedback_message = self._get_message()
322
+ except CoqTimeoutError:
323
+ pass
324
+ except CoqAnomaly as e:
325
+ if e.msg != "Timing Out":
326
+ raise
327
+ def _get_message(self, complete=False) -> Any:
328
+ msg_text = self._get_message_text(complete=complete)
329
+ assert msg_text != "None", msg_text
330
+ if msg_text[0] != "(":
331
+ eprint(f"Skipping non-sexp output {msg_text}",
332
+ guard=self.verbosity>=3)
333
+ return self._get_message(complete=complete)
334
+ try:
335
+ return loads(msg_text, nil=None)
336
+ except ExpectClosingBracket as exc:
337
+ eprint(
338
+ f"Tried to load a message but it's ill formed! \"{msg_text}\"",
339
+ guard=self.verbosity)
340
+ raise CoqAnomaly("") from exc
341
+ except AssertionError as exc:
342
+ eprint(f"Assertion error while parsing s-expr {msg_text}")
343
+ raise CoqAnomaly("") from exc
344
+ def _get_message_text(self, complete=False) -> Any:
345
+ try:
346
+ msg = self.message_queue.get(timeout=self.timeout)
347
+ if complete:
348
+ self._get_completed()
349
+ assert msg is not None
350
+ return msg
351
+ except queue.Empty as exc3:
352
+ eprint("Command timed out! Interrupting", guard=self.verbosity)
353
+ self._proc.send_signal(signal.SIGINT)
354
+ num_breaks = 1
355
+ try:
356
+ interrupt_response = \
357
+ loads(self.message_queue.get(timeout=self.timeout))
358
+ except queue.Empty:
359
+ self._proc.send_signal(signal.SIGINT)
360
+ num_breaks += 1
361
+ try:
362
+ interrupt_response = \
363
+ loads(self.message_queue.get(timeout=self.timeout))
364
+ except queue.Empty as exc:
365
+ raise CoqAnomaly("Timing Out") from exc
366
+
367
+ got_answer_after_interrupt = match(
368
+ normalizeMessage(interrupt_response),
369
+ ["Answer", int, ["CoqExn", TAIL]],
370
+ lambda *args: False,
371
+ ["Answer", TAIL],
372
+ lambda *args: True,
373
+ _, lambda *args: False)
374
+ if got_answer_after_interrupt:
375
+ self._get_completed()
376
+ for _i in range(num_breaks):
377
+ try:
378
+ after_interrupt_msg = loads(self.message_queue.get(
379
+ timeout=self.timeout))
380
+ except queue.Empty as exc:
381
+ raise CoqAnomaly("Timing Out") from exc
382
+ assert isBreakMessage(after_interrupt_msg), \
383
+ after_interrupt_msg
384
+ assert self.message_queue.empty(), self.messages
385
+ return dumps(interrupt_response)
386
+ for _i in range(num_breaks):
387
+ try:
388
+ after_interrupt_msg = loads(self.message_queue.get(
389
+ timeout=self.timeout))
390
+ except queue.Empty as exc2:
391
+ raise CoqAnomaly("Timing Out") from exc2
392
+ self._get_completed()
393
+ assert self.message_queue.empty(), self.messages
394
+ raise CoqTimeoutError("") from exc3
395
+ # Get the next message from the message queue, and make sure it's
396
+ # a Completed.
397
+ def _get_completed(self) -> None:
398
+ completed = self._get_message()
399
+ match(normalizeMessage(completed),
400
+ ["Answer", int, "Completed"], lambda state: None,
401
+ _, lambda msg: raise_(CompletedError(completed)))
402
+ # Send some text to serapi, and flush the stream to make sure they
403
+ # get it. NOT FOR EXTERNAL USE
404
+ def _send_flush(self, cmd: str):
405
+ assert self._fin
406
+ eprint("SENT: " + re.sub("\n+", "", cmd), guard=self.verbosity >= 4)
407
+ try:
408
+ self._fin.write(cmd.encode('utf-8'))
409
+ self._fin.flush()
410
+ except BrokenPipeError as exc:
411
+ raise CoqAnomaly("Coq process unexpectedly quit. Possibly running "
412
+ "out of memory due to too many threads?") from exc
413
+ def _send_acked(self, cmd: str):
414
+ self._send_flush(cmd)
415
+ self._get_ack()
416
+ def _get_ack(self) -> None:
417
+ ack = self._get_message()
418
+ match(normalizeMessage(ack),
419
+ ["Answer", _, "Ack"], lambda state: None,
420
+ ["Feedback", TAIL], lambda rest: self._get_ack(),
421
+ _, lambda msg: raise_(AckError(dumps(ack))))
422
+ def _update_state(self) -> None:
423
+ self.cur_state = self._get_next_state()
424
+ def _get_next_state(self) -> int:
425
+ msg = self._get_message()
426
+ while match(normalizeMessage(msg),
427
+ ["Feedback", TAIL], lambda tail: True,
428
+ ["Answer", int, "Completed"], lambda sidx: True,
429
+ _, lambda x: False):
430
+ msg = self._get_message()
431
+
432
+ return match(normalizeMessage(msg),
433
+ ["Answer", int, list],
434
+ lambda state_num, contents:
435
+ match(contents,
436
+ ["CoqExn", TAIL],
437
+ lambda rest:
438
+ raise_(CoqAnomaly("Overflowed"))
439
+ if "Stack overflow" in "\n".join(searchStrsInMsg(rest))
440
+ else raise_(CoqExn("\n".join(searchStrsInMsg(rest)))),
441
+ ["Added", int, TAIL],
442
+ lambda state_num, tail: state_num),
443
+ _, lambda x: raise_(BadResponse(msg)))
444
+ def _get_feedbacks(self) -> List['Sexp']:
445
+ unparsed_feedbacks: List[str] = []
446
+ unparsed_next_message = self._get_message_text()
447
+ while unparsed_next_message.startswith("(Feedback"):
448
+ unparsed_feedbacks.append(unparsed_next_message)
449
+ unparsed_next_message = self._get_message_text()
450
+ fin = unparsed_next_message
451
+ if re.match(r"\(Answer\s+\d+\s*\(CoqExn", fin):
452
+ message = "\n".join(searchStrsInMsg(loads(unparsed_feedbacks[-1], nil=None)))
453
+ if "Stack overflow" in message:
454
+ raise CoqAnomaly("Overflowed")
455
+ raise CoqExn(message)
456
+
457
+ return [loads(feedback_text, nil=None) for feedback_text in unparsed_feedbacks]
458
+ def _get_enter_goal_context(self) -> None:
459
+ assert self.proof_context
460
+ self.proof_context = ProofContext([self.proof_context.fg_goals[0]],
461
+ self.proof_context.fg_goals[1:] +
462
+ self.proof_context.bg_goals,
463
+ self.proof_context.shelved_goals,
464
+ self.proof_context.given_up_goals)
465
+ def _get_proof_context(self, update_nonfg_goals: bool = True) -> None:
466
+ # Try to do this the right way, fall back to the
467
+ # wrong way if we run into this bug:
468
+ # https://github.com/ejgallego/coq-serapi/issues/150
469
+ try:
470
+ text_response = self._ask_text("(Query () Goals)")
471
+ context_match = re.fullmatch(
472
+ r"\(Answer\s+\d+\s*\(ObjList\s*(.*)\)\)",
473
+ text_response.strip())
474
+ if not context_match:
475
+ if "Stack overflow" in text_response:
476
+ raise CoqAnomaly(f"\"{text_response}\"")
477
+ raise BadResponse(f"\"{text_response}\"")
478
+ context_str = context_match.group(1)
479
+ if context_str == "()":
480
+ self.proof_context = None
481
+ else:
482
+ goals_match = self.all_goals_regex.match(context_str)
483
+ if not goals_match:
484
+ raise BadResponse(context_str)
485
+ fg_goals_str, bg_goals_str, \
486
+ shelved_goals_str, given_up_goals_str = \
487
+ goals_match.groups()
488
+ if update_nonfg_goals or self.proof_context is None:
489
+ unparsed_levels = cast(List[str],
490
+ parseSexpOneLevel(bg_goals_str))
491
+ parsed2 = [uuulevel
492
+ for ulevel in unparsed_levels
493
+ for uulevel in cast(List[str],
494
+ parseSexpOneLevel(ulevel))
495
+ for uuulevel in
496
+ cast(List[str], parseSexpOneLevel(uulevel))]
497
+ bg_goals = [self._parseSexpGoalStr(bg_goal_str)
498
+ for bg_goal_str in parsed2]
499
+ self.proof_context = ProofContext(
500
+ [self._parseSexpGoalStr(goal)
501
+ for goal in cast(List[str],
502
+ parseSexpOneLevel(fg_goals_str))],
503
+ bg_goals,
504
+ [self._parseSexpGoalStr(shelved_goal)
505
+ for shelved_goal in
506
+ cast(List[str],
507
+ parseSexpOneLevel(shelved_goals_str))],
508
+ [self._parseSexpGoalStr(given_up_goal)
509
+ for given_up_goal in
510
+ cast(List[str],
511
+ parseSexpOneLevel(given_up_goals_str))])
512
+ else:
513
+ self.proof_context = ProofContext(
514
+ [self._parseSexpGoalStr(goal)
515
+ for goal in cast(List[str],
516
+ parseSexpOneLevel(fg_goals_str))],
517
+ unwrap(self.proof_context).bg_goals,
518
+ [self._parseSexpGoalStr(shelved_goal)
519
+ for shelved_goal in
520
+ cast(List[str],
521
+ parseSexpOneLevel(shelved_goals_str))],
522
+ unwrap(self.proof_context).given_up_goals)
523
+ except CoqExn:
524
+ self._send_acked("(Query ((pp ((pp_format PpStr)))) Goals)")
525
+
526
+ msg = self._get_message()
527
+ proof_context_msg = match(
528
+ normalizeMessage(msg),
529
+ ["Answer", int, ["CoqExn", TAIL]],
530
+ lambda statenum, rest:
531
+ raise_(CoqAnomaly("Stack overflow")) if
532
+ "Stack overflow." in searchStrsInMsg(rest) else
533
+ raise_(CoqExn("\n".join(searchStrsInMsg(rest)))),
534
+ ["Answer", int, list],
535
+ lambda statenum, contents: contents,
536
+ _, lambda *args:
537
+ raise_(UnrecognizedError(dumps(msg))))
538
+ self._get_completed()
539
+ if len(proof_context_msg) == 0:
540
+ self.proof_context = None
541
+ else:
542
+ newcontext = self._extract_proof_context(proof_context_msg[1])
543
+ if newcontext == "none":
544
+ self.proof_context = ProofContext([], [], [], [])
545
+ else:
546
+ self.proof_context = \
547
+ ProofContext(
548
+ [parsePPSubgoal(substr) for substr
549
+ in re.split(r"\n\n|(?=\snone)", newcontext)
550
+ if substr.strip()],
551
+ [], [], [])
552
+ def _handle_exception(self, e: CoqException, stmt: str):
553
+ eprint(f"Problem running statement: {stmt}\n",
554
+ guard=self.verbosity >= 2)
555
+ match(e,
556
+ CoqTimeoutError,
557
+ lambda *args: progn(self.cancel_failed(), # type: ignore
558
+ raise_(CoqTimeoutError(
559
+ f"Statment \"{stmt}\" timed out."))),
560
+ _, lambda e: None)
561
+ coqexn_msg = match(normalizeMessage(e.msg),
562
+ ['Answer', int, ['CoqExn', TAIL]],
563
+ lambda sentence_num, rest:
564
+ "\n".join(searchStrsInMsg(rest)),
565
+ str, lambda s: s,
566
+ [str], lambda s: s,
567
+ _, None)
568
+ if coqexn_msg:
569
+ eprint(coqexn_msg, guard=self.verbosity >= 2)
570
+ if ("Stream\\.Error" in coqexn_msg
571
+ or "Syntax error" in coqexn_msg
572
+ or "Syntax Error" in coqexn_msg):
573
+ self._get_completed()
574
+ raise ParseError(f"Couldn't parse command {stmt}")
575
+ if "CLexer.Error" in coqexn_msg:
576
+ self._get_completed()
577
+ raise ParseError(f"Couldn't parse command {stmt}")
578
+ if "NoSuchGoals" in coqexn_msg:
579
+ self._get_completed()
580
+ self.cancel_failed()
581
+ raise NoSuchGoalError("")
582
+ if "Invalid_argument" in coqexn_msg:
583
+ if "index out of bounds" in coqexn_msg and "Anomaly" in coqexn_msg:
584
+ self._get_completed()
585
+ self.cancel_failed()
586
+ raise ParseError(f"Invalid argument in {stmt}")
587
+ if "Not_found" in coqexn_msg:
588
+ self._get_completed()
589
+ self.cancel_failed()
590
+ raise e
591
+ if "Overflowed" in coqexn_msg or "Stack overflow" in coqexn_msg:
592
+ self._get_completed()
593
+ raise CoqAnomaly("Overflowed")
594
+ if "Anomaly" in coqexn_msg:
595
+ self._get_completed()
596
+ raise CoqAnomaly(coqexn_msg)
597
+ if "Unable to unify" in coqexn_msg:
598
+ self._get_completed()
599
+ self.cancel_failed()
600
+ raise CoqExn(coqexn_msg)
601
+ if re.match(r".*The identifier (.*) is reserved\..*",
602
+ coqexn_msg):
603
+ self._get_completed()
604
+ raise CoqExn(coqexn_msg)
605
+ self._get_completed()
606
+ self.cancel_failed()
607
+ raise CoqExn(coqexn_msg)
608
+ match(normalizeMessage(e.msg),
609
+ ['Stream\\.Error', str],
610
+ lambda *args: progn(self._get_completed(), # type: ignore
611
+ raise_(ParseError(
612
+ f"Couldn't parse command {stmt}"))),
613
+
614
+ ['CErrors\\.UserError', _],
615
+ lambda inner: progn(self._get_completed(), # type: ignore
616
+ self.cancel_failed(), # type: ignore
617
+ raise_(e)),
618
+ ['ExplainErr\\.EvaluatedError', TAIL],
619
+ lambda inner: progn(self._get_completed(), # type: ignore
620
+ self.cancel_failed(), # type: ignore
621
+ raise_(e)),
622
+ _, lambda *args: progn(raise_(UnrecognizedError(args))))
623
+ def _ask(self, cmd: str, complete: bool = True):
624
+ return loads(self._ask_text(cmd, complete))
625
+
626
+ def _ask_text(self, cmd: str, complete: bool = True):
627
+ assert self.message_queue.empty(), self.messages
628
+ self._send_acked(cmd)
629
+ msg = self._get_message_text(complete)
630
+ return msg
631
+ def _ppStrToTermStr(self, pp_str: str) -> str:
632
+ answer = self._ask(
633
+ f"(Print ((pp ((pp_format PpStr)))) (CoqPp {pp_str}))")
634
+ return match(normalizeMessage(answer),
635
+ ["Answer", int, ["ObjList", [["CoqString", _]]]],
636
+ lambda statenum, s: str(s),
637
+ ["Answer", int, ["CoqExn", TAIL]],
638
+ lambda statenum, msg:
639
+ raise_(CoqExn("\n".join(searchStrsInMsg(msg)))))
640
+
641
+ def _ppToTermStr(self, pp) -> str:
642
+ return self._ppStrToTermStr(dumps(pp))
643
+
644
+ @functools.lru_cache(maxsize=128)
645
+ def _sexpStrToTermStr(self, sexp_str: str) -> str:
646
+ try:
647
+ answer = self._ask(
648
+ f"(Print ((pp ((pp_format PpStr)))) (CoqConstr {sexp_str}))")
649
+ return match(normalizeMessage(answer),
650
+ ["Answer", int, ["ObjList", [["CoqString", _]]]],
651
+ lambda statenum, s: str(s),
652
+ ["Answer", int, ["CoqExn", TAIL]],
653
+ lambda statenum, msg:
654
+ raise_(CoqExn("\n".join(searchStrsInMsg(msg)))))
655
+ except CoqExn as e:
656
+ eprint("Coq exception when trying to convert to string:\n"
657
+ f"{sexp_str}", guard=self.verbosity >= 1)
658
+ eprint(e, guard=self.verbosity >= 2)
659
+ raise
660
+
661
+ def _sexpToTermStr(self, sexp) -> str:
662
+ return self._sexpStrToTermStr(dumps(sexp))
663
+
664
+ def _parseSexpHypStr(self, sexp_str: str) -> str:
665
+ var_sexps_str, _mid_str, term_sexp_str = \
666
+ cast(List[str], parseSexpOneLevel(sexp_str))
667
+
668
+ def get_id(var_pair_str: str) -> str:
669
+ id_possibly_quoted = unwrap(
670
+ id_regex.match(var_pair_str)).group(1)
671
+ if id_possibly_quoted[0] == "\"" and \
672
+ id_possibly_quoted[-1] == "\"":
673
+ return id_possibly_quoted[1:-1]
674
+ return id_possibly_quoted
675
+ ids_str = ",".join([get_id(var_pair_str) for
676
+ var_pair_str in
677
+ cast(List[str], parseSexpOneLevel(var_sexps_str))])
678
+ term_str = self._sexpStrToTermStr(term_sexp_str)
679
+ return f"{ids_str} : {term_str}"
680
+
681
+ def _parseSexpHyp(self, sexp) -> str:
682
+ var_sexps, _, term_sexp = sexp
683
+ ids_str = ",".join([dumps(var_sexp[1]) for var_sexp in var_sexps])
684
+ term_str = self._sexpToTermStr(term_sexp)
685
+ return f"{ids_str} : {term_str}"
686
+
687
+ def _parseSexpGoalStr(self, sexp_str: str) -> Obligation:
688
+ goal_match = goal_regex.fullmatch(sexp_str)
689
+ assert goal_match, sexp_str + "didn't match"
690
+ _goal_num_str, goal_term_str, hyps_list_str = \
691
+ goal_match.group(1, 2, 3)
692
+ goal_str = self._sexpStrToTermStr(goal_term_str).replace(r"\.", ".")
693
+ hyps = [self._parseSexpHypStr(hyp_str) for hyp_str in
694
+ cast(List[str], parseSexpOneLevel(hyps_list_str))]
695
+ return Obligation(hyps, goal_str)
696
+
697
+ def _parseSexpGoal(self, sexp) -> Obligation:
698
+ _goal_num, goal_term, hyps_list = \
699
+ match(normalizeMessage(sexp),
700
+ [["name", int], ["ty", _], ["hyp", list]],
701
+ lambda *args: args)
702
+ goal_str = self._sexpToTermStr(goal_term)
703
+ hyps = [self._parseSexpHyp(hyp_sexp) for hyp_sexp in hyps_list]
704
+ return Obligation(hyps, goal_str)
705
+
706
+ def _parseBgGoal(self, sexp) -> Obligation:
707
+ return match(normalizeMessage(sexp),
708
+ [[], [_]],
709
+ self._parseSexpGoal)
710
+ def _extract_proof_context(self, raw_proof_context: 'Sexp') -> str:
711
+ assert isinstance(raw_proof_context, list), raw_proof_context
712
+ assert len(raw_proof_context) > 0, raw_proof_context
713
+ assert isinstance(raw_proof_context[0], list), raw_proof_context
714
+ return cast(List[List[str]], raw_proof_context)[0][1]
715
+ def cancel_failed(self) -> None:
716
+ self.__cancel()
717
+ def __cancel(self) -> None:
718
+ self._flush_queue()
719
+ assert self.message_queue.empty(), self.messages
720
+ # Run the cancel
721
+ self._send_acked(f"(Cancel ({self.cur_state}))")
722
+ # Get the response from cancelling
723
+ self.cur_state = self._get_cancelled()
724
+ def _get_cancelled(self) -> int:
725
+ try:
726
+ feedback = self._get_message()
727
+
728
+ new_statenum = \
729
+ match(normalizeMessage(feedback),
730
+ ["Answer", int, ["CoqExn", TAIL]],
731
+ lambda docnum, rest:
732
+ raise_(CoqAnomaly("Overflowed"))
733
+ if "Stack overflow" in "\n".join(searchStrsInMsg(rest))
734
+ else raise_(CoqExn(feedback)),
735
+ ["Feedback", [['doc_id', int], ['span_id', int], TAIL]],
736
+ lambda docnum, statenum, *rest: statenum,
737
+ _, lambda *args: raise_(BadResponse(feedback)))
738
+
739
+ cancelled_answer = self._get_message()
740
+
741
+ match(normalizeMessage(cancelled_answer),
742
+ ["Answer", int, ["Canceled", list]],
743
+ lambda _, statenums: min(statenums),
744
+ ["Answer", int, ["CoqExn", TAIL]],
745
+ lambda statenum, rest:
746
+ raise_(CoqAnomaly("\n".join(searchStrsInMsg(rest))))
747
+ if "Anomaly" in "\n".join(searchStrsInMsg(rest)) else
748
+ raise_(CoqExn("\n".join(searchStrsInMsg(rest)))),
749
+ _, lambda *args: raise_(BadResponse(cancelled_answer)))
750
+ finally:
751
+ self._get_completed()
752
+
753
+ return new_statenum
754
+ def run(self) -> None:
755
+ assert self._fout
756
+ while not self.__sema.acquire(False):
757
+ try:
758
+ line = self._fout.readline().decode('utf-8')
759
+ except ValueError:
760
+ continue
761
+ if line.strip() == '':
762
+ break
763
+ self.message_queue.put(line)
764
+ eprint(f"RECEIVED: {line}", guard=self.verbosity >= 4)
765
+
766
+ def isFeedbackMessageOld(msg: 'Sexp') -> bool:
767
+ return match(normalizeMessage(msg),
768
+ ["Feedback", [["doc_id", int], ["span_id", int],
769
+ ["route", int],
770
+ ["contents", ["Message", "Notice",
771
+ [], TAIL]]]],
772
+ lambda *args: True,
773
+ _, lambda *args: False)
774
+ def isFeedbackMessage(msg: 'Sexp') -> bool:
775
+ return match(normalizeMessage(msg, depth=6),
776
+ ["Feedback", [["doc_id", int], ["span_id", int],
777
+ ["route", int],
778
+ ["contents", ["Message", ["level", "Notice"],
779
+ ["loc", []], TAIL]]]],
780
+ lambda *args: True,
781
+ _, lambda *args: False)
782
+
783
+ def isProgressMessage(msg: 'Sexp') -> bool:
784
+ return match(normalizeMessage(msg),
785
+ ["Feedback", [["doc_id", int], ["span_id", int],
786
+ ["route", int],
787
+ ["contents", ["ProcessingIn", str]]]],
788
+ lambda *args: True,
789
+ ["Feedback", [["doc_id", int], ["span_id", int],
790
+ ["route", int],
791
+ ["contents", "Processed"]]],
792
+ lambda *args: True,
793
+ _,
794
+ lambda *args: False)
795
+
796
+ def isBreakMessage(msg: 'Sexp') -> bool:
797
+ return match(normalizeMessage(msg),
798
+ "Sys.Break", lambda *args: True,
799
+ "Sys\\.Break", lambda *args: True,
800
+ _, lambda *args: False)
801
+
802
+ def normalizeMessage(sexp, depth: int = 5):
803
+ if depth <= 0:
804
+ return sexp
805
+ if isinstance(sexp, list):
806
+ return [normalizeMessage(item, depth=depth-1) for item in sexp]
807
+ if isinstance(sexp, Symbol):
808
+ return dumps(sexp)
809
+ return sexp
810
+
811
+ def searchStrsInMsg(sexp, fuel: int = 30) -> List[str]:
812
+ if isinstance(sexp, list) and len(sexp) > 0 and fuel > 0:
813
+ if sexp[0] == "str" or sexp[0] == Symbol("str"):
814
+ assert len(sexp) == 2 and (isinstance(sexp[1], str) or isinstance(sexp[1], Symbol)), sexp
815
+ return [str(sexp[1])]
816
+ return [substr
817
+ for substrs in [searchStrsInMsg(sublst, fuel - 1)
818
+ for sublst in sexp]
819
+ for substr in substrs]
820
+ return []
821
+
822
+
823
+ goal_regex = re.compile(r"\(\(info\s*\(\(evar\s*\(Ser_Evar\s*(\d+)\)\)"
824
+ r"\(name\s*\((?:\(Id\"?\s*[\w']+\"?\))*\)\)\)\)"
825
+ r"\(ty\s*(.*)\)\s*\(hyp\s*(.*)\)\)")
826
+
827
+ all_goals_regex_10 = re.compile(r"\(\(CoqGoal\s*"
828
+ r"\(\(goals\s*(.*)\)"
829
+ r"\(stack\s*(.*)\)"
830
+ r"\(shelf\s*(.*)\)"
831
+ r"\(given_up\s*(.*)\)"
832
+ r"\(bullet\s*.*\)\)\)\)")
833
+
834
+ all_goals_regex_13 = re.compile(r"\(\(CoqGoal\s*"
835
+ r"\(\(goals\s*(.*)\)"
836
+ r"\(stack\s*(.*)\)"
837
+ r"\(bullet\s*.*\)"
838
+ r"\(shelf\s*(.*)\)"
839
+ r"\(given_up\s*(.*)\)\)\)\)")
840
+
841
+ id_regex = re.compile(r"\(Id\s*(.*)\)")