diff --git a/Admin/components/components.sha1 b/Admin/components/components.sha1 --- a/Admin/components/components.sha1 +++ b/Admin/components/components.sha1 @@ -1,378 +1,379 @@ 59a71e08c34ff01f3f5c4af00db5e16369527eb7 Haskabelle-2013.tar.gz 23a96ff4951d72f4024b6e8843262eda988bc151 Haskabelle-2014.tar.gz eccff31931fb128c1dd522cfc85495c9b66e67af Haskabelle-2015.tar.gz 8ee375cfc38972f080dbc78f07b68dac03efe968 ProofGeneral-3.7.1.1.tar.gz 847b52c0676b5eb0fbf0476f64fc08c2d72afd0c ProofGeneral-4.1.tar.gz 8e0b2b432755ef11d964e20637d1bc567d1c0477 ProofGeneral-4.2-1.tar.gz 51e1e0f399e934020565b2301358452c0bcc8a5e ProofGeneral-4.2-2.tar.gz 8472221c876a430cde325841ce52893328302712 ProofGeneral-4.2.tar.gz fbe83b522cb37748ac1b3c943ad71704fdde2f82 bash_process-1.1.1.tar.gz bb9ef498cd594b4289221b96146d529c899da209 bash_process-1.1.tar.gz 81250148f8b89ac3587908fb20645081d7f53207 bash_process-1.2.1.tar.gz 97b2491382130a841b3bbaebdcf8720c4d4fb227 bash_process-1.2.2.tar.gz 5c5b7c18cc1dc2a4d22b997dac196da09eaca868 bash_process-1.2.3-1.tar.gz 48b01bd9436e243ffcb7297f08b498d0c0875ed9 bash_process-1.2.3.tar.gz 9e21f447bfa0431ae5097301d553dd6df3c58218 bash_process-1.2.tar.gz a65ce644b6094d41e9f991ef851cf05eff5dd0a9 bib2xhtml-20171221.tar.gz 4085dd6060a32d7e0d2e3f874c463a9964fd409b bib2xhtml-20190409.tar.gz f92cff635dfba5d4d77f469307369226c868542c cakeml-2.0.tar.gz e7ffe4238b61a3c1ee87aca4421e7a612e09b836 ci-extras-1.tar.gz e880f31f59bd403fb72fcd3b5afb413c3831a21c csdp-6.1-1.tar.gz 2659100ba8e28e7cb0ecb554178ee5315d4a87f5 csdp-6.1.1.tar.gz a2bd94f4f9281dc70dfda66cf28016c2ffef7ed7 csdp-6.1.tar.gz ec17080269737e4a97b4424a379924c09b338ca2 csdp-6.2.0.tar.gz 70105fd6fbfd1a868383fc510772b95234325d31 csdp-6.x.tar.gz 2f6417b8e96a0e4e8354fe0f1a253c18fb55d9a7 cvc3-2.4.1.tar.gz d70bfbe63590153c07709dea7084fbc39c669841 cvc4-1.5-1.tar.gz 541eac340464c5d34b70bb163ae277cc8829c40f cvc4-1.5-2.tar.gz 1a44895d2a440091a15cc92d7f77a06a2e432507 cvc4-1.5-3.tar.gz c0d8d5929b00e113752d8bf5d11241cd3bccafce cvc4-1.5-4.tar.gz ffb0d4739c10eb098eb092baef13eccf94a79bad cvc4-1.5-5.tar.gz 3682476dc5e915cf260764fa5b86f1ebdab57507 cvc4-1.5.tar.gz a5e02b5e990da4275dc5d4480c3b72fc73160c28 cvc4-1.5pre-1.tar.gz 4d9658fd2688ae8ac78da8fdfcbf85960f871b71 cvc4-1.5pre-2.tar.gz b01fdb93f2dc2b8bcfd41c6091d91b37d6e240f9 cvc4-1.5pre-3.tar.gz 76ff6103b8560f0e2778bbfbdb05f5fa18f850b7 cvc4-1.5pre-4.tar.gz 03aec2ec5757301c9df149f115d1f4f1d2cafd9e cvc4-1.5pre.tar.gz e99560d0b7cb9bafde2b0ec1a3a95af315918a25 cvc4-1.8.tar.gz 842d9526f37b928cf9e22f141884365129990d63 cygwin-20130110.tar.gz cb3b0706d208f104b800267697204f6d82f7b48a cygwin-20130114.tar.gz 3b44cca04855016d5f8cfb5101b2e0579ab80197 cygwin-20130117.tar.gz 1fde9ddf0fa4f398965113d0c0c4f0e97c78d008 cygwin-20130716.tar.gz a03735a53c2963eb0b453f6a7282d3419f28bf38 cygwin-20130916.tar.gz 7470125fc46e24ee188bdaacc6d560e01b6fa839 cygwin-20140520.tar.gz db4dedae026981c5f001be283180abc1962b79ad cygwin-20140521.tar.gz acbc4bf161ad21e96ecfe506266ccdbd288f8a6f cygwin-20140530.tar.gz 3dc680d9eb85276e8c3e9f6057dad0efe2d5aa41 cygwin-20140626.tar.gz 8e562dfe57a2f894f9461f4addedb88afa108152 cygwin-20140725.tar.gz 238d8e30e8e22495b7ea3f5ec36e852e97fe8bbf cygwin-20140813.tar.gz 629b8fbe35952d1551cd2a7ff08db697f6dff870 cygwin-20141024.tar.gz ce93d0b3b2743c4f4e5bba30c2889b3b7bc22f2c cygwin-20150410.tar.gz fa712dd5ec66ad16add1779d68aa171ff5694064 cygwin-20151210.tar.gz 056b843d5a3b69ecf8a52c06f2ce6e696dd275f9 cygwin-20151221.tar.gz 44f3a530f727e43a9413226c2423c9ca3e4c0cf5 cygwin-20161002.tar.gz dd56dd16d861fc6e1a008bf5e9da6f33ed6eb820 cygwin-20161022.tar.gz d9ad7aae99d54e3b9813151712eb88a441613f04 cygwin-20161024.tar.gz f8eb6a0f722e3cfe3775d1204c5c7063ee1f008e cygwin-20170828.tar.gz c22048912b010a5a0b4f2a3eb4d318d6953761e4 cygwin-20170930.tar.gz 5a3919e665947b820fd7f57787280c7512be3782 cygwin-20180604.tar.gz 2aa049170e8088de59bd70eed8220f552093932d cygwin-20190320.tar.gz fb898e263fcf6f847d97f564fe49ea0760bb453f cygwin-20190322.tar.gz cd01fac0ab4fdb50a2bbb6416da3f15a4d540da1 cygwin-20190524.tar.gz caa616fbab14c1fce790a87db5c4758c1322cf28 cygwin-20200116.tar.gz f053a9ab01f0be9cb456560f7eff66a8e7ba2fd2 cygwin-20200323.tar.gz 0107343cd2562618629f73b2581168f0045c3234 cygwin-20201002.tar.gz a3d481401b633c0ee6abf1da07d75da94076574c cygwin-20201130.tar.gz 0fe549949a025d65d52d6deca30554de8fca3b6e e-1.5.tar.gz 2e293256a134eb8e5b1a283361b15eb812fbfbf1 e-1.6-1.tar.gz e1919e72416cbd7ac8de5455caba8901acc7b44d e-1.6-2.tar.gz b98a98025d1f7e560ca6864a53296137dae736b4 e-1.6.tar.gz c11b25c919e2ec44fe2b6ac2086337b456344e97 e-1.8.tar.gz a895a96ec7e6fcc275114bb9b4c92b20fac73dba e-2.0-1.tar.gz 2ebd7e3067a2cdae3cb8b073345827013978d74b e-2.0-2.tar.gz fac44556dd16f666a2c186be30aa6d8c67228bb9 e-2.0-3.tar.gz 5d36fb62912cfcff7f3b99a6266c578aafc288b7 e-2.0-4.tar.gz 3223c51c0b16fe00ced4ae903041fff858e61742 e-2.0-5.tar.gz 6b962a6b4539b7ca4199977973c61a8c98a492e8 e-2.0.tar.gz 66449a7b68b7d85a7189e10735a81069356123b6 e-2.5-1.tar.gz 813b66ca151d7a39b5cacb39ab52acabc2a54845 e-2.5.tar.gz 6d34b18ca0aa1e10bab6413045d079188c0e2dfb exec_process-1.0.1.tar.gz 8b9bffd10e396d965e815418295f2ee2849bea75 exec_process-1.0.2.tar.gz e6aada354da11e533af2dee3dcdd96c06479b053 exec_process-1.0.3.tar.gz ae7ee5becb26512f18c609e83b34612918bae5f0 exec_process-1.0.tar.gz 7a4b46752aa60c1ee6c53a2c128dedc8255a4568 flatlaf-0.46-1.tar.gz ed5cbc216389b655dac21a19e770a02a96867b85 flatlaf-0.46.tar.gz 683acd94761ef460cca1a628f650355370de5afb hol-light-bundle-0.5-126.tar.gz 20b53cfc3ffc5b15c1eabc91846915b49b4c0367 isabelle_fonts-20151021.tar.gz 736844204b2ef83974cd9f0a215738b767958c41 isabelle_fonts-20151104.tar.gz 9502c1aea938021f154adadff254c5c55da344bd isabelle_fonts-20151106.tar.gz f5c63689a394b974ac0d365debda577c6fa31c07 isabelle_fonts-20151107.tar.gz 812101680b75f7fa9ee8e138ea6314fa4824ea2d isabelle_fonts-20151229.tar.gz 2730e1475c7d655655882e75743e0b451725a274 isabelle_fonts-20151231.tar.gz 1f004a6bf20088a7e8f1b3d4153aa85de6fc1091 isabelle_fonts-20160101.tar.gz 379d51ef3b71452dac34ba905def3daa8b590f2e isabelle_fonts-20160102.tar.gz 878536aab1eaf1a52da560c20bb41ab942971fa3 isabelle_fonts-20160227.tar.gz 8ff0eedf0191d808ecc58c6b3149a4697f29ab21 isabelle_fonts-20160812-1.tar.gz 9283e3b0b4c7239f57b18e076ec8bb21021832cb isabelle_fonts-20160812.tar.gz 620cffeb125e198b91a716da116f754d6cc8174b isabelle_fonts-20160830.tar.gz b70690c85c05d0ca5bc29287abd20142f6ddcfb0 isabelle_fonts-20171222.tar.gz c17c482e411bbaf992498041a3e1dea80336aaa6 isabelle_fonts-20171230.tar.gz 3affbb306baff37c360319b21cbaa2cc96ebb282 isabelle_fonts-20180113.tar.gz bee32019e5d7cf096ef2ea1d836c732e9a7628cc isabelle_fonts-20181124.tar.gz f249bc2c85bd2af9eee509de17187a766b74ab86 isabelle_fonts-20181129.tar.gz 928b5320073d04d93bcc5bc4347b6d01632b9d45 isabelle_fonts-20190210.tar.gz dfcdf9a757b9dc36cee87f82533b43c58ba84abe isabelle_fonts-20190309.tar.gz 95e3acf038df7fdeeacd8b4769930e6f57bf3692 isabelle_fonts-20190406.tar.gz dabcf5085d67c99159007007ff0e9bf775e423d1 isabelle_fonts-20190409.tar.gz 76827987c70051719e117138858930d42041f57d isabelle_fonts-20190717.tar.gz 0b2206f914336dec4923dd0479d8cee4b904f544 jdk-11+28.tar.gz 3e05213cad47dbef52804fe329395db9b4e57f39 jdk-11.0.2+9.tar.gz 06ac8993b5bebd02c70f1bd18ce13075f01115f3 jdk-11.0.3+7.tar.gz e7e3cc9b0550c1e5d71197ad8c30f92b622d7183 jdk-11.0.4+11.tar.gz 49007a84a2643a204ce4406770dfd574b97880d9 jdk-11.0.5+10.tar.gz 3c250e98eb82f98afc6744ddc9170d293f0677e1 jdk-11.0.6+10.tar.gz 76cf7a141e15db30bd975089c65c833b58092aa7 jdk-11.0.9+11.tar.gz 71d19df63816e9be1c4c5eb44aea7a44cfadb319 jdk-11.tar.gz 72455a2fdb6cced9cd563f4d5d6134f7a6c34913 jdk-15.0.1+9.tar.gz 8d83e433c1419e0c0cc5fd1762903d11b4a5752c jdk-6u31.tar.gz 38d2d2a91c66714c18430e136e7e5191af3996e6 jdk-7u11.tar.gz d765bc4ad2f34d494429b2a8c1563c49db224944 jdk-7u13.tar.gz 13a265e4b706ece26fdfa6fc9f4a3dd1366016d2 jdk-7u21.tar.gz 5080274f8721a18111a7f614793afe6c88726739 jdk-7u25.tar.gz dd24d63afd6d17b29ec9cb2b2464d4ff2e02de2c jdk-7u40.tar.gz ec740ee9ffd43551ddf1e5b91641405116af6291 jdk-7u6.tar.gz 71b629b2ce83dbb69967c4785530afce1bec3809 jdk-7u60.tar.gz e119f4cbfa2a39a53b9578d165d0dc44b59527b7 jdk-7u65.tar.gz d6d1c42989433839fe64f34eb77298ef6627aed4 jdk-7u67.tar.gz b66039bc6dc2bdb2992133743005e1e4fc58ae24 jdk-7u72.tar.gz d980055694ddfae430ee001c7ee877d535e97252 jdk-7u76.tar.gz baa6de37bb6f7a104ce5fe6506bca3d2572d601a jdk-7u80.tar.gz 7d5b152ac70f720bb9e783fa45ecadcf95069584 jdk-7u9.tar.gz baf275a68d3f799a841932e4e9a95a1a604058ae jdk-8u102.tar.gz 5442f1015a0657259be0590b04572cd933431df7 jdk-8u11.tar.gz 741de6a4a805a0f9fb917d1845409e99346c2747 jdk-8u112.tar.gz ae7df8bd0c18eb40237cf54cc28933f4893b9c92 jdk-8u121.tar.gz 51531a3a0c16e180ed95cb7d2bd680c2ec0aa553 jdk-8u131.tar.gz e45edcf184f608d6f4a7b966d65a5d3289462693 jdk-8u144.tar.gz 264e806b9300a4fb3b6e15ba0e2c664d4ea698c8 jdk-8u152.tar.gz 84b04d877a2ea3a4e2082297b540e14f76722bc5 jdk-8u162.tar.gz 87303a0de3fd595aa3857c8f7cececa036d6ed18 jdk-8u172.tar.gz 9ae0338a5277d8749b4b4c7e65fc627319d98b27 jdk-8u181.tar.gz cfecb1383faaf027ffbabfcd77a0b6a6521e0969 jdk-8u20.tar.gz 44ffeeae219782d40ce6822b580e608e72fd4c76 jdk-8u31.tar.gz c95ebf7777beb3e7ef10c0cf3f734cb78f9828e4 jdk-8u5.tar.gz 4132cf52d5025bf330d53b96a5c6466fef432377 jdk-8u51.tar.gz 74df343671deba03be7caa49de217d78b693f817 jdk-8u60.tar.gz dfb087bd64c3e5da79430e0ba706b9abc559c090 jdk-8u66.tar.gz 2ac389babd15aa5ddd1a424c1509e1c459e6fbb1 jdk-8u72.tar.gz caa0cf65481b6207f66437576643f41dabae3c83 jdk-8u92.tar.gz 44775a22f42a9d665696bfb49e53c79371c394b0 jedit_build-20111217.tar.gz a242a688810f2bccf24587b0062ce8027bf77fa2 jedit_build-20120304.tar.gz 4c948dee53f74361c097c08f49a1a5ff9b17bd1d jedit_build-20120307.tar.gz 9c221fe71af8a063fcffcce21672a97aea0a8d5b jedit_build-20120313.tar.gz ed72630f307729df08fdedb095f0af8725f81b9c jedit_build-20120327.tar.gz 6425f622625024c1de27f3730d6811f6370a19cd jedit_build-20120414.tar.gz 7b012f725ec1cc102dc259df178d511cc7890bba jedit_build-20120813.tar.gz 8e1d36f5071e3def2cb281f7fefe9f52352cb88f jedit_build-20120903.tar.gz 8fa0c67f59beba369ab836562eed4e56382f672a jedit_build-20121201.tar.gz 06e9be2627ebb95c45a9bcfa025d2eeef086b408 jedit_build-20130104.tar.gz c85c0829b8170f25aa65ec6852f505ce2a50639b jedit_build-20130628.tar.gz 5de3e399be2507f684b49dfd13da45228214bbe4 jedit_build-20130905.tar.gz 87136818fd5528d97288f5b06bd30c787229eb0d jedit_build-20130910.tar.gz c63189cbe39eb8104235a0928f579d9523de78a9 jedit_build-20130925.tar.gz 65cc13054be20d3a60474d406797c32a976d7db7 jedit_build-20130926.tar.gz 30ca171f745adf12b65c798c660ac77f9c0f9b4b jedit_build-20131106.tar.gz 054c1300128f8abd0f46a3e92c756ccdb96ff2af jedit_build-20140405.tar.gz 4a963665537ea66c69de4d761846541ebdbf69f2 jedit_build-20140511.tar.gz a9d637a30f6a87a3583f265da51e63e3619cff52 jedit_build-20140722.tar.gz f29391c53d85715f8454e1aaa304fbccc352928f jedit_build-20141018.tar.gz d7206d4c9d14d3f4c8115422b7391ffbcc6e80b4 jedit_build-20141026.tar.gz f15d36abc1780875a46b6dbd4568e43b776d5db6 jedit_build-20141104.tar.gz 14ce124c897abfa23713928dc034d6ef0e1c5031 jedit_build-20150228.tar.gz b5f7115384c167559211768eb5fe98138864473b jedit_build-20151023.tar.gz 8ba7b6791be788f316427cdcd805daeaa6935190 jedit_build-20151124.tar.gz c70c5a6c565d435a09a8639f8afd3de360708e1c jedit_build-20160330.tar.gz d4e1496c257659cf15458d718f4663cdd95a404e jedit_build-20161024.tar.gz d806c1c26b571b5b4ef05ea11e8b9cf936518e06 jedit_build-20170319.tar.gz 7bcb202e13358dd750e964b2f747664428b5d8b3 jedit_build-20180417.tar.gz 23c8a05687d05a6937f7d600ac3aa19e3ce59c9c jedit_build-20180504.tar.gz 9c64ee0705e5284b507ca527196081979d689519 jedit_build-20181025.tar.gz cfa65bf8720b9b798ffa0986bafbc8437f44f758 jedit_build-20181026.tar.gz 847492b75b38468268f9ea424d27d53f2d95cef4 jedit_build-20181203.tar.gz 536a38ed527115b4bf2545a2137ec57b6ffad718 jedit_build-20190120.tar.gz 58b9f03e5ec0b85f8123c31f5d8092dae5803773 jedit_build-20190130.tar.gz ec0aded5f2655e2de8bc4427106729e797584f2f jedit_build-20190224.tar.gz 1e53598a02ec8d8736b15f480cbe2c84767a7827 jedit_build-20190508.tar.gz b9c6f49d3f6ebe2e85a50595ce7412d01a4314ac jedit_build-20190717.tar.gz 1c753beb93e92e95e99e8ead23a68346bd1af44a jedit_build-20200610.tar.gz 533b1ee6459f59bcbe4f09e214ad2cb990fb6952 jedit_build-20200908.tar.gz f9966b5ed26740bb5b8bddbfe947fcefaea43d4d jedit_build-20201223.tar.gz 0bd2bc2d9a491ba5fc8dd99df27c04f11a72e8fa jfreechart-1.0.14-1.tar.gz 8122526f1fc362ddae1a328bdbc2152853186fee jfreechart-1.0.14.tar.gz d911f63a5c9b4c7335bb73f805cb1711ce017a84 jfreechart-1.5.0.tar.gz d84b7d8ef273afec55284327fca7dd20f5ecb77a jfreechart-1.5.1.tar.gz c8a19a36adf6cefa779d85f22ded2f4654e68ea5 jortho-1.0-1.tar.gz 2155e0bdbd29cd3d2905454de2e7203b9661d239 jortho-1.0-2.tar.gz ffe179867cf5ffaabbb6bb096db9bdc0d7110065 jortho-1.0.tar.gz 6c737137cc597fc920943783382e928ea79e3feb kodkodi-1.2.16.tar.gz afb04f4048a87bb888fe7b05b0139cb060c7925b kodkodi-1.5.2-1.tar.gz 5f95c96bb99927f3a026050f85bd056f37a9189e kodkodi-1.5.2.tar.gz 0634a946b216f7f07f1a0f7e28cf345daa28828f kodkodi-1.5.3.tar.gz 52e95b3493d71902f9df89d0bb59d0046a5f0c63 kodkodi-1.5.4-1.tar.gz 267189c637de26cf304d699cfa95389da002b250 kodkodi-1.5.4.tar.gz 3ecdade953bb455ed2907952be287d7e5cf6533b kodkodi-1.5.5.tar.gz 6b12bf3f40b16fae8ff22aa39171fa018d107cb3 kodkodi-1.5.6.tar.gz 377e36efb8608e6c828c7718d890e97fde2006a4 linux_app-20131007.tar.gz 759848095e2ad506083d92b5646947e3c32f27a0 linux_app-20191223.tar.gz 1a449ce69ac874e21804595d16aaaf5a0d0d0c10 linux_app-20200110.tar.gz 0aab4f73ff7f5e36f33276547e10897e1e56fb1d macos_app-20130716.tar.gz ad5d0e640ce3609a885cecab645389a2204e03bb macos_app-20150916.tar.gz 400af57ec5cd51f96928d9de00d077524a6fe316 macos_app-20181205.tar.gz 3bc42b8e22f0be5ec5614f1914066164c83498f8 macos_app-20181208.tar.gz 26df569cee9c2fd91b9ac06714afd43f3b37a1dd nunchaku-0.3.tar.gz e573f2cbb57eb7b813ed5908753cfe2cb41033ca nunchaku-0.5.tar.gz fe57793aca175336deea4f5e9c0d949a197850ac opam-1.2.2.tar.gz eb499a18e7040ca0fe1ca824c9dcb2087c47c9ba opam-2.0.3-1.tar.gz 002f74c9e65e650de2638bf54d7b012b8de76c28 opam-2.0.3.tar.gz ddb3b438430d9565adbf5e3d913bd52af8337511 opam-2.0.6.tar.gz fc66802c169f44511d3be30435eb89a11e635742 opam-2.0.7.tar.gz 1c8cb6a8f4cbeaedce2d6d1ba8fc7e2ab3663aeb polyml-5.4.1.tar.gz a3f9c159a0ee9a63b7a5d0c835ed9c2c908f8b56 polyml-5.5.0-1.tar.gz 7d604a99355efbfc1459d80db3279ffa7ade3e39 polyml-5.5.0-2.tar.gz b3d776e6744f0cd2773d467bc2cfe1de3d1ca2fd polyml-5.5.0-3.tar.gz 1812e9fa6d163f63edb93e37d1217640a166cf3e polyml-5.5.0.tar.gz 36f5b8224f484721749682a3655c796a55a2718d polyml-5.5.1-1.tar.gz 36f78f27291a9ceb13bf1120b62a45625afd44a6 polyml-5.5.1.tar.gz a588640dbf5da9ae15455b02ef709764a48637dc polyml-5.5.2-1.tar.gz 4b690390946f7bfb777b89eb16d6f08987cca12f polyml-5.5.2-2.tar.gz 5b31ad8556e41dfd6d5e85f407818be399aa3d2a polyml-5.5.2-3.tar.gz 532f6e8814752aeb406c62fabcfd2cc05f8a7ca8 polyml-5.5.2.tar.gz 1c53f699d35c0db6c7cf4ea51f2310adbd1d0dc5 polyml-5.5.3-20150820.tar.gz b4b624fb5f34d1dc814fb4fb469fafd7d7ea018a polyml-5.5.3-20150908.tar.gz b668e1f43a41608a8eb365c5e19db6c54c72748a polyml-5.5.3-20150911.tar.gz 1f5cd9b1390dab13861f90dfc06d4180cc107587 polyml-5.5.3-20150916.tar.gz f78896e588e8ebb4da57bf0c95210b0f0fa9e551 polyml-5.6-1.tar.gz 21fa0592b7dfd23269063f42604438165630c0f0 polyml-5.6-2.tar.gz 03ba81e595fa6d6df069532d67ad3195c37d9046 polyml-5.6-20151123.tar.gz 822f489c18e38ce5ef979ec21dccce4473e09be6 polyml-5.6-20151206.tar.gz bd6a448f0e0d5787747f4f30ca661f9c1868e4a7 polyml-5.6-20151223.tar.gz 5b70c12c95a90d858f90c1945011289944ea8e17 polyml-5.6-20160118.tar.gz 5b19dc93082803b82aa553a5cfb3e914606c0ffd polyml-5.6.tar.gz 80b923fca3533bf291ff9da991f2262a98b68cc4 polyml-5.7-20170217.tar.gz 381a70cecf0fdee47f6842e2bdb5107ed52adab6 polyml-5.7.1-1.tar.gz 39dac33b569ac66f76126b8f4edc6d9227bd8a63 polyml-5.7.1-2.tar.gz 0b896ccc35bd3f2541cd55e6f0ed14637ed9fc68 polyml-5.7.1-4.tar.gz 262450ac9966abebae2e1d4f9ae703cfe0f5d8d9 polyml-5.7.1-5.tar.gz 1aeb57877d694db7fe4d4395287cddf3bc77710b polyml-5.7.1-6.tar.gz e3e7e20b1e0e5d5d68df4cd4caa1e1a7410d46b6 polyml-5.7.1-7.tar.gz 1430533c09b17f8be73798a47a5f409d43a04cf4 polyml-5.7.1-8.tar.gz 171b5783b88522a35e4822b19ef8ba838c04f494 polyml-5.7.1.tar.gz 5fbcab1da2b5eb97f24da2590ece189d55b3a105 polyml-5.7.tar.gz 51e024225b460900da5279f0b91b217085f98cf9 polyml-5.8-20190220.tar.gz 20a83fa58d497b533150defe39bcd4540529b25f polyml-5.8-20190306.tar.gz 9f0e9cd10df4c3383b063eb076e8b698ca50c3d0 polyml-5.8.1-20191101.tar.gz f46deb909d645ac8c140968e4d32b5763beb9add polyml-5.8.1-20191113.tar.gz 36a40a981b57daae0463d14940a8edf6fa1af179 polyml-5.8.1-20191114.tar.gz 525b05536b08c11a1eae943fe6818a8622326084 polyml-5.8.1-20191124.tar.gz 9043828803483ca14df64488dff014ad050a6d34 polyml-5.8.1-20200228.tar.gz 1186607e2c43b77db86731f12fbedb531ca50a21 polyml-5.8.1-20200708.tar.gz 22ae16bf7850e73b903d2ca8eb506da05b441cf3 polyml-5.8.1.tar.gz d1fd6eced69dc1df7226432fcb824568e0994ff2 polyml-5.8.tar.gz 49f1adfacdd6d29fa9f72035d94a31eaac411a97 polyml-test-0a6ebca445fc.tar.gz 2a8c4421e0a03c0d6ad556b3c36c34eb11568adb polyml-test-1236652ebd55.tar.gz 8e83fb5088cf265902b8da753a8eac5fe3f6a14b polyml-test-159dc81efc3b.tar.gz a0064c157a59e2706e18512a49a6dca914fa17fc polyml-test-1b2dcf8f5202.tar.gz 4e6543dbbb2b2aa402fd61428e1c045c48f18b47 polyml-test-79534495ee94.tar.gz 853ab0e9ff2b73790cc80a2d36cbff8b03e50a8e polyml-test-7a7b742897e9.tar.gz 85bfda83d138e936fdafd68ed3627b1058e5c2c3 polyml-test-7e49fce62e3d.tar.gz c629cd499a724bbe37b962f727e4ff340c50299d polyml-test-8529546198aa.tar.gz 7df4857d73dbc9edda25a6ad329e47639e70fadf polyml-test-8fda4fd22441.tar.gz 2b7c02b67feb2f44dda6938a7244f4257e7c580c polyml-test-905dae2ebfda.tar.gz 3dfdc58e5d9b28f038a725e05c9c2f2ce0bb2632 polyml-test-a3cfdf648da-1.tar.gz e2f075b0cc709f4f7f6492b725362f9010b2c6d1 polyml-test-a3cfdf648da-2.tar.gz 33568f69ce813b7405386ddbefa14ad0342bb8f0 polyml-test-a3cfdf648da.tar.gz 4bedaac4f1fb9a9199aa63695735063c47059003 polyml-test-a444f281ccec.tar.gz f3031692edcc5d8028a42861e4e40779f0f9d3e1 polyml-test-b68438d33c69.tar.gz cb2318cff6ea9293cd16a4435a4fe28ad9dbe0b8 polyml-test-cf46747fee61.tar.gz 67ffed2f98864721bdb1e87f0ef250e4c69e6160 polyml-test-d68c6736402e.tar.gz b4ceeaac47f3baae41c2491a8368b03217946166 polyml-test-e7a662f8f9c4.tar.gz 609c7d09d3ed01156ff91261e801e2403ff93729 polyml-test-e8d82343b692.tar.gz b6d87466e9b44e8ef4a2fac74c96b139080a506a polyml-test-f54aa41240d0.tar.gz d365f3fc11c2427cafc62b3c79951880a1476ebb polyml-test-f86ae3dc1686.tar.gz a619177143fea42a464f49bb864665407c07a16c polyml-test-fb4f42af00fa.tar.gz 53123dc011b2d4b4e8fe307f3c9fa355718ad01a postgresql-42.1.1.tar.gz 3a5d31377ec07a5069957f5477a4848cfc89a594 postgresql-42.1.4.tar.gz 7d6ef4320d5163ceb052eb83c1cb3968f099a422 postgresql-42.2.18.tar.gz e7cd5c7955e9eb5ce8cd07feb97230b23d2eec40 postgresql-42.2.2.tar.gz 231b33c9c3c27d47e3ba01b399103d70509e0731 postgresql-42.2.5.tar.gz 6335fbc0658e447b5b9bc48c9ad36e33a05bb72b postgresql-42.2.9.tar.gz f132329ca1045858ef456cc08b197c9eeea6881b postgresql-9.4.1212.tar.gz 0885e1f1d8feaca78d2f204b6487e6eec6dfab4b scala-2.10.0.tar.gz f7dc7a4e1aea46408fd6e44b8cfacb33af61afbc scala-2.10.1.tar.gz 207e4916336335386589c918c5e3f3dcc14698f2 scala-2.10.2.tar.gz 21c8ee274ffa471ab54d4196ecd827bf3d43e591 scala-2.10.3.tar.gz d4688ddaf83037ca43b5bf271325fc53ae70e3aa scala-2.10.4.tar.gz 44d12297a78988ffd34363535e6a8e0d94c1d8b5 scala-2.11.0.tar.gz 14f20de82b25215a5e055631fb147356400625e6 scala-2.11.1.tar.gz 4fe9590d08e55760b86755d3fab750e90ac6c380 scala-2.11.2.tar.gz 27a296495b2167148de06314ed9a942f2dbe23fe scala-2.11.4.tar.gz 4b24326541161ce65424293ca9da3e7c2c6ab452 scala-2.11.5.tar.gz e7cf20e3b27c894c6127c7a37042c1667f57385e scala-2.11.6.tar.gz 4810c1b00719115df235be1c5991aa6ea7186134 scala-2.11.7.tar.gz 3eca4b80710996fff87ed1340dcea2c5f6ebf4f7 scala-2.11.8.tar.gz 0004e53f885fb165b50c95686dec40d99ab0bdbd scala-2.12.0.tar.gz 059cbdc58d36e3ac1fffcccd9139ecd34f271882 scala-2.12.10.tar.gz 82056106aa6fd37c159ea76d16096c20a749cccd scala-2.12.11.tar.gz fe7ff585acffaad7f0dd4a1d079134d15c26ed0d scala-2.12.12.tar.gz 74a8c3dab3a25a87357996ab3e95d825dc820fd0 scala-2.12.2.tar.gz d66796a68ec3254b46b17b1f8ee5bcc56a93aacf scala-2.12.3.tar.gz 1636556167dff2c191baf502c23f12e09181ef78 scala-2.12.4.tar.gz 8171f494bba54fb0d01c887f889ab8fde7171c2a scala-2.12.5.tar.gz 54c1b06fa2c5f6c2ab3d391ef342c0532cd7f392 scala-2.12.6.tar.gz 02358f00acc138371324b6248fdb62eed791c6bd scala-2.12.7.tar.gz 201c05ae9cc382ee6c08af49430e426f6bbe0d5a scala-2.12.8.tar.gz +ec53cce3c5edda1145ec5d13924a5f9418995c15 scala-2.13.4.tar.gz b447017e81600cc5e30dd61b5d4962f6da01aa80 scala-2.8.1.final.tar.gz 5659440f6b86db29f0c9c0de7249b7e24a647126 scala-2.9.2.tar.gz abe7a3b50da529d557a478e9f631a22429418a67 smbc-0.4.1.tar.gz cbd491c0feba1d21019d05564e76dd04f592ccb4 spass-3.8ds-1.tar.gz edaa1268d82203067657aabcf0371ce7d4b579b9 spass-3.8ds-2.tar.gz 43b5afbcad575ab6817d2289756ca22fd2ef43a9 spass-3.8ds.tar.gz b016a785f1f78855c00d351ff598355c3b87450f sqlite-jdbc-3.18.0-1.tar.gz b85b5bc071a59ef2a8326ceb1617d5a9a5be41cf sqlite-jdbc-3.18.0.tar.gz e56117a67ab01fb24c7fc054ede3160cefdac5f8 sqlite-jdbc-3.20.0.tar.gz 27aeac6a91353d69f0438837798ac4ae6f9ff8c5 sqlite-jdbc-3.23.1.tar.gz 4d17611857fa3a93944c1f159c0fd2a161967aaf sqlite-jdbc-3.27.2.1.tar.gz 806be457eb79408fcc5a72aeca3f64b2d89a6b63 sqlite-jdbc-3.30.1.tar.gz cba2b194114216b226d75d49a70d1bd12b141ac8 sqlite-jdbc-3.32.3.2.tar.gz 29306acd6ce9f4c87032b2c271c6df035fe7d4d3 sqlite-jdbc-3.34.0.tar.gz 8d20968603f45a2c640081df1ace6a8b0527452a sqlite-jdbc-3.8.11.2.tar.gz 2369f06e8d095f9ba26df938b1a96000e535afff ssh-java-20161009.tar.gz a2335d28b5b95d8d26500a53f1a9303fc5beaf36 ssh-java-20190323.tar.gz fdc415284e031ee3eb2f65828cbc6945736fe995 stack-1.9.1.tar.gz 6e19948ff4a821e2052fc9b3ddd9ae343f4fcdbb stack-1.9.3.tar.gz f969443705aa8619e93af5b34ea98d15cd7efaf1 stack-2.1.3.tar.gz ebd0221d038966aa8bde075f1b0189ff867b02ca stack-2.5.1.tar.gz 1f4a2053cc1f34fa36c4d9d2ac906ad4ebc863fd sumatra_pdf-2.1.1.tar.gz 601e08d048d8e50b0729429c8928b667d9b6bde9 sumatra_pdf-2.3.2.tar.gz 14d46c2eb1a34821703da59d543433f581e91df3 sumatra_pdf-2.4.tar.gz 44d67b6742919ce59a42368fc60e2afa210a3e42 sumatra_pdf-2.5.2.tar.gz 89719a13bc92810730a430973684629426ed1b2a sumatra_pdf-3.0.tar.gz f5afcc82f8e734665d38867e99475d3ad0d5ed15 sumatra_pdf-3.1.1.tar.gz a45eca5c1277f42f87bb8dc12a3074ccf5488221 sumatra_pdf-3.1.2-1.tar.gz 3b3239b2e6f8062b90d819f3703e30a50f4fa1e7 sumatra_pdf-3.1.2-2.tar.gz 8486387f61557147ec06b1f637117c017c8f0528 sumatra_pdf-3.1.2.tar.gz 869ea6d8ea35c8ba68d7fcb028f16b2b7064c5fd vampire-1.0.tar.gz 399f687b56575b93e730f68c91c989cb48aa34d8 vampire-4.2.2.tar.gz 98c5c79fef7256db9f64c8feea2edef0a789ce46 verit-2016post.tar.gz 52ba18a6c96b53c5ae9b179d5a805a0c08f1da6d verit-2020.10-rmx-1.tar.gz b6706e74e20e14038e9b38f0acdb5639a134246a verit-2020.10-rmx.tar.gz 81d21dfd0ea5c58f375301f5166be9dbf8921a7a windows_app-20130716.tar.gz fe15e1079cf5ad86f3cbab4553722a0d20002d11 windows_app-20130905.tar.gz e6a43b7b3b21295853bd2a63b27ea20bd6102f5f windows_app-20130906.tar.gz 8fe004aead867d4c82425afac481142bd3f01fb0 windows_app-20130908.tar.gz d273abdc7387462f77a127fa43095eed78332b5c windows_app-20130909.tar.gz c368908584e2bca38b3bcb20431d0c69399fc2f0 windows_app-20131130.tar.gz c3f5285481a95fde3c1961595b4dd0311ee7ac1f windows_app-20131201.tar.gz 14807afcf69e50d49663d5b48f4b103f30ae842b windows_app-20150821.tar.gz ed106181510e825bf959025d8e0a2fc3f78e7a3f windows_app-20180417.tar.gz e809e4ab0d33cb413a7c47dd947e7dbdfcca1c24 windows_app-20181002.tar.gz 9e96ba128a0617a9020a178781df49d48c997e19 windows_app-20181006.tar.gz 1c36a840320dfa9bac8af25fc289a4df5ea3eccb xz-java-1.2-1.tar.gz 2ae13aa17d0dc95ce254a52f1dba10929763a10d xz-java-1.2.tar.gz c22196148fcace5443a933238216cff5112948df xz-java-1.5.tar.gz 4368ee09154dff42666a8c87e072261745619e51 xz-java-1.6.tar.gz 63f5fa09e92a895cb9aea27d7142abc86c487d25 xz-java-1.8.tar.gz 4530a1aa6f4498ee3d78d6000fa71a3f63bd077f yices-1.0.28.tar.gz 3a8f77822278fe9250890e357248bc678d8fac95 z3-3.2-1.tar.gz 12ae71acde43bd7bed1e005c43034b208c0cba4c z3-3.2.tar.gz d94a716502c8503d63952bcb4d4176fac8b28704 z3-4.0.tar.gz 86e721296c400ada440e4a9ce11b9e845eec9e25 z3-4.3.0.tar.gz a8917c31b31c182edeec0aaa48870844960c8a61 z3-4.3.2pre-1.tar.gz 06b30757ff23aefbc30479785c212685ffd39f4d z3-4.3.2pre.tar.gz 93e7e4bddc6afcf87fe2b6656cfcb1b1acd0a4f8 z3-4.4.0pre-1.tar.gz b1bc411c2083fc01577070b56b94514676f53854 z3-4.4.0pre-2.tar.gz 4c366ab255d2e9343fb635d44d4d55ddd24c76d0 z3-4.4.0pre-3.tar.gz 517ba7b94c1985416c5b411c8ae84456367eb231 z3-4.4.0pre.tar.gz aa20745f0b03e606b1a4149598e0c7572b63c657 z3-4.8.3.tar.gz 9dfeb39c87393af7b6a34118507637aa53aca05e zipperposition-2.0-1.tar.gz b884c60653002a7811e3b652ae0515e825d98667 zipperposition-2.0.tar.gz diff --git a/Admin/components/main b/Admin/components/main --- a/Admin/components/main +++ b/Admin/components/main @@ -1,28 +1,28 @@ #main components for everyday use, without big impact on overall build time bash_process-1.2.3-1 bib2xhtml-20190409 csdp-6.1.1 cvc4-1.8 e-2.5-1 flatlaf-0.46-1 isabelle_fonts-20190717 jdk-15.0.1+9 jedit_build-20201223 jfreechart-1.5.1 jortho-1.0-2 kodkodi-1.5.6 nunchaku-0.5 opam-2.0.7 polyml-test-f86ae3dc1686 postgresql-42.2.18 -scala-2.12.12 +scala-2.13.4 smbc-0.4.1 spass-3.8ds-2 sqlite-jdbc-3.34.0 ssh-java-20190323 stack-2.5.1 vampire-4.2.2 verit-2020.10-rmx-1 xz-java-1.8 z3-4.4.0pre-3 zipperposition-2.0-1 diff --git a/etc/settings b/etc/settings --- a/etc/settings +++ b/etc/settings @@ -1,176 +1,176 @@ # -*- shell-script -*- :mode=shellscript: # # Isabelle system settings. # # Important notes: # * See the "system" manual for explanations on Isabelle settings # * User settings go into $ISABELLE_HOME_USER/etc/settings # * DO NOT EDIT the repository copy of this file! # * DO NOT COPY this file into the $ISABELLE_HOME_USER directory! ### ### Isabelle/Scala ### ISABELLE_JAVA_SYSTEM_OPTIONS="-server -Dfile.encoding=UTF-8 -Disabelle.threads=0" ISABELLE_TOOL_JAVA_OPTIONS="-Djava.awt.headless=true -Xms512m -Xmx4g -Xss16m" -ISABELLE_SCALAC_OPTIONS="-encoding UTF-8 -nowarn -target:jvm-1.8 -Xmax-classfile-name 130 -J-Xms512m -J-Xmx4g -J-Xss16m" +ISABELLE_SCALAC_OPTIONS="-encoding UTF-8 -nowarn -target:jvm-1.8 -J-Xms512m -J-Xmx4g -J-Xss16m" classpath "$ISABELLE_HOME/lib/classes/Pure.jar" isabelle_scala_service 'isabelle.Tools' [ -d "$ISABELLE_HOME/Admin" ] && isabelle_scala_service 'isabelle.Admin_Tools' isabelle_scala_service 'isabelle.Scala_Functions' isabelle_scala_service 'isabelle.Sessions$File_Format' isabelle_scala_service 'isabelle.Bibtex$File_Format' isabelle_scala_service 'isabelle.ML_Statistics$Handler' isabelle_scala_service 'isabelle.Scala$Handler' isabelle_scala_service 'isabelle.Print_Operation$Handler' isabelle_scala_service 'isabelle.Simplifier_Trace$Handler' isabelle_scala_service 'isabelle.Server_Commands' #paranoia settings -- avoid intrusion of alien options unset "_JAVA_OPTIONS" unset "JAVA_TOOL_OPTIONS" #paranoia settings -- avoid problems of Java/Swing versus XIM/IBus etc. unset XMODIFIERS ### ### Interactive sessions (cf. isabelle console) ### ISABELLE_LINE_EDITOR="rlwrap" ### ### Batch sessions (cf. isabelle build) ### ISABELLE_BUILD_OPTIONS="" ### ### Document preparation (cf. isabelle latex/document) ### ISABELLE_PDFLATEX="lualatex --file-line-error" ISABELLE_BIBTEX="bibtex" ISABELLE_MAKEINDEX="makeindex" ISABELLE_EPSTOPDF="epstopdf" ### ### Misc path settings ### isabelle_directory '~' isabelle_directory '$ISABELLE_HOME_USER' isabelle_directory '~~' ISABELLE_COMPONENT_REPOSITORY="https://isabelle.sketis.net/components" ISABELLE_COMPONENTS_BASE="$USER_HOME/.isabelle/contrib" # The place for user configuration, heap files, etc. if [ -z "$ISABELLE_IDENTIFIER" ]; then ISABELLE_HOME_USER="$USER_HOME/.isabelle" else ISABELLE_HOME_USER="$USER_HOME/.isabelle/$ISABELLE_IDENTIFIER" fi # Where to look for isabelle tools (multiple dirs separated by ':'). ISABELLE_TOOLS="$ISABELLE_HOME/lib/Tools" # Location for temporary files (should be on a local file system). ISABELLE_TMP_PREFIX="${TMPDIR:-/tmp}/isabelle-$USER" # Heap locations. ISABELLE_HEAPS="$ISABELLE_HOME_USER/heaps" ISABELLE_HEAPS_SYSTEM="$ISABELLE_HOME/heaps" # HTML browser info. ISABELLE_BROWSER_INFO="$ISABELLE_HOME_USER/browser_info" ISABELLE_BROWSER_INFO_SYSTEM="$ISABELLE_HOME/browser_info" # Site settings check -- just to make it a little bit harder to copy this file verbatim! [ -n "$ISABELLE_SITE_SETTINGS_PRESENT" ] && \ { echo >&2 "### Isabelle site settings already present! Maybe copied etc/settings in full?"; } ISABELLE_SITE_SETTINGS_PRESENT=true ### ### Default logic ### ISABELLE_LOGIC=HOL ### ### Docs ### # Where to look for docs (multiple dirs separated by ':'). ISABELLE_DOCS="$ISABELLE_HOME/doc" ISABELLE_DOCS_RELEASE_NOTES="~~/ANNOUNCE:~~/README:~~/NEWS:~~/COPYRIGHT:~~/CONTRIBUTORS:~~/contrib/README:~~/src/Tools/jEdit/README:~~/README_REPOSITORY" ISABELLE_DOCS_EXAMPLES="~~/src/HOL/Examples/Seq.thy:~~/src/HOL/Examples/Drinker.thy:~~/src/HOL/Examples/ML.thy:~~/src/HOL/Unix/Unix.thy:~~/src/Tools/SML/Examples.thy:~~/src/Pure/ROOT.ML" # "open" within desktop environment (potentially asynchronous) case "$ISABELLE_PLATFORM_FAMILY" in linux) ISABELLE_OPEN="xdg-open" ;; macos) ISABELLE_OPEN="open" ;; windows) ISABELLE_OPEN="cygstart" ;; esac PDF_VIEWER="$ISABELLE_OPEN" ### ### Symbol rendering ### ISABELLE_SYMBOLS="$ISABELLE_HOME/etc/symbols:$ISABELLE_HOME_USER/etc/symbols" ### ### OCaml ### ISABELLE_OPAM_ROOT="$USER_HOME/.opam" ISABELLE_OCAML_VERSION="ocaml-base-compiler.4.07.0" ### ### Haskell ### ISABELLE_STACK_ROOT="$USER_HOME/.stack" ISABELLE_STACK_RESOLVER="lts-16.12" ISABELLE_GHC_VERSION="ghc-8.8.4" ### ### Misc settings ### ISABELLE_GNUPLOT="gnuplot" ISABELLE_FONTFORGE="fontforge" #ISABELLE_MLTON="/usr/bin/mlton" #ISABELLE_SMLNJ="/usr/bin/sml" #ISABELLE_SWIPL="/usr/bin/swipl" diff --git a/src/Doc/JEdit/JEdit.thy b/src/Doc/JEdit/JEdit.thy --- a/src/Doc/JEdit/JEdit.thy +++ b/src/Doc/JEdit/JEdit.thy @@ -1,2276 +1,2276 @@ (*:maxLineLen=78:*) theory JEdit imports Base begin chapter \Introduction\ section \Concepts and terminology\ text \ Isabelle/jEdit is a Prover IDE that integrates \<^emph>\parallel proof checking\ @{cite "Wenzel:2009" and "Wenzel:2013:ITP"} with \<^emph>\asynchronous user interaction\ @{cite "Wenzel:2010" and "Wenzel:2012:UITP-EPTCS" and "Wenzel:2014:ITP-PIDE" and "Wenzel:2014:UITP"}, based on a document-oriented approach to \<^emph>\continuous proof processing\ @{cite "Wenzel:2011:CICM" and "Wenzel:2012" and "Wenzel:2018:FIDE" and "Wenzel:2019:MKM"}. Many concepts and system components are fit together in order to make this work. The main building blocks are as follows. \<^descr>[Isabelle/ML] is the implementation and extension language of Isabelle, see also @{cite "isabelle-implementation"}. It is integrated into the logical context of Isabelle/Isar and allows to manipulate logical entities directly. Arbitrary add-on tools may be implemented for object-logics such as Isabelle/HOL. \<^descr>[Isabelle/Scala] is the system programming language of Isabelle. It extends the pure logical environment of Isabelle/ML towards the outer world of graphical user interfaces, text editors, IDE frameworks, web services, SSH servers, SQL databases etc. Special infrastructure allows to transfer algebraic datatypes and formatted text easily between ML and Scala, using asynchronous protocol commands. \<^descr>[PIDE] is a general framework for Prover IDEs based on Isabelle/Scala. It is built around a concept of parallel and asynchronous document processing, which is supported natively by the parallel proof engine that is implemented in Isabelle/ML. The traditional prover command loop is given up; instead there is direct support for editing of source text, with rich formal markup for GUI rendering. \<^descr>[jEdit] is a sophisticated text editor\<^footnote>\\<^url>\http://www.jedit.org\\ implemented in Java\<^footnote>\\<^url>\https://adoptopenjdk.net\\. It is easily extensible by plugins written in any language that works on the JVM. In the context of Isabelle this is always Scala\<^footnote>\\<^url>\https://www.scala-lang.org\\. \<^descr>[Isabelle/jEdit] is the main application of the PIDE framework and the default user-interface for Isabelle. It targets both beginners and experts. Technically, Isabelle/jEdit consists of the original jEdit code base with minimal patches and a special plugin for Isabelle. This is integrated as a desktop application for the main operating system families: Linux, Windows, macOS. End-users of Isabelle download and run a standalone application that exposes jEdit as a text editor on the surface. Thus there is occasionally a tendency to apply the name ``jEdit'' to any of the Isabelle Prover IDE aspects, without proper differentiation. When discussing these PIDE building blocks in public forums, mailing lists, or even scientific publications, it is particularly important to distinguish Isabelle/ML versus Standard ML, Isabelle/Scala versus Scala, Isabelle/jEdit versus jEdit. \ section \The Isabelle/jEdit Prover IDE\ text \ \begin{figure}[!htb] \begin{center} \includegraphics[width=\textwidth]{isabelle-jedit} \end{center} \caption{The Isabelle/jEdit Prover IDE} \label{fig:isabelle-jedit} \end{figure} Isabelle/jEdit (\figref{fig:isabelle-jedit}) consists of some plugins for the jEdit text editor, while preserving its general look-and-feel as far as possible. The main plugin is called ``Isabelle'' and has its own menu \<^emph>\Plugins~/ Isabelle\ with access to several actions and add-on panels (see also \secref{sec:dockables}), as well as \<^emph>\Plugins~/ Plugin Options~/ Isabelle\ (see also \secref{sec:options}). The options allow to specify a logic session name, but the same selector is also accessible in the \<^emph>\Theories\ panel (\secref{sec:theories}). After startup of the Isabelle plugin, the selected logic session image is provided automatically by the Isabelle build tool @{cite "isabelle-system"}: if it is absent or outdated wrt.\ its sources, the build process updates it within the running text editor. Prover IDE functionality is fully activated after successful termination of the build process. A failure may require changing some options and restart of the Isabelle plugin or application. Changing the logic session requires a restart of the whole application to take effect. \<^medskip> The main job of the Prover IDE is to manage sources and their changes, taking the logical structure as a formal document into account (see also \secref{sec:document-model}). The editor and the prover are connected asynchronously without locking. The prover is free to organize the checking of the formal text in parallel on multiple cores, and provides feedback via markup, which is rendered in the editor via colors, boxes, squiggly underlines, hyperlinks, popup windows, icons, clickable output etc. Using the mouse together with the modifier key \<^verbatim>\CONTROL\ (Linux, Windows) or \<^verbatim>\COMMAND\ (macOS) exposes formal content via tooltips and/or hyperlinks (see also \secref{sec:tooltips-hyperlinks}). Output (in popups etc.) may be explored recursively, using the same techniques as in the editor source buffer. Thus the Prover IDE gives an impression of direct access to formal content of the prover within the editor, but in reality only certain aspects are exposed, according to the possibilities of the prover and its add-on tools. \ subsection \Documentation\ text \ The \<^emph>\Documentation\ panel of Isabelle/jEdit provides access to some example theory files and the standard Isabelle documentation. PDF files are opened by regular desktop operations of the underlying platform. The section ``Original jEdit Documentation'' contains the original \<^emph>\User's Guide\ of this sophisticated text editor. The same is accessible via the \<^verbatim>\Help\ menu or \<^verbatim>\F1\ keyboard shortcut, using the built-in HTML viewer of Java/Swing. The latter also includes \<^emph>\Frequently Asked Questions\ and documentation of individual plugins. Most of the information about jEdit is relevant for Isabelle/jEdit as well, but users need to keep in mind that defaults sometimes differ, and the official jEdit documentation does not know about the Isabelle plugin with its support for continuous checking of formal source text: jEdit is a plain text editor, but Isabelle/jEdit is a Prover IDE. \ subsection \Plugins\ text \ The \<^emph>\Plugin Manager\ of jEdit allows to augment editor functionality by JVM modules (jars) that are provided by the central plugin repository, which is accessible via various mirror sites. Connecting to the plugin server-infrastructure of the jEdit project allows to update bundled plugins or to add further functionality. This needs to be done with the usual care for such an open bazaar of contributions. Arbitrary combinations of add-on features are apt to cause problems. It is advisable to start with the default configuration of Isabelle/jEdit and develop a sense how it is meant to work, before loading too many other plugins. \<^medskip> The \<^emph>\Isabelle\ plugin is responsible for the main Prover IDE functionality of Isabelle/jEdit: it manages the prover session in the background. A few additional plugins are bundled with Isabelle/jEdit for convenience or out of necessity, notably \<^emph>\Console\ with its \<^emph>\Scala\ sub-plugin (\secref{sec:scala-console}) and \<^emph>\SideKick\ with some Isabelle-specific parsers for document tree structure (\secref{sec:sidekick}). The \<^emph>\Navigator\ plugin is particularly important for hyperlinks within the formal document-model (\secref{sec:tooltips-hyperlinks}). Further plugins (e.g.\ \<^emph>\ErrorList\, \<^emph>\Code2HTML\) are included to saturate the dependencies of bundled plugins, but have no particular use in Isabelle/jEdit. \ subsection \Options \label{sec:options}\ text \ Both jEdit and Isabelle have distinctive management of persistent options. Regular jEdit options are accessible via the dialogs \<^emph>\Utilities~/ Global Options\ or \<^emph>\Plugins~/ Plugin Options\, with a second chance to flip the two within the central options dialog. Changes are stored in \<^path>\$JEDIT_SETTINGS/properties\ and \<^path>\$JEDIT_SETTINGS/keymaps\. Isabelle system options are managed by Isabelle/Scala and changes are stored in \<^path>\$ISABELLE_HOME_USER/etc/preferences\, independently of other jEdit properties. See also @{cite "isabelle-system"}, especially the coverage of sessions and command-line tools like @{tool build} or @{tool options}. Those Isabelle options that are declared as \<^verbatim>\public\ are configurable in Isabelle/jEdit via \<^emph>\Plugin Options~/ Isabelle~/ General\. Moreover, there are various options for rendering document content, which are configurable via \<^emph>\Plugin Options~/ Isabelle~/ Rendering\. Thus \<^emph>\Plugin Options~/ Isabelle\ in jEdit provides a view on a subset of Isabelle system options. Note that some of these options affect general parameters that are relevant outside Isabelle/jEdit as well, e.g.\ @{system_option threads} or @{system_option parallel_proofs} for the Isabelle build tool @{cite "isabelle-system"}, but it is possible to use the settings variable @{setting ISABELLE_BUILD_OPTIONS} to change defaults for batch builds without affecting the Prover IDE. The jEdit action @{action_def isabelle.options} opens the options dialog for the Isabelle plugin; it can be mapped to editor GUI elements as usual. \<^medskip> Options are usually loaded on startup and saved on shutdown of Isabelle/jEdit. Editing the generated \<^path>\$JEDIT_SETTINGS/properties\ or \<^path>\$ISABELLE_HOME_USER/etc/preferences\ manually while the application is running may cause lost updates! \ subsection \Keymaps\ text \ Keyboard shortcuts are managed as a separate concept of \<^emph>\keymap\ that is configurable via \<^emph>\Global Options~/ Shortcuts\. The \<^verbatim>\imported\ keymap is derived from the initial environment of properties that is available at the first start of the editor; afterwards the keymap file takes precedence and is no longer affected by change of default properties. Users may modify their keymap later, but this can lead to conflicts with \<^verbatim>\shortcut\ properties in \<^file>\$JEDIT_HOME/src/jEdit.props\. The action @{action_def "isabelle.keymap-merge"} helps to resolve pending Isabelle keymap changes wrt. the current jEdit keymap; non-conflicting changes are applied implicitly. This action is automatically invoked on Isabelle/jEdit startup. \ section \Command-line invocation \label{sec:command-line}\ text \ Isabelle/jEdit is normally invoked as a single-instance desktop application, based on platform-specific executables for Linux, Windows, macOS. It is also possible to invoke the Prover IDE on the command-line, with some extra options and environment settings. The command-line usage of @{tool_def jedit} is as follows: @{verbatim [display] \Usage: isabelle jedit [OPTIONS] [FILES ...] Options are: -A NAME ancestor session for option -R (default: parent) -D NAME=X set JVM system property -J OPTION add JVM runtime option (default $JEDIT_JAVA_SYSTEM_OPTIONS $JEDIT_JAVA_OPTIONS) -R NAME build image with requirements from other sessions -b build only -d DIR include session directory -f fresh build -i NAME include session in name-space of theories -j OPTION add jEdit runtime option (default $JEDIT_OPTIONS) -l NAME logic image name -m MODE add print mode for output -n no build of session image on startup -p CMD ML process command prefix (process policy) -s system build mode for session image (system_heaps=true) -u user build mode for session image (system_heaps=false) Start jEdit with Isabelle plugin setup and open FILES (default "$USER_HOME/Scratch.thy" or ":" for empty buffer).\} The \<^verbatim>\-l\ option specifies the session name of the logic image to be used for proof processing. Additional session root directories may be included via option \<^verbatim>\-d\ to augment the session name space (see also @{cite "isabelle-system"}). By default, the specified image is checked and built on demand, but option \<^verbatim>\-n\ bypasses the implicit build process for the selected session image. Options \<^verbatim>\-s\ and \<^verbatim>\-u\ override the default system option @{system_option system_heaps}: this determines where to store the session image of @{tool build}. The \<^verbatim>\-R\ option builds an auxiliary logic image with all theories from other sessions that are not already present in its parent; it also opens the session \<^verbatim>\ROOT\ entry in the editor to facilitate editing of the main session. The \<^verbatim>\-A\ option specifies and alternative ancestor session for option \<^verbatim>\-R\: this allows to restructure the hierarchy of session images on the spot. The \<^verbatim>\-i\ option includes additional sessions into the name-space of theories: multiple occurrences are possible. The \<^verbatim>\-m\ option specifies additional print modes for the prover process. Note that the system option @{system_option_ref jedit_print_mode} allows to do the same persistently (e.g.\ via the \<^emph>\Plugin Options\ dialog of Isabelle/jEdit), without requiring command-line invocation. The \<^verbatim>\-J\ and \<^verbatim>\-j\ options pass additional low-level options to the JVM or jEdit, respectively. The defaults are provided by the Isabelle settings environment @{cite "isabelle-system"}, but note that these only work for the command-line tool described here, and not the desktop application. The \<^verbatim>\-D\ option allows to define JVM system properties; this is passed directly to the underlying \<^verbatim>\java\ process. The \<^verbatim>\-b\ and \<^verbatim>\-f\ options control the self-build mechanism of Isabelle/jEdit. This is only relevant for building from sources, which also requires an auxiliary \<^verbatim>\jedit_build\ component from \<^url>\https://isabelle.in.tum.de/components\. The official Isabelle release already includes a pre-built version of Isabelle/jEdit. \<^bigskip> It is also possible to connect to an already running Isabelle/jEdit process via @{tool_def jedit_client}: @{verbatim [display] \Usage: isabelle jedit_client [OPTIONS] [FILES ...] Options are: -c only check presence of server -n only report server name - -s NAME server name (default Isabelle) + -s NAME server name (default "Isabelle") Connect to already running Isabelle/jEdit instance and open FILES\} The \<^verbatim>\-c\ option merely checks the presence of the server, producing a process return-code. The \<^verbatim>\-n\ option reports the server name, and the \<^verbatim>\-s\ option provides a different server name. The default server name is the official distribution name (e.g.\ \<^verbatim>\Isabelle2020\). Thus @{tool jedit_client} can connect to the Isabelle desktop application without further options. The \<^verbatim>\-p\ option allows to override the implicit default of the system option @{system_option_ref ML_process_policy} for ML processes started by the Prover IDE, e.g. to control CPU affinity on multiprocessor systems. The JVM system property \<^verbatim>\isabelle.jedit_server\ provides a different server name, e.g.\ use \<^verbatim>\isabelle jedit -Disabelle.jedit_server=\\name\ and \<^verbatim>\isabelle jedit_client -s\~\name\ to connect later on. \ section \GUI rendering\ subsection \Look-and-feel \label{sec:look-and-feel}\ text \ jEdit is a Java/AWT/Swing application with the ambition to support ``native'' look-and-feel on all platforms, within the limits of what Java provider and major operating systems allow (see also \secref{sec:problems}). Isabelle/jEdit enables platform-specific look-and-feel by default as follows. \<^descr>[Linux:] The platform-independent \<^emph>\Metal\ is used by default. The Linux-specific \<^emph>\GTK+\ look-and-feel often works, but the overall GTK theme and options need to be selected to suite Java/AWT/Swing. Note that the Java Virtual Machine has no direct influence of GTK rendering: it happens within external C libraries. \<^descr>[Windows:] Regular \<^emph>\Windows\ look-and-feel is used by default. \<^descr>[macOS:] Regular \<^emph>\Mac OS X\ look-and-feel is used by default. Users may experiment with different Swing look-and-feels, but need to keep in mind that this extra variance of GUI functionality often causes problems. The platform-independent \<^emph>\Metal\ look-and-feel should work smoothly on all platforms, although its is technically and stylistically outdated. Changing the look-and-feel in \<^emph>\Global Options~/ Appearance\ may update the GUI only partially: a proper restart of Isabelle/jEdit is usually required. \ subsection \Displays with high resolution \label{sec:hdpi}\ text \ In 2020, we usually see displays with high resolution like ``Ultra HD'' / ``4K'' at $3840 \times 2160$, or more. Old ``Full HD'' displays at $1920 \times 1080$ pixels are still being used, but Java 11 font-rendering might look bad on it. GUI layouts are lagging behind the high resolution trends, and implicitly assume very old-fashioned $1024 \times 768$ or $1280 \times 1024$ screens and fonts with 12 or 14 pixels. Java and jEdit do provide reasonable support for high resolution, but this requires manual adjustments as described below. \<^medskip> The \<^bold>\operating-system\ often provides some configuration for global scaling of text fonts, e.g.\ to enlarge it uniformly by $200\%$. This impacts regular GUI elements, when used with native look-and-feel: Linux \<^emph>\GTK+\, \<^emph>\Windows\, \<^emph>\Mac OS X\, respectively. Alternatively, it is possible to use the platform-independent \<^emph>\Metal\ look-and-feel and change its main font sizes via jEdit options explained below. The Isabelle/jEdit \<^bold>\application\ provides further options to adjust font sizes in particular GUI elements. Here is a summary of all relevant font properties: \<^item> \<^emph>\Global Options / Text Area / Text font\: the main text area font, which is also used as reference point for various derived font sizes, e.g.\ the \<^emph>\Output\ (\secref{sec:output}) and \<^emph>\State\ (\secref{sec:state-output}) panels. \<^item> \<^emph>\Global Options / Gutter / Gutter font\: the font for the gutter area left of the main text area, e.g.\ relevant for display of line numbers (disabled by default). \<^item> \<^emph>\Global Options / Appearance / Button, menu and label font\ as well as \<^emph>\List and text field font\: this specifies the primary and secondary font for the \<^emph>\Metal\ look-and-feel (\secref{sec:look-and-feel}). \<^item> \<^emph>\Plugin Options / Isabelle / General / Reset Font Size\: the main text area font size for action @{action_ref "isabelle.reset-font-size"}, e.g.\ relevant for quick scaling like in common web browsers. \<^item> \<^emph>\Plugin Options / Console / General / Font\: the console window font, e.g.\ relevant for Isabelle/Scala command-line. In \figref{fig:isabelle-jedit-hdpi} the \<^emph>\Metal\ look-and-feel is configured with custom fonts at 36 pixels, and the main text area and console at 40 pixels. This leads to fairly good rendering quality, despite the old-fashioned appearance of \<^emph>\Metal\. \begin{sidewaysfigure}[!htb] \begin{center} \includegraphics[width=\textwidth]{isabelle-jedit-hdpi} \end{center} \caption{Metal look-and-feel with custom fonts for high resolution} \label{fig:isabelle-jedit-hdpi} \end{sidewaysfigure} \ chapter \Augmented jEdit functionality\ section \Dockable windows \label{sec:dockables}\ text \ In jEdit terminology, a \<^emph>\view\ is an editor window with one or more \<^emph>\text areas\ that show the content of one or more \<^emph>\buffers\. A regular view may be surrounded by \<^emph>\dockable windows\ that show additional information in arbitrary format, not just text; a \<^emph>\plain view\ does not allow dockables. The \<^emph>\dockable window manager\ of jEdit organizes these dockable windows, either as \<^emph>\floating\ windows, or \<^emph>\docked\ panels within one of the four margins of the view. There may be any number of floating instances of some dockable window, but at most one docked instance; jEdit actions that address \<^emph>\the\ dockable window of a particular kind refer to the unique docked instance. Dockables are used routinely in jEdit for important functionality like \<^emph>\HyperSearch Results\ or the \<^emph>\File System Browser\. Plugins often provide a central dockable to access their main functionality, which may be opened by the user on demand. The Isabelle/jEdit plugin takes this approach to the extreme: its plugin menu provides the entry-points to many panels that are managed as dockable windows. Some important panels are docked by default, e.g.\ \<^emph>\Documentation\, \<^emph>\State\, \<^emph>\Theories\ \<^emph>\Output\, \<^emph>\Query\. The user can change this arrangement easily and persistently. Compared to plain jEdit, dockable window management in Isabelle/jEdit is slightly augmented according to the the following principles: \<^item> Floating windows are dependent on the main window as \<^emph>\dialog\ in the sense of Java/AWT/Swing. Dialog windows always stay on top of the view, which is particularly important in full-screen mode. The desktop environment of the underlying platform may impose further policies on such dependent dialogs, in contrast to fully independent windows, e.g.\ some window management functions may be missing. \<^item> Keyboard focus of the main view vs.\ a dockable window is carefully managed according to the intended semantics, as a panel mainly for output or input. For example, activating the \<^emph>\Output\ (\secref{sec:output}) or State (\secref{sec:state-output}) panel via the dockable window manager returns keyboard focus to the main text area, but for \<^emph>\Query\ (\secref{sec:query}) or \<^emph>\Sledgehammer\ \secref{sec:sledgehammer} the focus is given to the main input field of that panel. \<^item> Panels that provide their own text area for output have an additional dockable menu item \<^emph>\Detach\. This produces an independent copy of the current output as a floating \<^emph>\Info\ window, which displays that content independently of ongoing changes of the PIDE document-model. Note that Isabelle/jEdit popup windows (\secref{sec:tooltips-hyperlinks}) provide a similar \<^emph>\Detach\ operation as an icon. \ section \Isabelle symbols \label{sec:symbols}\ text \ Isabelle sources consist of \<^emph>\symbols\ that extend plain ASCII to allow infinitely many mathematical symbols within the formal sources. This works without depending on particular encodings and varying Unicode standards.\<^footnote>\Raw Unicode characters within formal sources compromise portability and reliability in the face of changing interpretation of special features of Unicode, such as Combining Characters or Bi-directional Text.\ See @{cite "Wenzel:2011:CICM"}. For the prover back-end, formal text consists of ASCII characters that are grouped according to some simple rules, e.g.\ as plain ``\<^verbatim>\a\'' or symbolic ``\<^verbatim>\\\''. For the editor front-end, a certain subset of symbols is rendered physically via Unicode glyphs, to show ``\<^verbatim>\\\'' as ``\\\'', for example. This symbol interpretation is specified by the Isabelle system distribution in \<^file>\$ISABELLE_HOME/etc/symbols\ and may be augmented by the user in \<^path>\$ISABELLE_HOME_USER/etc/symbols\. The appendix of @{cite "isabelle-isar-ref"} gives an overview of the standard interpretation of finitely many symbols from the infinite collection. Uninterpreted symbols are displayed literally, e.g.\ ``\<^verbatim>\\\''. Overlap of Unicode characters used in symbol interpretation with informal ones (which might appear e.g.\ in comments) needs to be avoided. Raw Unicode characters within prover source files should be restricted to informal parts, e.g.\ to write text in non-latin alphabets in comments. \ paragraph \Encoding.\ text \Technically, the Unicode interpretation of Isabelle symbols is an \<^emph>\encoding\ called \<^verbatim>\UTF-8-Isabelle\ in jEdit (\<^emph>\not\ in the underlying JVM). It is provided by the Isabelle Base plugin and enabled by default for all source files in Isabelle/jEdit. Sometimes such defaults are reset accidentally, or malformed UTF-8 sequences in the text force jEdit to fall back on a different encoding like \<^verbatim>\ISO-8859-15\. In that case, verbatim ``\<^verbatim>\\\'' will be shown in the text buffer instead of its Unicode rendering ``\\\''. The jEdit menu operation \<^emph>\File~/ Reload with Encoding~/ UTF-8-Isabelle\ helps to resolve such problems (after repairing malformed parts of the text). If the loaded text already contains Unicode sequences that are in conflict with the Isabelle symbol encoding, the fallback-encoding UTF-8 is used and Isabelle symbols remain in literal \<^verbatim>\\\ form. The jEdit menu operation \<^emph>\Utilities~/ Buffer Options~/ Character encoding\ allows to enforce \<^verbatim>\UTF-8-Isabelle\, but this will also change original Unicode text into Isabelle symbols when saving the file! \ paragraph \Font.\ text \Correct rendering via Unicode requires a font that contains glyphs for the corresponding codepoints. There are also various unusual symbols with particular purpose in Isabelle, e.g.\ control symbols and very long arrows. Isabelle/jEdit prefers its own font collection \<^verbatim>\Isabelle DejaVu\, with families \<^verbatim>\Serif\ (default for help texts), \<^verbatim>\Sans\ (default for GUI elements), \<^verbatim>\Mono Sans\ (default for text area). This ensures that all standard Isabelle symbols are shown on the screen (or printer) as expected. Note that a Java/AWT/Swing application can load additional fonts only if they are not installed on the operating system already! Outdated versions of Isabelle fonts that happen to be provided by the operating system prevent Isabelle/jEdit to use its bundled version. This could lead to missing glyphs (black rectangles), when the system version of a font is older than the application version. This problem can be avoided by refraining to ``install'' a copy of the Isabelle fonts in the first place, although it might be tempting to use the same font in other applications. HTML pages generated by Isabelle refer to the same Isabelle fonts as a server-side resource. Thus a web-browser can use that without requiring a locally installed copy. \ paragraph \Input methods.\ text \In principle, Isabelle/jEdit could delegate the problem to produce Isabelle symbols in their Unicode rendering to the underlying operating system and its \<^emph>\input methods\. Regular jEdit also provides various ways to work with \<^emph>\abbreviations\ to produce certain non-ASCII characters. Since none of these standard input methods work satisfactorily for the mathematical characters required for Isabelle, various specific Isabelle/jEdit mechanisms are provided. This is a summary for practically relevant input methods for Isabelle symbols. \<^enum> The \<^emph>\Symbols\ panel: some GUI buttons allow to insert certain symbols in the text buffer. There are also tooltips to reveal the official Isabelle representation with some additional information about \<^emph>\symbol abbreviations\ (see below). \<^enum> Copy/paste from decoded source files: text that is already rendered as Unicode can be re-used for other text. This also works between different applications, e.g.\ Isabelle/jEdit and some web browser or mail client, as long as the same Unicode interpretation of Isabelle symbols is used. \<^enum> Copy/paste from prover output within Isabelle/jEdit. The same principles as for text buffers apply, but note that \<^emph>\copy\ in secondary Isabelle/jEdit windows works via the keyboard shortcuts \<^verbatim>\C+c\ or \<^verbatim>\C+INSERT\, while jEdit menu actions always refer to the primary text area! \<^enum> Completion provided by the Isabelle plugin (see \secref{sec:completion}). Isabelle symbols have a canonical name and optional abbreviations. This can be used with the text completion mechanism of Isabelle/jEdit, to replace a prefix of the actual symbol like \<^verbatim>\\\, or its name preceded by backslash \<^verbatim>\\lambda\, or its ASCII abbreviation \<^verbatim>\%\ by the Unicode rendering. The following table is an extract of the information provided by the standard \<^file>\$ISABELLE_HOME/etc/symbols\ file: \<^medskip> \begin{tabular}{lll} \<^bold>\symbol\ & \<^bold>\name with backslash\ & \<^bold>\abbreviation\ \\\hline \\\ & \<^verbatim>\\lambda\ & \<^verbatim>\%\ \\ \\\ & \<^verbatim>\\Rightarrow\ & \<^verbatim>\=>\ \\ \\\ & \<^verbatim>\\Longrightarrow\ & \<^verbatim>\==>\ \\[0.5ex] \\\ & \<^verbatim>\\And\ & \<^verbatim>\!!\ \\ \\\ & \<^verbatim>\\equiv\ & \<^verbatim>\==\ \\[0.5ex] \\\ & \<^verbatim>\\forall\ & \<^verbatim>\!\ \\ \\\ & \<^verbatim>\\exists\ & \<^verbatim>\?\ \\ \\\ & \<^verbatim>\\longrightarrow\ & \<^verbatim>\-->\ \\ \\\ & \<^verbatim>\\and\ & \<^verbatim>\&\ \\ \\\ & \<^verbatim>\\or\ & \<^verbatim>\|\ \\ \\\ & \<^verbatim>\\not\ & \<^verbatim>\~\ \\ \\\ & \<^verbatim>\\noteq\ & \<^verbatim>\~=\ \\ \\\ & \<^verbatim>\\in\ & \<^verbatim>\:\ \\ \\\ & \<^verbatim>\\notin\ & \<^verbatim>\~:\ \\ \end{tabular} \<^medskip> Note that the above abbreviations refer to the input method. The logical notation provides ASCII alternatives that often coincide, but sometimes deviate. This occasionally causes user confusion with old-fashioned Isabelle source that use ASCII replacement notation like \<^verbatim>\!\ or \<^verbatim>\ALL\ directly in the text. On the other hand, coincidence of symbol abbreviations with ASCII replacement syntax syntax helps to update old theory sources via explicit completion (see also \<^verbatim>\C+b\ explained in \secref{sec:completion}). \ paragraph \Control symbols.\ text \There are some special control symbols to modify the display style of a single symbol (without nesting). Control symbols may be applied to a region of selected text, either using the \<^emph>\Symbols\ panel or keyboard shortcuts or jEdit actions. These editor operations produce a separate control symbol for each symbol in the text, in order to make the whole text appear in a certain style. \<^medskip> \begin{tabular}{llll} \<^bold>\style\ & \<^bold>\symbol\ & \<^bold>\shortcut\ & \<^bold>\action\ \\\hline superscript & \<^verbatim>\\<^sup>\ & \<^verbatim>\C+e UP\ & @{action_ref "isabelle.control-sup"} \\ subscript & \<^verbatim>\\<^sub>\ & \<^verbatim>\C+e DOWN\ & @{action_ref "isabelle.control-sub"} \\ bold face & \<^verbatim>\\<^bold>\ & \<^verbatim>\C+e RIGHT\ & @{action_ref "isabelle.control-bold"} \\ emphasized & \<^verbatim>\\<^emph>\ & \<^verbatim>\C+e LEFT\ & @{action_ref "isabelle.control-emph"} \\ reset & & \<^verbatim>\C+e BACK_SPACE\ & @{action_ref "isabelle.control-reset"} \\ \end{tabular} \<^medskip> To produce a single control symbol, it is also possible to complete on \<^verbatim>\\sup\, \<^verbatim>\\sub\, \<^verbatim>\\bold\, \<^verbatim>\\emph\ as for regular symbols. The emphasized style only takes effect in document output (when used with a cartouche), but not in the editor. \ section \Scala console \label{sec:scala-console}\ text \ The \<^emph>\Console\ plugin manages various shells (command interpreters), e.g.\ \<^emph>\BeanShell\, which is the official jEdit scripting language, and the cross-platform \<^emph>\System\ shell. Thus the console provides similar functionality than the Emacs buffers \<^verbatim>\*scratch*\ and \<^verbatim>\*shell*\. Isabelle/jEdit extends the repertoire of the console by \<^emph>\Scala\, which is the regular Scala toplevel loop running inside the same JVM process as Isabelle/jEdit itself. This means the Scala command interpreter has access to the JVM name space and state of the running Prover IDE application. The default environment imports the full content of packages \<^verbatim>\isabelle\ and \<^verbatim>\isabelle.jedit\. For example, \<^verbatim>\PIDE\ refers to the Isabelle/jEdit plugin object, and \<^verbatim>\view\ to the current editor view of jEdit. The Scala expression \<^verbatim>\PIDE.snapshot(view)\ makes a PIDE document snapshot of the current buffer within the current editor view: it allows to retrieve document markup in a timeless~/ stateless manner, while the prover continues its processing. This helps to explore Isabelle/Scala functionality interactively. Some care is required to avoid interference with the internals of the running application. \ section \Physical and logical files \label{sec:files}\ text \ File specifications in jEdit follow various formats and conventions according to \<^emph>\Virtual File Systems\, which may be also provided by plugins. This allows to access remote files via the \<^verbatim>\https:\ protocol prefix, for example. Isabelle/jEdit attempts to work with the file-system model of jEdit as far as possible. In particular, theory sources are passed from the editor to the prover, without indirection via the file-system. Thus files don't need to be saved: the editor buffer content is used directly. \ subsection \Local files and environment variables \label{sec:local-files}\ text \ Local files (without URL notation) are particularly important. The file path notation is that of the Java Virtual Machine on the underlying platform. On Windows the preferred form uses backslashes, but happens to accept forward slashes like Unix/POSIX as well. Further differences arise due to Windows drive letters and network shares: thus relative paths (with forward slashes) are portable, but absolute paths are not. File paths in Java are distinct from Isabelle; the latter uses POSIX notation with forward slashes on \<^emph>\all\ platforms. Isabelle/ML on Windows uses Unix-style path notation, with drive letters according to Cygwin (e.g.\ \<^verbatim>\/cygdrive/c\). Environment variables from the Isabelle process may be used freely, e.g.\ \<^file>\$ISABELLE_HOME/etc/symbols\ or \<^file>\$POLYML_HOME/README\. There are special shortcuts: \<^dir>\~\ for \<^dir>\$USER_HOME\ and \<^dir>\~~\ for \<^dir>\$ISABELLE_HOME\. \<^medskip> Since jEdit happens to support environment variables within file specifications as well, it is natural to use similar notation within the editor, e.g.\ in the file-browser. This does not work in full generality, though, due to the bias of jEdit towards platform-specific notation and of Isabelle towards POSIX. Moreover, the Isabelle settings environment is not accessible when starting Isabelle/jEdit via the desktop application wrapper, in contrast to @{tool jedit} run from the command line (\secref{sec:command-line}). Isabelle/jEdit imitates important system settings within the Java process environment, in order to allow easy access to these important places from the editor: \<^verbatim>\$ISABELLE_HOME\, \<^verbatim>\$ISABELLE_HOME_USER\, \<^verbatim>\$JEDIT_HOME\, \<^verbatim>\$JEDIT_SETTINGS\. The file browser of jEdit also includes \<^emph>\Favorites\ for these locations. \<^medskip> Path specifications in prover input or output usually include formal markup that turns it into a hyperlink (see also \secref{sec:tooltips-hyperlinks}). This allows to open the corresponding file in the text editor, independently of the path notation. If the path refers to a directory, it is opened in the jEdit file browser. Formally checked paths in prover input are subject to completion (\secref{sec:completion}): partial specifications are resolved via directory content and possible completions are offered in a popup. \ subsection \PIDE resources via virtual file-systems\ text \ The jEdit file browser is docked by default, e.g. see \figref{fig:isabelle-jedit-hdpi} (left docking area). It provides immediate access to the local file-system, as well as important Isabelle resources via the \<^emph>\Favorites\ menu. Environment variables like \<^verbatim>\$ISABELLE_HOME\ are discussed in \secref{sec:local-files}. Virtual file-systems are more special: the idea is to present structured information like a directory tree. The following URLs are offered in the \<^emph>\Favorites\ menu, or by corresponding jEdit actions. \<^item> URL \<^verbatim>\isabelle-export:\ or action @{action_def "isabelle-export-browser"} shows a toplevel directory with theory names: each may provide its own tree structure of session exports. Exports are like a logical file-system for the current prover session, maintained as Isabelle/Scala data structures and written to the session database eventually. The \<^verbatim>\isabelle-export:\ URL exposes the current content according to a snapshot of the document model. The file browser is \<^emph>\not\ updated continuously when the PIDE document changes: the reload operation needs to be used explicitly. A notable example for exports is the command @{command_ref export_code} @{cite "isabelle-isar-ref"}. \<^item> URL \<^verbatim>\isabelle-session:\ or action @{action_def "isabelle-session-browser"} show the structure of session chapters and sessions within them. What looks like a file-entry is actually a reference to the session definition in its corresponding \<^verbatim>\ROOT\ file. The latter is subject to Prover IDE markup, so the session theories and other files may be browsed quickly by following hyperlinks in the text. \ section \Indentation\ text \ Isabelle/jEdit augments the existing indentation facilities of jEdit to take the structure of theory and proof texts into account. There is also special support for unstructured proof scripts (\<^theory_text>\apply\ etc.). \<^descr>[Syntactic indentation] follows the outer syntax of Isabelle/Isar. Action @{action "indent-lines"} (shortcut \<^verbatim>\C+i\) indents the current line according to command keywords and some command substructure: this approximation may need further manual tuning. Action @{action "isabelle.newline"} (shortcut \<^verbatim>\ENTER\) indents the old and the new line according to command keywords only: leading to precise alignment of the main Isar language elements. This depends on option @{system_option_def "jedit_indent_newline"} (enabled by default). Regular input (via keyboard or completion) indents the current line whenever an new keyword is emerging at the start of the line. This depends on option @{system_option_def "jedit_indent_input"} (enabled by default). \<^descr>[Semantic indentation] adds additional white space to unstructured proof scripts via the number of subgoals. This requires information of ongoing document processing and may thus lag behind when the user is editing too quickly; see also option @{system_option_def "jedit_script_indent"} and @{system_option_def "jedit_script_indent_limit"}. The above options are accessible in the menu \<^emph>\Plugins / Plugin Options / Isabelle / General\. A prerequisite for advanced indentation is \<^emph>\Utilities / Buffer Options / Automatic indentation\: it needs to be set to \<^verbatim>\full\ (default). \ section \SideKick parsers \label{sec:sidekick}\ text \ The \<^emph>\SideKick\ plugin provides some general services to display buffer structure in a tree view. Isabelle/jEdit provides SideKick parsers for its main mode for theory files, ML files, as well as some minor modes for the \<^verbatim>\NEWS\ file (see \figref{fig:sidekick}), session \<^verbatim>\ROOT\ files, system \<^verbatim>\options\, and Bib{\TeX} files (\secref{sec:bibtex}). \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{sidekick} \end{center} \caption{The Isabelle NEWS file with SideKick tree view} \label{fig:sidekick} \end{figure} The default SideKick parser for theory files is \<^verbatim>\isabelle\: it provides a tree-view on the formal document structure, with section headings at the top and formal specification elements at the bottom. The alternative parser \<^verbatim>\isabelle-context\ shows nesting of context blocks according to \<^theory_text>\begin \ end\ structure. \<^medskip> Isabelle/ML files are structured according to semi-formal comments that are explained in @{cite "isabelle-implementation"}. This outline is turned into a tree-view by default, by using the \<^verbatim>\isabelle-ml\ parser. There is also a folding mode of the same name, for hierarchic text folds within ML files. \<^medskip> The special SideKick parser \<^verbatim>\isabelle-markup\ exposes the uninterpreted markup tree of the PIDE document model of the current buffer. This is occasionally useful for informative purposes, but the amount of displayed information might cause problems for large buffers. \ chapter \Prover IDE functionality \label{sec:document-model}\ section \Document model \label{sec:document-model}\ text \ The document model is central to the PIDE architecture: the editor and the prover have a common notion of structured source text with markup, which is produced by formal processing. The editor is responsible for edits of document source, as produced by the user. The prover is responsible for reports of document markup, as produced by its processing in the background. Isabelle/jEdit handles classic editor events of jEdit, in order to connect the physical world of the GUI (with its singleton state) to the mathematical world of multiple document versions (with timeless and stateless updates). \ subsection \Editor buffers and document nodes \label{sec:buffer-node}\ text \ As a regular text editor, jEdit maintains a collection of \<^emph>\buffers\ to store text files; each buffer may be associated with any number of visible \<^emph>\text areas\. Buffers are subject to an \<^emph>\edit mode\ that is determined from the file name extension. The following modes are treated specifically in Isabelle/jEdit: \<^medskip> \begin{tabular}{lll} \<^bold>\mode\ & \<^bold>\file name\ & \<^bold>\content\ \\\hline \<^verbatim>\isabelle\ & \<^verbatim>\*.thy\ & theory source \\ \<^verbatim>\isabelle-ml\ & \<^verbatim>\*.ML\ & Isabelle/ML source \\ \<^verbatim>\sml\ & \<^verbatim>\*.sml\ or \<^verbatim>\*.sig\ & Standard ML source \\ \<^verbatim>\isabelle-root\ & \<^verbatim>\ROOT\ & session root \\ \<^verbatim>\isabelle-options\ & & Isabelle options \\ \<^verbatim>\isabelle-news\ & & Isabelle NEWS \\ \end{tabular} \<^medskip> All jEdit buffers are automatically added to the PIDE document-model as \<^emph>\document nodes\. The overall document structure is defined by the theory nodes in two dimensions: \<^enum> via \<^bold>\theory imports\ that are specified in the \<^emph>\theory header\ using concrete syntax of the @{command_ref theory} command @{cite "isabelle-isar-ref"}; \<^enum> via \<^bold>\auxiliary files\ that are included into a theory by \<^emph>\load commands\, notably @{command_ref ML_file} and @{command_ref SML_file} @{cite "isabelle-isar-ref"}. In any case, source files are managed by the PIDE infrastructure: the physical file-system only plays a subordinate role. The relevant version of source text is passed directly from the editor to the prover, using internal communication channels. \ subsection \Theories \label{sec:theories}\ text \ The \<^emph>\Theories\ panel (see also \figref{fig:theories}) provides an overview of the status of continuous checking of theory nodes within the document model. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{theories} \end{center} \caption{Theories panel with an overview of the document-model, and jEdit text areas as editable views on some of the document nodes} \label{fig:theories} \end{figure} Theory imports are resolved automatically by the PIDE document model: all required files are loaded and stored internally, without the need to open corresponding jEdit buffers. Opening or closing editor buffers later on has no direct impact on the formal document content: it only affects visibility. In contrast, auxiliary files (e.g.\ from @{command ML_file} commands) are \<^emph>\not\ resolved within the editor by default, but the prover process takes care of that. This may be changed by enabling the system option @{system_option jedit_auto_resolve}: it ensures that all files are uniformly provided by the editor. \<^medskip> The visible \<^emph>\perspective\ of Isabelle/jEdit is defined by the collective view on theory buffers via open text areas. The perspective is taken as a hint for document processing: the prover ensures that those parts of a theory where the user is looking are checked, while other parts that are presently not required are ignored. The perspective is changed by opening or closing text area windows, or scrolling within a window. The \<^emph>\Theories\ panel provides some further options to influence the process of continuous checking: it may be switched off globally to restrict the prover to superficial processing of command syntax. It is also possible to indicate theory nodes as \<^emph>\required\ for continuous checking: this means such nodes and all their imports are always processed independently of the visibility status (if continuous checking is enabled). Big theory libraries that are marked as required can have significant impact on performance! The \<^emph>\Purge\ button restricts the document model to theories that are required for open editor buffers: inaccessible theories are removed and will be rechecked when opened or imported later. \<^medskip> Formal markup of checked theory content is turned into GUI rendering, based on a standard repertoire known from mainstream IDEs for programming languages: colors, icons, highlighting, squiggly underlines, tooltips, hyperlinks etc. For outer syntax of Isabelle/Isar there is some traditional syntax-highlighting via static keywords and tokenization within the editor; this buffer syntax is determined from theory imports. In contrast, the painting of inner syntax (term language etc.)\ uses semantic information that is reported dynamically from the logical context. Thus the prover can provide additional markup to help the user to understand the meaning of formal text, and to produce more text with some add-on tools (e.g.\ information messages with \<^emph>\sendback\ markup by automated provers or disprovers in the background). \ subsection \Auxiliary files \label{sec:aux-files}\ text \ Special load commands like @{command_ref ML_file} and @{command_ref SML_file} @{cite "isabelle-isar-ref"} refer to auxiliary files within some theory. Conceptually, the file argument of the command extends the theory source by the content of the file, but its editor buffer may be loaded~/ changed~/ saved separately. The PIDE document model propagates changes of auxiliary file content to the corresponding load command in the theory, to update and process it accordingly: changes of auxiliary file content are treated as changes of the corresponding load command. \<^medskip> As a concession to the massive amount of ML files in Isabelle/HOL itself, the content of auxiliary files is only added to the PIDE document-model on demand, the first time when opened explicitly in the editor. There are further tricks to manage markup of ML files, such that Isabelle/HOL may be edited conveniently in the Prover IDE on small machines with only 8\,GB of main memory. Using \<^verbatim>\Pure\ as logic session image, the exploration may start at the top \<^file>\$ISABELLE_HOME/src/HOL/Main.thy\ or the bottom \<^file>\$ISABELLE_HOME/src/HOL/HOL.thy\, for example. It is also possible to explore the Isabelle/Pure bootstrap process (a virtual copy) by opening \<^file>\$ISABELLE_HOME/src/Pure/ROOT.ML\ like a theory in the Prover IDE. Initially, before an auxiliary file is opened in the editor, the prover reads its content from the physical file-system. After the file is opened for the first time in the editor, e.g.\ by following the hyperlink (\secref{sec:tooltips-hyperlinks}) for the argument of its @{command ML_file} command, the content is taken from the jEdit buffer. The change of responsibility from prover to editor counts as an update of the document content, so subsequent theory sources need to be re-checked. When the buffer is closed, the responsibility remains to the editor: the file may be opened again without causing another document update. A file that is opened in the editor, but its theory with the load command is not, is presently inactive in the document model. A file that is loaded via multiple load commands is associated to an arbitrary one: this situation is morally unsupported and might lead to confusion. \<^medskip> Output that refers to an auxiliary file is combined with that of the corresponding load command, and shown whenever the file or the command are active (see also \secref{sec:output}). Warnings, errors, and other useful markup is attached directly to the positions in the auxiliary file buffer, in the manner of standard IDEs. By using the load command @{command SML_file} as explained in \<^file>\$ISABELLE_HOME/src/Tools/SML/Examples.thy\, Isabelle/jEdit may be used as fully-featured IDE for Standard ML, independently of theory or proof development: the required theory merely serves as some kind of project file for a collection of SML source modules. \ section \Output \label{sec:output}\ text \ Prover output consists of \<^emph>\markup\ and \<^emph>\messages\. Both are directly attached to the corresponding positions in the original source text, and visualized in the text area, e.g.\ as text colours for free and bound variables, or as squiggly underlines for warnings, errors etc.\ (see also \figref{fig:output}). In the latter case, the corresponding messages are shown by hovering with the mouse over the highlighted text --- although in many situations the user should already get some clue by looking at the position of the text highlighting, without seeing the message body itself. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{output} \end{center} \caption{Multiple views on prover output: gutter with icon, text area with popup, text overview column, \<^emph>\Theories\ panel, \<^emph>\Output\ panel} \label{fig:output} \end{figure} The ``gutter'' on the left-hand-side of the text area uses icons to provide a summary of the messages within the adjacent text line. Message priorities are used to prefer errors over warnings, warnings over information messages; other output is ignored. The ``text overview column'' on the right-hand-side of the text area uses similar information to paint small rectangles for the overall status of the whole text buffer. The graphics is scaled to fit the logical buffer length into the given window height. Mouse clicks on the overview area move the cursor approximately to the corresponding text line in the buffer. The \<^emph>\Theories\ panel provides another course-grained overview, but without direct correspondence to text positions. The coloured rectangles represent the amount of messages of a certain kind (warnings, errors, etc.) and the execution status of commands. The border of each rectangle indicates the overall status of processing: a thick border means it is \<^emph>\finished\ or \<^emph>\failed\ (with color for errors). A double-click on one of the theory entries with their status overview opens the corresponding text buffer, without moving the cursor to a specific point. \<^medskip> The \<^emph>\Output\ panel displays prover messages that correspond to a given command, within a separate window. The cursor position in the presently active text area determines the prover command whose cumulative message output is appended and shown in that window (in canonical order according to the internal execution of the command). There are also control elements to modify the update policy of the output wrt.\ continued editor movements: \<^emph>\Auto update\ and \<^emph>\Update\. This is particularly useful for multiple instances of the \<^emph>\Output\ panel to look at different situations. Alternatively, the panel can be turned into a passive \<^emph>\Info\ window via the \<^emph>\Detach\ menu item. Proof state is handled separately (\secref{sec:state-output}), but it is also possible to tick the corresponding checkbox to append it to regular output (\figref{fig:output-including-state}). This is a globally persistent option: it affects all open panels and future editor sessions. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{output-including-state} \end{center} \caption{Proof state display within the regular output panel} \label{fig:output-including-state} \end{figure} \<^medskip> Following the IDE principle, regular messages are attached to the original source in the proper place and may be inspected on demand via popups. This excludes messages that are somehow internal to the machinery of proof checking, notably \<^emph>\proof state\ and \<^emph>\tracing\. In any case, the same display technology is used for small popups and big output windows. The formal text contains markup that may be explored recursively via further popups and hyperlinks (see \secref{sec:tooltips-hyperlinks}), or clicked directly to initiate certain actions (see \secref{sec:auto-tools} and \secref{sec:sledgehammer}). \<^medskip> Alternatively, the subsequent actions (with keyboard shortcuts) allow to show tooltip messages or navigate error positions: \<^medskip> \begin{tabular}[t]{l} @{action_ref "isabelle.tooltip"} (\<^verbatim>\CS+b\) \\ @{action_ref "isabelle.message"} (\<^verbatim>\CS+m\) \\ \end{tabular}\quad \begin{tabular}[t]{l} @{action_ref "isabelle.first-error"} (\<^verbatim>\CS+a\) \\ @{action_ref "isabelle.last-error"} (\<^verbatim>\CS+z\) \\ @{action_ref "isabelle.next-error"} (\<^verbatim>\CS+n\) \\ @{action_ref "isabelle.prev-error"} (\<^verbatim>\CS+p\) \\ \end{tabular} \<^medskip> \ section \Proof state \label{sec:state-output}\ text \ The main purpose of the Prover IDE is to help the user editing proof documents, with ongoing formal checking by the prover in the background. This can be done to some extent in the main text area alone, especially for well-structured Isar proofs. Nonetheless, internal proof state needs to be inspected in many situations of exploration and ``debugging''. The \<^emph>\State\ panel shows exclusively such proof state messages without further distraction, while all other messages are displayed in \<^emph>\Output\ (\secref{sec:output}). \Figref{fig:output-and-state} shows a typical GUI layout where both panels are open. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{output-and-state} \end{center} \caption{Separate proof state display (right) and other output (bottom).} \label{fig:output-and-state} \end{figure} Another typical arrangement has more than one \<^emph>\State\ panel open (as floating windows), with \<^emph>\Auto update\ disabled to look at an old situation while the proof text in the vicinity is changed. The \<^emph>\Update\ button triggers an explicit one-shot update; this operation is also available via the action @{action "isabelle.update-state"} (keyboard shortcut \<^verbatim>\S+ENTER\). On small screens, it is occasionally useful to have all messages concatenated in the regular \<^emph>\Output\ panel, e.g.\ see \figref{fig:output-including-state}. \<^medskip> The mechanics of \<^emph>\Output\ versus \<^emph>\State\ are slightly different: \<^item> \<^emph>\Output\ shows information that is continuously produced and already present when the GUI wants to show it. This is implicitly controlled by the visible perspective on the text. \<^item> \<^emph>\State\ initiates a real-time query on demand, with a full round trip including a fresh print operation on the prover side. This is controlled explicitly when the cursor is moved to the next command (\<^emph>\Auto update\) or the \<^emph>\Update\ operation is triggered. This can make a difference in GUI responsibility and resource usage within the prover process. Applications with very big proof states that are only inspected in isolation work better with the \<^emph>\State\ panel. \ section \Query \label{sec:query}\ text \ The \<^emph>\Query\ panel provides various GUI forms to request extra information from the prover, as a replacement of old-style diagnostic commands like @{command find_theorems}. There are input fields and buttons for a particular query command, with output in a dedicated text area. The main query modes are presented as separate tabs: \<^emph>\Find Theorems\, \<^emph>\Find Constants\, \<^emph>\Print Context\, e.g.\ see \figref{fig:query}. As usual in jEdit, multiple \<^emph>\Query\ windows may be active at the same time: any number of floating instances, but at most one docked instance (which is used by default). \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{query} \end{center} \caption{An instance of the Query panel: find theorems} \label{fig:query} \end{figure} \<^medskip> The following GUI elements are common to all query modes: \<^item> The spinning wheel provides feedback about the status of a pending query wrt.\ the evaluation of its context and its own operation. \<^item> The \<^emph>\Apply\ button attaches a fresh query invocation to the current context of the command where the cursor is pointing in the text. \<^item> The \<^emph>\Search\ field allows to highlight query output according to some regular expression, in the notation that is commonly used on the Java platform.\<^footnote>\\<^url>\https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html\\ This may serve as an additional visual filter of the result. \<^item> The \<^emph>\Zoom\ box controls the font size of the output area. All query operations are asynchronous: there is no need to wait for the evaluation of the document for the query context, nor for the query operation itself. Query output may be detached as independent \<^emph>\Info\ window, using a menu operation of the dockable window manager. The printed result usually provides sufficient clues about the original query, with some hyperlink to its context (via markup of its head line). \ subsection \Find theorems\ text \ The \<^emph>\Query\ panel in \<^emph>\Find Theorems\ mode retrieves facts from the theory or proof context matching all of given criteria in the \<^emph>\Find\ text field. A single criterion has the following syntax: \<^rail>\ ('-'?) ('name' ':' @{syntax name} | 'intro' | 'elim' | 'dest' | 'solves' | 'simp' ':' @{syntax term} | @{syntax term}) \ See also the Isar command @{command_ref find_theorems} in @{cite "isabelle-isar-ref"}. \ subsection \Find constants\ text \ The \<^emph>\Query\ panel in \<^emph>\Find Constants\ mode prints all constants whose type meets all of the given criteria in the \<^emph>\Find\ text field. A single criterion has the following syntax: \<^rail>\ ('-'?) ('name' ':' @{syntax name} | 'strict' ':' @{syntax type} | @{syntax type}) \ See also the Isar command @{command_ref find_consts} in @{cite "isabelle-isar-ref"}. \ subsection \Print context\ text \ The \<^emph>\Query\ panel in \<^emph>\Print Context\ mode prints information from the theory or proof context, or proof state. See also the Isar commands @{command_ref print_context}, @{command_ref print_cases}, @{command_ref print_term_bindings}, @{command_ref print_theorems}, described in @{cite "isabelle-isar-ref"}. \ section \Tooltips and hyperlinks \label{sec:tooltips-hyperlinks}\ text \ Formally processed text (prover input or output) contains rich markup that can be explored by using the \<^verbatim>\CONTROL\ modifier key on Linux and Windows, or \<^verbatim>\COMMAND\ on macOS. Hovering with the mouse while the modifier is pressed reveals a \<^emph>\tooltip\ (grey box over the text with a yellow popup) and/or a \<^emph>\hyperlink\ (black rectangle over the text with change of mouse pointer); see also \figref{fig:tooltip}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{popup1} \end{center} \caption{Tooltip and hyperlink for some formal entity} \label{fig:tooltip} \end{figure} Tooltip popups use the same rendering technology as the main text area, and further tooltips and/or hyperlinks may be exposed recursively by the same mechanism; see \figref{fig:nested-tooltips}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{popup2} \end{center} \caption{Nested tooltips over formal entities} \label{fig:nested-tooltips} \end{figure} The tooltip popup window provides some controls to \<^emph>\close\ or \<^emph>\detach\ the window, turning it into a separate \<^emph>\Info\ window managed by jEdit. The \<^verbatim>\ESCAPE\ key closes \<^emph>\all\ popups, which is particularly relevant when nested tooltips are stacking up. \<^medskip> A black rectangle in the text indicates a hyperlink that may be followed by a mouse click (while the \<^verbatim>\CONTROL\ or \<^verbatim>\COMMAND\ modifier key is still pressed). Such jumps to other text locations are recorded by the \<^emph>\Navigator\ plugin, which is bundled with Isabelle/jEdit and enabled by default. There are usually navigation arrows in the main jEdit toolbar. Note that the link target may be a file that is itself not subject to formal document processing of the editor session and thus prevents further exploration: the chain of hyperlinks may end in some source file of the underlying logic image, or within the ML bootstrap sources of Isabelle/Pure. \ section \Formal scopes and semantic selection\ text \ Formal entities are semantically annotated in the source text as explained in \secref{sec:tooltips-hyperlinks}. A \<^emph>\formal scope\ consists of the defining position with all its referencing positions. This correspondence is highlighted in the text according to the cursor position, see also \figref{fig:scope1}. Here the referencing positions are rendered with an additional border, in reminiscence to a hyperlink. A mouse click with \<^verbatim>\C\ modifier, or the action @{action_def "isabelle.goto-entity"} (shortcut \<^verbatim>\CS+d\) jumps to the original defining position. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{scope1} \end{center} \caption{Scope of formal entity: defining vs.\ referencing positions} \label{fig:scope1} \end{figure} The action @{action_def "isabelle.select-entity"} (shortcut \<^verbatim>\CS+ENTER\) supports semantic selection of all occurrences of the formal entity at the caret position, with a defining position in the current editor buffer. This facilitates systematic renaming, using regular jEdit editing of a multi-selection, see also \figref{fig:scope2}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{scope2} \end{center} \caption{The result of semantic selection and systematic renaming} \label{fig:scope2} \end{figure} By default, the visual feedback on scopes is restricted to definitions within the visible text area. The keyboard modifier \<^verbatim>\CS\ overrides this: then all defining and referencing positions are shown. This modifier may be configured via option @{system_option jedit_focus_modifier}; the default coincides with the modifier for the above keyboard actions. The empty string means to disable this additional visual feedback. \ section \Completion \label{sec:completion}\ text \ Smart completion of partial input is the IDE functionality \<^emph>\par excellance\. Isabelle/jEdit combines several sources of information to achieve that. Despite its complexity, it should be possible to get some idea how completion works by experimentation, based on the overview of completion varieties in \secref{sec:completion-varieties}. The remaining subsections explain concepts around completion more systematically. \<^medskip> \<^emph>\Explicit completion\ is triggered by the action @{action_ref "isabelle.complete"}, which is bound to the keyboard shortcut \<^verbatim>\C+b\, and thus overrides the jEdit default for @{action_ref "complete-word"}. \<^emph>\Implicit completion\ hooks into the regular keyboard input stream of the editor, with some event filtering and optional delays. \<^medskip> Completion options may be configured in \<^emph>\Plugin Options~/ Isabelle~/ General~/ Completion\. These are explained in further detail below, whenever relevant. There is also a summary of options in \secref{sec:completion-options}. The asynchronous nature of PIDE interaction means that information from the prover is delayed --- at least by a full round-trip of the document update protocol. The default options already take this into account, with a sufficiently long completion delay to speculate on the availability of all relevant information from the editor and the prover, before completing text immediately or producing a popup. Although there is an inherent danger of non-deterministic behaviour due to such real-time parameters, the general completion policy aims at determined results as far as possible. \ subsection \Varieties of completion \label{sec:completion-varieties}\ subsubsection \Built-in templates\ text \ Isabelle is ultimately a framework of nested sub-languages of different kinds and purposes. The completion mechanism supports this by the following built-in templates: \<^descr> \<^verbatim>\`\ (single ASCII back-quote) or \<^verbatim>\"\ (double ASCII quote) support \<^emph>\quotations\ via text cartouches. There are three selections, which are always presented in the same order and do not depend on any context information. The default choice produces a template ``\\\\\'', where the box indicates the cursor position after insertion; the other choices help to repair the block structure of unbalanced text cartouches. \<^descr> \<^verbatim>\@{\ is completed to the template ``\@{\}\'', where the box indicates the cursor position after insertion. Here it is convenient to use the wildcard ``\<^verbatim>\__\'' or a more specific name prefix to let semantic completion of name-space entries propose antiquotation names. With some practice, input of quoted sub-languages and antiquotations of embedded languages should work smoothly. Note that national keyboard layouts might cause problems with back-quote as dead key, but double quote can be used instead. \ subsubsection \Syntax keywords\ text \ Syntax completion tables are determined statically from the keywords of the ``outer syntax'' of the underlying edit mode: for theory files this is the syntax of Isar commands according to the cumulative theory imports. Keywords are usually plain words, which means the completion mechanism only inserts them directly into the text for explicit completion (\secref{sec:completion-input}), but produces a popup (\secref{sec:completion-popup}) otherwise. At the point where outer syntax keywords are defined, it is possible to specify an alternative replacement string to be inserted instead of the keyword itself. An empty string means to suppress the keyword altogether, which is occasionally useful to avoid confusion, e.g.\ the rare keyword @{command simproc_setup} vs.\ the frequent name-space entry \simp\. \ subsubsection \Isabelle symbols\ text \ The completion tables for Isabelle symbols (\secref{sec:symbols}) are determined statically from \<^file>\$ISABELLE_HOME/etc/symbols\ and \<^path>\$ISABELLE_HOME_USER/etc/symbols\ for each symbol specification as follows: \<^medskip> \begin{tabular}{ll} \<^bold>\completion entry\ & \<^bold>\example\ \\\hline literal symbol & \<^verbatim>\\\ \\ symbol name with backslash & \<^verbatim>\\\\<^verbatim>\forall\ \\ symbol abbreviation & \<^verbatim>\ALL\ or \<^verbatim>\!\ \\ \end{tabular} \<^medskip> When inserted into the text, the above examples all produce the same Unicode rendering \\\ of the underlying symbol \<^verbatim>\\\. A symbol abbreviation that is a plain word, like \<^verbatim>\ALL\, is treated like a syntax keyword. Non-word abbreviations like \<^verbatim>\-->\ are inserted more aggressively, except for single-character abbreviations like \<^verbatim>\!\ above. Completion via abbreviations like \<^verbatim>\ALL\ or \<^verbatim>\-->\ depends on the semantic language context (\secref{sec:completion-context}). In contrast, backslash sequences like \<^verbatim>\\forall\ \<^verbatim>\\\ are always possible, but require additional interaction to confirm (via popup). This is important in ambiguous situations, e.g.\ for Isabelle document source, which may contain formal symbols or informal {\LaTeX} macros. Backslash sequences also help when input is broken, and thus escapes its normal semantic context: e.g.\ antiquotations or string literals in ML, which do not allow arbitrary backslash sequences. Special symbols like \<^verbatim>\\\ or control symbols like \<^verbatim>\\<^cancel>\, \<^verbatim>\\<^latex>\, \<^verbatim>\\<^binding>\ can have an argument: completing on a name prefix offers a template with an empty cartouche. Thus completion of \<^verbatim>\\co\ or \<^verbatim>\\ca\ allows to compose formal document comments quickly.\<^footnote>\It is customary to put a space between \<^verbatim>\\\ and its argument, while control symbols do \<^emph>\not\ allow extra space here.\ \ subsubsection \User-defined abbreviations\ text \ The theory header syntax supports abbreviations via the \<^theory_text>\abbrevs\ keyword @{cite "isabelle-isar-ref"}. This is a slight generalization of built-in templates and abbreviations for Isabelle symbols, as explained above. Examples may be found in the Isabelle sources, by searching for ``\<^verbatim>\abbrevs\'' in \<^verbatim>\*.thy\ files. The \<^emph>\Symbols\ panel shows the abbreviations that are available in the current theory buffer (according to its \<^theory_text>\imports\) in the \<^verbatim>\Abbrevs\ tab. \ subsubsection \Name-space entries\ text \ This is genuine semantic completion, using information from the prover, so it requires some delay. A \<^emph>\failed name-space lookup\ produces an error message that is annotated with a list of alternative names that are legal. The list of results is truncated according to the system option @{system_option_ref completion_limit}. The completion mechanism takes this into account when collecting information on the prover side. Already recognized names are \<^emph>\not\ completed further, but completion may be extended by appending a suffix of underscores. This provokes a failed lookup, and another completion attempt (ignoring the underscores). For example, in a name space where \<^verbatim>\foo\ and \<^verbatim>\foobar\ are known, the input \<^verbatim>\foo\ remains unchanged, but \<^verbatim>\foo_\ may be completed to \<^verbatim>\foo\ or \<^verbatim>\foobar\. The special identifier ``\<^verbatim>\__\'' serves as a wild-card for arbitrary completion: it exposes the name-space content to the completion mechanism (truncated according to @{system_option completion_limit}). This is occasionally useful to explore an unknown name-space, e.g.\ in some template. \ subsubsection \File-system paths\ text \ Depending on prover markup about file-system paths in the source text, e.g.\ for the argument of a load command (\secref{sec:aux-files}), the completion mechanism explores the directory content and offers the result as completion popup. Relative path specifications are understood wrt.\ the \<^emph>\master directory\ of the document node (\secref{sec:buffer-node}) of the enclosing editor buffer; this requires a proper theory, not an auxiliary file. A suffix of slashes may be used to continue the exploration of an already recognized directory name. \ subsubsection \Spell-checking\ text \ The spell-checker combines semantic markup from the prover (regions of plain words) with static dictionaries (word lists) that are known to the editor. Unknown words are underlined in the text, using @{system_option_ref spell_checker_color} (blue by default). This is not an error, but a hint to the user that some action may be taken. The jEdit context menu provides various actions, as far as applicable: \<^medskip> \begin{tabular}{l} @{action_ref "isabelle.complete-word"} \\ @{action_ref "isabelle.exclude-word"} \\ @{action_ref "isabelle.exclude-word-permanently"} \\ @{action_ref "isabelle.include-word"} \\ @{action_ref "isabelle.include-word-permanently"} \\ \end{tabular} \<^medskip> Instead of the specific @{action_ref "isabelle.complete-word"}, it is also possible to use the generic @{action_ref "isabelle.complete"} with its default keyboard shortcut \<^verbatim>\C+b\. \<^medskip> Dictionary lookup uses some educated guesses about lower-case, upper-case, and capitalized words. This is oriented on common use in English, where this aspect is not decisive for proper spelling (in contrast to German, for example). \ subsection \Semantic completion context \label{sec:completion-context}\ text \ Completion depends on a semantic context that is provided by the prover, although with some delay, because at least a full PIDE protocol round-trip is required. Until that information becomes available in the PIDE document-model, the default context is given by the outer syntax of the editor mode (see also \secref{sec:buffer-node}). The semantic \<^emph>\language context\ provides information about nested sub-languages of Isabelle: keywords are only completed for outer syntax, and antiquotations for languages that support them. Symbol abbreviations only work for specific sub-languages: e.g.\ ``\<^verbatim>\=>\'' is \<^emph>\not\ completed in regular ML source, but is completed within ML strings, comments, antiquotations. Backslash representations of symbols like ``\<^verbatim>\\foobar\'' or ``\<^verbatim>\\\'' work in any context --- after additional confirmation. The prover may produce \<^emph>\no completion\ markup in exceptional situations, to tell that some language keywords should be excluded from further completion attempts. For example, ``\<^verbatim>\:\'' within accepted Isar syntax looses its meaning as abbreviation for symbol ``\\\''. \ subsection \Input events \label{sec:completion-input}\ text \ Completion is triggered by certain events produced by the user, with optional delay after keyboard input according to @{system_option jedit_completion_delay}. \<^descr>[Explicit completion] works via action @{action_ref "isabelle.complete"} with keyboard shortcut \<^verbatim>\C+b\. This overrides the shortcut for @{action_ref "complete-word"} in jEdit, but it is possible to restore the original jEdit keyboard mapping of @{action "complete-word"} via \<^emph>\Global Options~/ Shortcuts\ and invent a different one for @{action "isabelle.complete"}. \<^descr>[Explicit spell-checker completion] works via @{action_ref "isabelle.complete-word"}, which is exposed in the jEdit context menu, if the mouse points to a word that the spell-checker can complete. \<^descr>[Implicit completion] works via regular keyboard input of the editor. It depends on further side-conditions: \<^enum> The system option @{system_option_ref jedit_completion} needs to be enabled (default). \<^enum> Completion of syntax keywords requires at least 3 relevant characters in the text. \<^enum> The system option @{system_option_ref jedit_completion_delay} determines an additional delay (0.5 by default), before opening a completion popup. The delay gives the prover a chance to provide semantic completion information, notably the context (\secref{sec:completion-context}). \<^enum> The system option @{system_option_ref jedit_completion_immediate} (enabled by default) controls whether replacement text should be inserted immediately without popup, regardless of @{system_option jedit_completion_delay}. This aggressive mode of completion is restricted to symbol abbreviations that are not plain words (\secref{sec:symbols}). \<^enum> Completion of symbol abbreviations with only one relevant character in the text always enforces an explicit popup, regardless of @{system_option_ref jedit_completion_immediate}. \ subsection \Completion popup \label{sec:completion-popup}\ text \ A \<^emph>\completion popup\ is a minimally invasive GUI component over the text area that offers a selection of completion items to be inserted into the text, e.g.\ by mouse clicks. Items are sorted dynamically, according to the frequency of selection, with persistent history. The popup may interpret special keys \<^verbatim>\ENTER\, \<^verbatim>\TAB\, \<^verbatim>\ESCAPE\, \<^verbatim>\UP\, \<^verbatim>\DOWN\, \<^verbatim>\PAGE_UP\, \<^verbatim>\PAGE_DOWN\, but all other key events are passed to the underlying text area. This allows to ignore unwanted completions most of the time and continue typing quickly. Thus the popup serves as a mechanism of confirmation of proposed items, while the default is to continue without completion. The meaning of special keys is as follows: \<^medskip> \begin{tabular}{ll} \<^bold>\key\ & \<^bold>\action\ \\\hline \<^verbatim>\ENTER\ & select completion (if @{system_option jedit_completion_select_enter}) \\ \<^verbatim>\TAB\ & select completion (if @{system_option jedit_completion_select_tab}) \\ \<^verbatim>\ESCAPE\ & dismiss popup \\ \<^verbatim>\UP\ & move up one item \\ \<^verbatim>\DOWN\ & move down one item \\ \<^verbatim>\PAGE_UP\ & move up one page of items \\ \<^verbatim>\PAGE_DOWN\ & move down one page of items \\ \end{tabular} \<^medskip> Movement within the popup is only active for multiple items. Otherwise the corresponding key event retains its standard meaning within the underlying text area. \ subsection \Insertion \label{sec:completion-insert}\ text \ Completion may first propose replacements to be selected (via a popup), or replace text immediately in certain situations and depending on certain options like @{system_option jedit_completion_immediate}. In any case, insertion works uniformly, by imitating normal jEdit text insertion, depending on the state of the \<^emph>\text selection\. Isabelle/jEdit tries to accommodate the most common forms of advanced selections in jEdit, but not all combinations make sense. At least the following important cases are well-defined: \<^descr>[No selection.] The original is removed and the replacement inserted, depending on the caret position. \<^descr>[Rectangular selection of zero width.] This special case is treated by jEdit as ``tall caret'' and insertion of completion imitates its normal behaviour: separate copies of the replacement are inserted for each line of the selection. \<^descr>[Other rectangular selection or multiple selections.] Here the original is removed and the replacement is inserted for each line (or segment) of the selection. Support for multiple selections is particularly useful for \<^emph>\HyperSearch\: clicking on one of the items in the \<^emph>\HyperSearch Results\ window makes jEdit select all its occurrences in the corresponding line of text. Then explicit completion can be invoked via \<^verbatim>\C+b\, e.g.\ to replace occurrences of \<^verbatim>\-->\ by \\\. \<^medskip> Insertion works by removing and inserting pieces of text from the buffer. This counts as one atomic operation on the jEdit history. Thus unintended completions may be reverted by the regular @{action undo} action of jEdit. According to normal jEdit policies, the recovered text after @{action undo} is selected: \<^verbatim>\ESCAPE\ is required to reset the selection and to continue typing more text. \ subsection \Options \label{sec:completion-options}\ text \ This is a summary of Isabelle/Scala system options that are relevant for completion. They may be configured in \<^emph>\Plugin Options~/ Isabelle~/ General\ as usual. \<^item> @{system_option_def completion_limit} specifies the maximum number of items for various semantic completion operations (name-space entries etc.) \<^item> @{system_option_def jedit_completion} guards implicit completion via regular jEdit key events (\secref{sec:completion-input}): it allows to disable implicit completion altogether. \<^item> @{system_option_def jedit_completion_select_enter} and @{system_option_def jedit_completion_select_tab} enable keys to select a completion item from the popup (\secref{sec:completion-popup}). Note that a regular mouse click on the list of items is always possible. \<^item> @{system_option_def jedit_completion_context} specifies whether the language context provided by the prover should be used at all. Disabling that option makes completion less ``semantic''. Note that incomplete or severely broken input may cause some disagreement of the prover and the user about the intended language context. \<^item> @{system_option_def jedit_completion_delay} and @{system_option_def jedit_completion_immediate} determine the handling of keyboard events for implicit completion (\secref{sec:completion-input}). A @{system_option jedit_completion_delay}~\<^verbatim>\> 0\ postpones the processing of key events, until after the user has stopped typing for the given time span, but @{system_option jedit_completion_immediate}~\<^verbatim>\= true\ means that abbreviations of Isabelle symbols are handled nonetheless. \<^item> @{system_option_def completion_path_ignore} specifies ``glob'' patterns to ignore in file-system path completion (separated by colons), e.g.\ backup files ending with tilde. \<^item> @{system_option_def spell_checker} is a global guard for all spell-checker operations: it allows to disable that mechanism altogether. \<^item> @{system_option_def spell_checker_dictionary} determines the current dictionary, taken from the colon-separated list in the settings variable @{setting_def JORTHO_DICTIONARIES}. There are jEdit actions to specify local updates to a dictionary, by including or excluding words. The result of permanent dictionary updates is stored in the directory \<^path>\$ISABELLE_HOME_USER/dictionaries\, in a separate file for each dictionary. \<^item> @{system_option_def spell_checker_include} specifies a comma-separated list of markup elements that delimit words in the source that is subject to spell-checking, including various forms of comments. \<^item> @{system_option_def spell_checker_exclude} specifies a comma-separated list of markup elements that disable spell-checking (e.g.\ in nested antiquotations). \ section \Automatically tried tools \label{sec:auto-tools}\ text \ Continuous document processing works asynchronously in the background. Visible document source that has been evaluated may get augmented by additional results of \<^emph>\asynchronous print functions\. An example for that is proof state output, if that is enabled in the Output panel (\secref{sec:output}). More heavy-weight print functions may be applied as well, e.g.\ to prove or disprove parts of the formal text by other means. Isabelle/HOL provides various automatically tried tools that operate on outermost goal statements (e.g.\ @{command lemma}, @{command theorem}), independently of the state of the current proof attempt. They work implicitly without any arguments. Results are output as \<^emph>\information messages\, which are indicated in the text area by blue squiggles and a blue information sign in the gutter (see \figref{fig:auto-tools}). The message content may be shown as for other output (see also \secref{sec:output}). Some tools produce output with \<^emph>\sendback\ markup, which means that clicking on certain parts of the text inserts that into the source in the proper place. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{auto-tools} \end{center} \caption{Result of automatically tried tools} \label{fig:auto-tools} \end{figure} \<^medskip> The following Isabelle system options control the behavior of automatically tried tools (see also the jEdit dialog window \<^emph>\Plugin Options~/ Isabelle~/ General~/ Automatically tried tools\): \<^item> @{system_option_ref auto_methods} controls automatic use of a combination of standard proof methods (@{method auto}, @{method simp}, @{method blast}, etc.). This corresponds to the Isar command @{command_ref "try0"} @{cite "isabelle-isar-ref"}. The tool is disabled by default, since unparameterized invocation of standard proof methods often consumes substantial CPU resources without leading to success. \<^item> @{system_option_ref auto_nitpick} controls a slightly reduced version of @{command_ref nitpick}, which tests for counterexamples using first-order relational logic. See also the Nitpick manual @{cite "isabelle-nitpick"}. This tool is disabled by default, due to the extra overhead of invoking an external Java process for each attempt to disprove a subgoal. \<^item> @{system_option_ref auto_quickcheck} controls automatic use of @{command_ref quickcheck}, which tests for counterexamples using a series of assignments for free variables of a subgoal. This tool is \<^emph>\enabled\ by default. It requires little overhead, but is a bit weaker than @{command nitpick}. \<^item> @{system_option_ref auto_sledgehammer} controls a significantly reduced version of @{command_ref sledgehammer}, which attempts to prove a subgoal using external automatic provers. See also the Sledgehammer manual @{cite "isabelle-sledgehammer"}. This tool is disabled by default, due to the relatively heavy nature of Sledgehammer. \<^item> @{system_option_ref auto_solve_direct} controls automatic use of @{command_ref solve_direct}, which checks whether the current subgoals can be solved directly by an existing theorem. This also helps to detect duplicate lemmas. This tool is \<^emph>\enabled\ by default. Invocation of automatically tried tools is subject to some global policies of parallel execution, which may be configured as follows: \<^item> @{system_option_ref auto_time_limit} (default 2.0) determines the timeout (in seconds) for each tool execution. \<^item> @{system_option_ref auto_time_start} (default 1.0) determines the start delay (in seconds) for automatically tried tools, after the main command evaluation is finished. Each tool is submitted independently to the pool of parallel execution tasks in Isabelle/ML, using hardwired priorities according to its relative ``heaviness''. The main stages of evaluation and printing of proof states take precedence, but an already running tool is not canceled and may thus reduce reactivity of proof document processing. Users should experiment how the available CPU resources (number of cores) are best invested to get additional feedback from prover in the background, by using a selection of weaker or stronger tools. \ section \Sledgehammer \label{sec:sledgehammer}\ text \ The \<^emph>\Sledgehammer\ panel (\figref{fig:sledgehammer}) provides a view on some independent execution of the Isar command @{command_ref sledgehammer}, with process indicator (spinning wheel) and GUI elements for important Sledgehammer arguments and options. Any number of Sledgehammer panels may be active, according to the standard policies of Dockable Window Management in jEdit. Closing such windows also cancels the corresponding prover tasks. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{sledgehammer} \end{center} \caption{An instance of the Sledgehammer panel} \label{fig:sledgehammer} \end{figure} The \<^emph>\Apply\ button attaches a fresh invocation of @{command sledgehammer} to the command where the cursor is pointing in the text --- this should be some pending proof problem. Further buttons like \<^emph>\Cancel\ and \<^emph>\Locate\ help to manage the running process. Results appear incrementally in the output window of the panel. Proposed proof snippets are marked-up as \<^emph>\sendback\, which means a single mouse click inserts the text into a suitable place of the original source. Some manual editing may be required nonetheless, say to remove earlier proof attempts. \ chapter \Isabelle document preparation\ text \ The ultimate purpose of Isabelle is to produce nicely rendered documents with the Isabelle document preparation system, which is based on {\LaTeX}; see also @{cite "isabelle-system" and "isabelle-isar-ref"}. Isabelle/jEdit provides some additional support for document editing. \ section \Document outline\ text \ Theory sources may contain document markup commands, such as @{command_ref chapter}, @{command_ref section}, @{command subsection}. The Isabelle SideKick parser (\secref{sec:sidekick}) represents this document outline as structured tree view, with formal statements and proofs nested inside; see \figref{fig:sidekick-document}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{sidekick-document} \end{center} \caption{Isabelle document outline via SideKick tree view} \label{fig:sidekick-document} \end{figure} It is also possible to use text folding according to this structure, by adjusting \<^emph>\Utilities / Buffer Options / Folding mode\ of jEdit. The default mode \<^verbatim>\isabelle\ uses the structure of formal definitions, statements, and proofs. The alternative mode \<^verbatim>\sidekick\ uses the document structure of the SideKick parser, as explained above. \ section \Markdown structure\ text \ Document text is internally structured in paragraphs and nested lists, using notation that is similar to Markdown\<^footnote>\\<^url>\https://commonmark.org\\. There are special control symbols for items of different kinds of lists, corresponding to \<^verbatim>\itemize\, \<^verbatim>\enumerate\, \<^verbatim>\description\ in {\LaTeX}. This is illustrated in for \<^verbatim>\itemize\ in \figref{fig:markdown-document}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{markdown-document} \end{center} \caption{Markdown structure within document text} \label{fig:markdown-document} \end{figure} Items take colour according to the depth of nested lists. This helps to explore the implicit rules for list structure interactively. There is also markup for individual items and paragraphs in the text: it may be explored via mouse hovering with \<^verbatim>\CONTROL\ / \<^verbatim>\COMMAND\ as usual (\secref{sec:tooltips-hyperlinks}). \ section \Citations and Bib{\TeX} entries \label{sec:bibtex}\ text \ Citations are managed by {\LaTeX} and Bib{\TeX} in \<^verbatim>\.bib\ files. The Isabelle session build process and the @{tool latex} tool @{cite "isabelle-system"} are smart enough to assemble the result, based on the session directory layout. The document antiquotation \@{cite}\ is described in @{cite "isabelle-isar-ref"}. Within the Prover IDE it provides semantic markup for tooltips, hyperlinks, and completion for Bib{\TeX} database entries. Isabelle/jEdit does \<^emph>\not\ know about the actual Bib{\TeX} environment used in {\LaTeX} batch-mode, but it can take citations from those \<^verbatim>\.bib\ files that happen to be open in the editor; see \figref{fig:cite-completion}. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{cite-completion} \end{center} \caption{Semantic completion of citations from open Bib{\TeX} files} \label{fig:cite-completion} \end{figure} Isabelle/jEdit also provides IDE support for editing \<^verbatim>\.bib\ files themselves. There is syntax highlighting based on entry types (according to standard Bib{\TeX} styles), a context-menu to compose entries systematically, and a SideKick tree view of the overall content; see \figref{fig:bibtex-mode}. Semantic checking with errors and warnings is performed by the original \<^verbatim>\bibtex\ tool using style \<^verbatim>\plain\: different Bib{\TeX} styles may produce slightly different results. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{bibtex-mode} \end{center} \caption{Bib{\TeX} mode with context menu, SideKick tree view, and semantic output from the \<^verbatim>\bibtex\ tool} \label{fig:bibtex-mode} \end{figure} Regular document preview (\secref{sec:document-preview}) of \<^verbatim>\.bib\ files approximates the usual {\LaTeX} bibliography output in HTML (using style \<^verbatim>\unsort\). \ section \Document preview and printing \label{sec:document-preview}\ text \ The action @{action_def isabelle.preview} opens an HTML preview of the current document node in the default web browser. The content is derived from the semantic markup produced by the prover, and thus depends on the status of formal processing. Action @{action_def isabelle.draft} is similar to @{action isabelle.preview}, but shows a plain-text document draft. Both actions show document sources in a regular Web browser, which may be also used to print the result in a more portable manner than the Java printer dialog of the jEdit @{action_ref print} action. \ chapter \ML debugging within the Prover IDE\ text \ Isabelle/ML is based on Poly/ML\<^footnote>\\<^url>\https://www.polyml.org\\ and thus benefits from the source-level debugger of that implementation of Standard ML. The Prover IDE provides the \<^emph>\Debugger\ dockable to connect to running ML threads, inspect the stack frame with local ML bindings, and evaluate ML expressions in a particular run-time context. A typical debugger session is shown in \figref{fig:ml-debugger}. ML debugging depends on the following pre-requisites. \<^enum> ML source needs to be compiled with debugging enabled. This may be controlled for particular chunks of ML sources using any of the subsequent facilities. \<^enum> The system option @{system_option_ref ML_debugger} as implicit state of the Isabelle process. It may be changed in the menu \<^emph>\Plugins / Plugin Options / Isabelle / General\. ML modules need to be reloaded and recompiled to pick up that option as intended. \<^enum> The configuration option @{attribute_ref ML_debugger}, with an attribute of the same name, to update a global or local context (e.g.\ with the @{command declare} command). \<^enum> Commands that modify @{attribute ML_debugger} state for individual files: @{command_ref ML_file_debug}, @{command_ref ML_file_no_debug}, @{command_ref SML_file_debug}, @{command_ref SML_file_no_debug}. The instrumentation of ML code for debugging causes minor run-time overhead. ML modules that implement critical system infrastructure may lead to deadlocks or other undefined behaviour, when put under debugger control! \<^enum> The \<^emph>\Debugger\ panel needs to be active, otherwise the program ignores debugger instrumentation of the compiler and runs unmanaged. It is also possible to start debugging with the panel open, and later undock it, to let the program continue unhindered. \<^enum> The ML program needs to be stopped at a suitable breakpoint, which may be activated individually or globally as follows. For ML sources that have been compiled with debugger support, the IDE visualizes possible breakpoints in the text. A breakpoint may be toggled by pointing accurately with the mouse, with a right-click to activate jEdit's context menu and its \<^emph>\Toggle Breakpoint\ item. Alternatively, the \<^emph>\Break\ checkbox in the \<^emph>\Debugger\ panel may be enabled to stop ML threads always at the next possible breakpoint. Note that the state of individual breakpoints \<^emph>\gets lost\ when the coresponding ML source is re-compiled! This may happen unintentionally, e.g.\ when following hyperlinks into ML modules that have not been loaded into the IDE before. \begin{figure}[!htb] \begin{center} \includegraphics[scale=0.333]{ml-debugger} \end{center} \caption{ML debugger session} \label{fig:ml-debugger} \end{figure} The debugger panel (\figref{fig:ml-debugger}) shows a list of all threads that are presently stopped. Each thread shows a stack of all function invocations that lead to the current breakpoint at the top. It is possible to jump between stack positions freely, by clicking on this list. The current situation is displayed in the big output window, as a local ML environment with names and printed values. ML expressions may be evaluated in the current context by entering snippets of source into the text fields labeled \Context\ and \ML\, and pushing the \Eval\ button. By default, the source is interpreted as Isabelle/ML with the usual support for antiquotations (like @{command ML}, @{command ML_file}). Alternatively, strict Standard ML may be enforced via the \<^emph>\SML\ checkbox (like @{command SML_file}). The context for Isabelle/ML is optional, it may evaluate to a value of type \<^ML_type>\theory\, \<^ML_type>\Proof.context\, or \<^ML_type>\Context.generic\. Thus the given ML expression (with its antiquotations) may be subject to the intended dynamic run-time context, instead of the static compile-time context. \<^medskip> The buttons labeled \<^emph>\Continue\, \<^emph>\Step\, \<^emph>\Step over\, \<^emph>\Step out\ recommence execution of the program, with different policies concerning nested function invocations. The debugger always moves the cursor within the ML source to the next breakpoint position, and offers new stack frames as before. \ chapter \Miscellaneous tools\ section \Timing and monitoring\ text \ Managed evaluation of commands within PIDE documents includes timing information, which consists of elapsed (wall-clock) time, CPU time, and GC (garbage collection) time. Note that in a multithreaded system it is difficult to measure execution time precisely: elapsed time is closer to the real requirements of runtime resources than CPU or GC time, which are both subject to influences from the parallel environment that are outside the scope of the current command transaction. The \<^emph>\Timing\ panel provides an overview of cumulative command timings for each document node. Commands with elapsed time below the given threshold are ignored in the grand total. Nodes are sorted according to their overall timing. For the document node that corresponds to the current buffer, individual command timings are shown as well. A double-click on a theory node or command moves the editor focus to that particular source position. It is also possible to reveal individual timing information via some tooltip for the corresponding command keyword, using the technique of mouse hovering with \<^verbatim>\CONTROL\~/ \<^verbatim>\COMMAND\ modifier (\secref{sec:tooltips-hyperlinks}). Actual display of timing depends on the global option @{system_option_ref jedit_timing_threshold}, which can be configured in \<^emph>\Plugin Options~/ Isabelle~/ General\. \<^medskip> The jEdit status line includes a monitor widget for the current heap usage of the Isabelle/ML process; this includes information about ongoing garbage collection (shown as ``ML cleanup''). A double-click opens a new instance of the \<^emph>\Monitor\ panel, as explained below. There is a similar widget for the JVM: a double-click opens an external Java monitor process with detailed information and controls for the Java process underlying Isabelle/Scala/jEdit (this is based on \<^verbatim>\jconsole\). \<^medskip> The \<^emph>\Monitor\ panel visualizes various data collections about recent activity of the runtime system of Isabelle/ML and Java. There are buttons to request a full garbage collection and sharing of live data on the ML heap. The display is continuously updated according to @{system_option_ref editor_chart_delay}. Note that the painting of the chart takes considerable runtime itself --- on the Java Virtual Machine that runs Isabelle/Scala, not Isabelle/ML. \ section \Low-level output\ text \ Prover output is normally shown directly in the main text area or specific panels like \<^emph>\Output\ (\secref{sec:output}) or \<^emph>\State\ (\secref{sec:state-output}). Beyond this, it is occasionally useful to inspect low-level output channels via some of the following additional panels: \<^item> \<^emph>\Protocol\ shows internal messages between the Isabelle/Scala and Isabelle/ML side of the PIDE document editing protocol. Recording of messages starts with the first activation of the corresponding dockable window; earlier messages are lost. Display of protocol messages causes considerable slowdown, so it is important to undock all \<^emph>\Protocol\ panels for production work. \<^item> \<^emph>\Raw Output\ shows chunks of text from the \<^verbatim>\stdout\ and \<^verbatim>\stderr\ channels of the prover process. Recording of output starts with the first activation of the corresponding dockable window; earlier output is lost. The implicit stateful nature of physical I/O channels makes it difficult to relate raw output to the actual command from where it was originating. Parallel execution may add to the confusion. Peeking at physical process I/O is only the last resort to diagnose problems with tools that are not PIDE compliant. Under normal circumstances, prover output always works via managed message channels (corresponding to \<^ML>\writeln\, \<^ML>\warning\, \<^ML>\Output.error_message\ in Isabelle/ML), which are displayed by regular means within the document model (\secref{sec:output}). Unhandled Isabelle/ML exceptions are printed by the system via \<^ML>\Output.error_message\. \<^item> \<^emph>\Syslog\ shows system messages that might be relevant to diagnose problems with the startup or shutdown phase of the prover process; this also includes raw output on \<^verbatim>\stderr\. Isabelle/ML also provides an explicit \<^ML>\Output.system_message\ operation, which is occasionally useful for diagnostic purposes within the system infrastructure itself. A limited amount of syslog messages are buffered, independently of the docking state of the \<^emph>\Syslog\ panel. This allows to diagnose serious problems with Isabelle/PIDE process management, outside of the actual protocol layer. Under normal situations, such low-level system output can be ignored. \ chapter \Known problems and workarounds \label{sec:problems}\ text \ \<^item> \<^bold>\Problem:\ Keyboard shortcuts \<^verbatim>\C+PLUS\ and \<^verbatim>\C+MINUS\ for adjusting the editor font size depend on platform details and national keyboards. \<^bold>\Workaround:\ Rebind keys via \<^emph>\Global Options~/ Shortcuts\. \<^item> \<^bold>\Problem:\ The macOS key sequence \<^verbatim>\COMMAND+COMMA\ for application \<^emph>\Preferences\ is in conflict with the jEdit default keyboard shortcut for \<^emph>\Incremental Search Bar\ (action @{action_ref "quick-search"}). \<^bold>\Workaround:\ Rebind key via \<^emph>\Global Options~/ Shortcuts\ according to the national keyboard layout, e.g.\ \<^verbatim>\COMMAND+SLASH\ on English ones. \<^item> \<^bold>\Problem:\ On macOS Big Sur full-screen mode causes problems with dialog windows (e.g. \<^emph>\Search and Replace\ or \<^emph>\Hypersearch Results\). \<^bold>\Workaround:\ Go to \<^emph>\System Preferences / General\ and change the default ``\<^emph>\Prefer tabs: \<^bold>\in full screen\ when opening documents\'' to ``\<^emph>\\<^bold>\never\\''. \<^item> \<^bold>\Problem:\ On macOS with native Apple look-and-feel, some exotic national keyboards may cause a conflict of menu accelerator keys with regular jEdit key bindings. This leads to duplicate execution of the corresponding jEdit action. \<^bold>\Workaround:\ Disable the native Apple menu bar via Java runtime option \<^verbatim>\-Dapple.laf.useScreenMenuBar=false\. \<^item> \<^bold>\Problem:\ macOS system fonts sometimes lead to character drop-outs in the main text area. \<^bold>\Workaround:\ Use the default \<^verbatim>\Isabelle DejaVu\ fonts. \<^item> \<^bold>\Problem:\ On macOS the Java printer dialog sometimes does not work. \<^bold>\Workaround:\ Use action @{action isabelle.draft} and print via the Web browser. \<^item> \<^bold>\Problem:\ Antialiased text rendering may show bad performance or bad visual quality, notably on Linux/X11. \<^bold>\Workaround:\ The property \<^verbatim>\view.antiAlias\ (via menu item Utilities / Global Options / Text Area / Anti Aliased smooth text) has the main impact on text rendering, but some related properties may also change the behaviour. The default is \<^verbatim>\view.antiAlias=subpixel HRGB\: it can be much faster than \<^verbatim>\standard\, but occasionally causes problems with odd color shades. An alternative is to have \<^verbatim>\view.antiAlias=standard\ and set a Java system property like this:\<^footnote>\See also \<^url>\https://docs.oracle.com/javase/10/troubleshoot/java-2d-pipeline-rendering-and-properties.htm\.\ @{verbatim [display] \isabelle jedit -Dsun.java2d.opengl=true\} If this works reliably, it can be made persistent via @{setting JEDIT_JAVA_OPTIONS} within \<^path>\$ISABELLE_HOME_USER/etc/settings\. For the Isabelle desktop ``app'', there is a corresponding file with Java runtime options in the main directory (name depends on the OS platform). \<^item> \<^bold>\Problem:\ Some Linux/X11 input methods such as IBus tend to disrupt key event handling of Java/AWT/Swing. \<^bold>\Workaround:\ Do not use X11 input methods. Note that environment variable \<^verbatim>\XMODIFIERS\ is reset by default within Isabelle settings. \<^item> \<^bold>\Problem:\ Some Linux/X11 window managers that are not ``re-parenting'' cause problems with additional windows opened by Java. This affects either historic or neo-minimalistic window managers like \<^verbatim>\awesome\ or \<^verbatim>\xmonad\. \<^bold>\Workaround:\ Use a regular re-parenting X11 window manager. \<^item> \<^bold>\Problem:\ Various forks of Linux/X11 window managers and desktop environments (like Gnome) disrupt the handling of menu popups and mouse positions of Java/AWT/Swing. \<^bold>\Workaround:\ Use suitable version of Linux desktops. \<^item> \<^bold>\Problem:\ Full-screen mode via jEdit action @{action_ref "toggle-full-screen"} (default keyboard shortcut \<^verbatim>\F11\ or \<^verbatim>\S+F11\) works robustly on Windows, but not on macOS or various Linux/X11 window managers. For the latter platforms, it is approximated by educated guesses on the window size (excluding the macOS menu bar). \<^bold>\Workaround:\ Use native full-screen control of the macOS window manager, unless it is macOS 11.1 (Big Sur). \<^item> \<^bold>\Problem:\ Native full-screen mode on macOS 11.1 is incompatible with Java window management: it puts dialog windows (Search, Hypersearch, etc.) into an unusable state. \<^bold>\Workaround:\ use the approximative action @{action_ref "toggle-full-screen"}. \<^item> \<^bold>\Problem:\ Heap space of the JVM may fill up and render the Prover IDE unresponsive, e.g.\ when editing big Isabelle sessions with many theories. \<^bold>\Workaround:\ Increase JVM heap parameters by editing platform-specific files (for ``properties'' or ``options'') that are associated with the main app bundle. \ end diff --git a/src/HOL/Imperative_HOL/Array.thy b/src/HOL/Imperative_HOL/Array.thy --- a/src/HOL/Imperative_HOL/Array.thy +++ b/src/HOL/Imperative_HOL/Array.thy @@ -1,499 +1,499 @@ (* Title: HOL/Imperative_HOL/Array.thy Author: John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen *) section \Monadic arrays\ theory Array imports Heap_Monad begin subsection \Primitives\ definition present :: "heap \ 'a::heap array \ bool" where "present h a \ addr_of_array a < lim h" definition get :: "heap \ 'a::heap array \ 'a list" where "get h a = map from_nat (arrays h (TYPEREP('a)) (addr_of_array a))" definition set :: "'a::heap array \ 'a list \ heap \ heap" where "set a x = arrays_update (\h. h(TYPEREP('a) := ((h(TYPEREP('a))) (addr_of_array a:=map to_nat x))))" definition alloc :: "'a list \ heap \ 'a::heap array \ heap" where "alloc xs h = (let l = lim h; r = Array l; h'' = set r xs (h\lim := l + 1\) in (r, h''))" definition length :: "heap \ 'a::heap array \ nat" where "length h a = List.length (get h a)" definition update :: "'a::heap array \ nat \ 'a \ heap \ heap" where "update a i x h = set a ((get h a)[i:=x]) h" definition noteq :: "'a::heap array \ 'b::heap array \ bool" (infix "=!!=" 70) where "r =!!= s \ TYPEREP('a) \ TYPEREP('b) \ addr_of_array r \ addr_of_array s" subsection \Monad operations\ definition new :: "nat \ 'a::heap \ 'a array Heap" where [code del]: "new n x = Heap_Monad.heap (alloc (replicate n x))" definition of_list :: "'a::heap list \ 'a array Heap" where [code del]: "of_list xs = Heap_Monad.heap (alloc xs)" definition make :: "nat \ (nat \ 'a::heap) \ 'a array Heap" where [code del]: "make n f = Heap_Monad.heap (alloc (map f [0 ..< n]))" definition len :: "'a::heap array \ nat Heap" where [code del]: "len a = Heap_Monad.tap (\h. length h a)" definition nth :: "'a::heap array \ nat \ 'a Heap" where [code del]: "nth a i = Heap_Monad.guard (\h. i < length h a) (\h. (get h a ! i, h))" definition upd :: "nat \ 'a \ 'a::heap array \ 'a::heap array Heap" where [code del]: "upd i x a = Heap_Monad.guard (\h. i < length h a) (\h. (a, update a i x h))" definition map_entry :: "nat \ ('a::heap \ 'a) \ 'a array \ 'a array Heap" where [code del]: "map_entry i f a = Heap_Monad.guard (\h. i < length h a) (\h. (a, update a i (f (get h a ! i)) h))" definition swap :: "nat \ 'a \ 'a::heap array \ 'a Heap" where [code del]: "swap i x a = Heap_Monad.guard (\h. i < length h a) (\h. (get h a ! i, update a i x h))" definition freeze :: "'a::heap array \ 'a list Heap" where [code del]: "freeze a = Heap_Monad.tap (\h. get h a)" subsection \Properties\ text \FIXME: Does there exist a "canonical" array axiomatisation in the literature?\ text \Primitives\ lemma noteq_sym: "a =!!= b \ b =!!= a" and unequal [simp]: "a \ a' \ a =!!= a'" unfolding noteq_def by auto lemma noteq_irrefl: "r =!!= r \ False" unfolding noteq_def by auto lemma present_alloc_noteq: "present h a \ a =!!= fst (alloc xs h)" by (simp add: present_def noteq_def alloc_def Let_def) lemma get_set_eq [simp]: "get (set r x h) r = x" by (simp add: get_def set_def o_def) lemma get_set_neq [simp]: "r =!!= s \ get (set s x h) r = get h r" by (simp add: noteq_def get_def set_def) lemma set_same [simp]: "set r x (set r y h) = set r x h" by (simp add: set_def) lemma set_set_swap: "r =!!= r' \ set r x (set r' x' h) = set r' x' (set r x h)" by (simp add: Let_def fun_eq_iff noteq_def set_def) lemma get_update_eq [simp]: "get (update a i v h) a = (get h a) [i := v]" by (simp add: update_def) lemma nth_update_neq [simp]: "a =!!= b \ get (update b j v h) a ! i = get h a ! i" by (simp add: update_def noteq_def) lemma get_update_elem_neqIndex [simp]: "i \ j \ get (update a j v h) a ! i = get h a ! i" by simp lemma length_update [simp]: "length (update b i v h) = length h" by (simp add: update_def length_def set_def get_def fun_eq_iff) lemma update_swap_neq: "a =!!= a' \ update a i v (update a' i' v' h) = update a' i' v' (update a i v h)" apply (unfold update_def) apply simp apply (subst set_set_swap, assumption) apply (subst get_set_neq) apply (erule noteq_sym) apply simp done lemma update_swap_neqIndex: "\ i \ i' \ \ update a i v (update a i' v' h) = update a i' v' (update a i v h)" by (auto simp add: update_def set_set_swap list_update_swap) lemma get_alloc: "get (snd (alloc xs h)) (fst (alloc ys h)) = xs" by (simp add: Let_def split_def alloc_def) lemma length_alloc: "length (snd (alloc (xs :: 'a::heap list) h)) (fst (alloc (ys :: 'a list) h)) = List.length xs" by (simp add: Array.length_def get_alloc) lemma set: "set (fst (alloc ls h)) new_ls (snd (alloc ls h)) = snd (alloc new_ls h)" by (simp add: Let_def split_def alloc_def) lemma present_update [simp]: "present (update b i v h) = present h" by (simp add: update_def present_def set_def get_def fun_eq_iff) lemma present_alloc [simp]: "present (snd (alloc xs h)) (fst (alloc xs h))" by (simp add: present_def alloc_def set_def Let_def) lemma not_present_alloc [simp]: "\ present h (fst (alloc xs h))" by (simp add: present_def alloc_def Let_def) text \Monad operations\ lemma execute_new [execute_simps]: "execute (new n x) h = Some (alloc (replicate n x) h)" by (simp add: new_def execute_simps) lemma success_newI [success_intros]: "success (new n x) h" by (auto intro: success_intros simp add: new_def) lemma effect_newI [effect_intros]: assumes "(a, h') = alloc (replicate n x) h" shows "effect (new n x) h h' a" by (rule effectI) (simp add: assms execute_simps) lemma effect_newE [effect_elims]: assumes "effect (new n x) h h' r" obtains "r = fst (alloc (replicate n x) h)" "h' = snd (alloc (replicate n x) h)" "get h' r = replicate n x" "present h' r" "\ present h r" using assms by (rule effectE) (simp add: get_alloc execute_simps) lemma execute_of_list [execute_simps]: "execute (of_list xs) h = Some (alloc xs h)" by (simp add: of_list_def execute_simps) lemma success_of_listI [success_intros]: "success (of_list xs) h" by (auto intro: success_intros simp add: of_list_def) lemma effect_of_listI [effect_intros]: assumes "(a, h') = alloc xs h" shows "effect (of_list xs) h h' a" by (rule effectI) (simp add: assms execute_simps) lemma effect_of_listE [effect_elims]: assumes "effect (of_list xs) h h' r" obtains "r = fst (alloc xs h)" "h' = snd (alloc xs h)" "get h' r = xs" "present h' r" "\ present h r" using assms by (rule effectE) (simp add: get_alloc execute_simps) lemma execute_make [execute_simps]: "execute (make n f) h = Some (alloc (map f [0 ..< n]) h)" by (simp add: make_def execute_simps) lemma success_makeI [success_intros]: "success (make n f) h" by (auto intro: success_intros simp add: make_def) lemma effect_makeI [effect_intros]: assumes "(a, h') = alloc (map f [0 ..< n]) h" shows "effect (make n f) h h' a" by (rule effectI) (simp add: assms execute_simps) lemma effect_makeE [effect_elims]: assumes "effect (make n f) h h' r" obtains "r = fst (alloc (map f [0 ..< n]) h)" "h' = snd (alloc (map f [0 ..< n]) h)" "get h' r = map f [0 ..< n]" "present h' r" "\ present h r" using assms by (rule effectE) (simp add: get_alloc execute_simps) lemma execute_len [execute_simps]: "execute (len a) h = Some (length h a, h)" by (simp add: len_def execute_simps) lemma success_lenI [success_intros]: "success (len a) h" by (auto intro: success_intros simp add: len_def) lemma effect_lengthI [effect_intros]: assumes "h' = h" "r = length h a" shows "effect (len a) h h' r" by (rule effectI) (simp add: assms execute_simps) lemma effect_lengthE [effect_elims]: assumes "effect (len a) h h' r" obtains "r = length h' a" "h' = h" using assms by (rule effectE) (simp add: execute_simps) lemma execute_nth [execute_simps]: "i < length h a \ execute (nth a i) h = Some (get h a ! i, h)" "i \ length h a \ execute (nth a i) h = None" by (simp_all add: nth_def execute_simps) lemma success_nthI [success_intros]: "i < length h a \ success (nth a i) h" by (auto intro: success_intros simp add: nth_def) lemma effect_nthI [effect_intros]: assumes "i < length h a" "h' = h" "r = get h a ! i" shows "effect (nth a i) h h' r" by (rule effectI) (insert assms, simp add: execute_simps) lemma effect_nthE [effect_elims]: assumes "effect (nth a i) h h' r" obtains "i < length h a" "r = get h a ! i" "h' = h" using assms by (rule effectE) (cases "i < length h a", auto simp: execute_simps elim: successE) lemma execute_upd [execute_simps]: "i < length h a \ execute (upd i x a) h = Some (a, update a i x h)" "i \ length h a \ execute (upd i x a) h = None" by (simp_all add: upd_def execute_simps) lemma success_updI [success_intros]: "i < length h a \ success (upd i x a) h" by (auto intro: success_intros simp add: upd_def) lemma effect_updI [effect_intros]: assumes "i < length h a" "h' = update a i v h" shows "effect (upd i v a) h h' a" by (rule effectI) (insert assms, simp add: execute_simps) lemma effect_updE [effect_elims]: assumes "effect (upd i v a) h h' r" obtains "r = a" "h' = update a i v h" "i < length h a" using assms by (rule effectE) (cases "i < length h a", auto simp: execute_simps elim: successE) lemma execute_map_entry [execute_simps]: "i < length h a \ execute (map_entry i f a) h = Some (a, update a i (f (get h a ! i)) h)" "i \ length h a \ execute (map_entry i f a) h = None" by (simp_all add: map_entry_def execute_simps) lemma success_map_entryI [success_intros]: "i < length h a \ success (map_entry i f a) h" by (auto intro: success_intros simp add: map_entry_def) lemma effect_map_entryI [effect_intros]: assumes "i < length h a" "h' = update a i (f (get h a ! i)) h" "r = a" shows "effect (map_entry i f a) h h' r" by (rule effectI) (insert assms, simp add: execute_simps) lemma effect_map_entryE [effect_elims]: assumes "effect (map_entry i f a) h h' r" obtains "r = a" "h' = update a i (f (get h a ! i)) h" "i < length h a" using assms by (rule effectE) (cases "i < length h a", auto simp: execute_simps elim: successE) lemma execute_swap [execute_simps]: "i < length h a \ execute (swap i x a) h = Some (get h a ! i, update a i x h)" "i \ length h a \ execute (swap i x a) h = None" by (simp_all add: swap_def execute_simps) lemma success_swapI [success_intros]: "i < length h a \ success (swap i x a) h" by (auto intro: success_intros simp add: swap_def) lemma effect_swapI [effect_intros]: assumes "i < length h a" "h' = update a i x h" "r = get h a ! i" shows "effect (swap i x a) h h' r" by (rule effectI) (insert assms, simp add: execute_simps) lemma effect_swapE [effect_elims]: assumes "effect (swap i x a) h h' r" obtains "r = get h a ! i" "h' = update a i x h" "i < length h a" using assms by (rule effectE) (cases "i < length h a", auto simp: execute_simps elim: successE) lemma execute_freeze [execute_simps]: "execute (freeze a) h = Some (get h a, h)" by (simp add: freeze_def execute_simps) lemma success_freezeI [success_intros]: "success (freeze a) h" by (auto intro: success_intros simp add: freeze_def) lemma effect_freezeI [effect_intros]: assumes "h' = h" "r = get h a" shows "effect (freeze a) h h' r" by (rule effectI) (insert assms, simp add: execute_simps) lemma effect_freezeE [effect_elims]: assumes "effect (freeze a) h h' r" obtains "h' = h" "r = get h a" using assms by (rule effectE) (simp add: execute_simps) lemma upd_return: "upd i x a \ return a = upd i x a" by (rule Heap_eqI) (simp add: bind_def guard_def upd_def execute_simps) lemma array_make: "new n x = make n (\_. x)" by (rule Heap_eqI) (simp add: map_replicate_trivial execute_simps) lemma array_of_list_make [code]: "of_list xs = make (List.length xs) (\n. xs ! n)" by (rule Heap_eqI) (simp add: map_nth execute_simps) hide_const (open) present get set alloc length update noteq new of_list make len nth upd map_entry swap freeze subsection \Code generator setup\ subsubsection \Logical intermediate layer\ definition new' where [code del]: "new' = Array.new o nat_of_integer" lemma [code]: "Array.new = new' o of_nat" by (simp add: new'_def o_def) definition make' where [code del]: "make' i f = Array.make (nat_of_integer i) (f o of_nat)" lemma [code]: "Array.make n f = make' (of_nat n) (f o nat_of_integer)" by (simp add: make'_def o_def) definition len' where [code del]: "len' a = Array.len a \ (\n. return (of_nat n))" lemma [code]: "Array.len a = len' a \ (\i. return (nat_of_integer i))" by (simp add: len'_def) definition nth' where [code del]: "nth' a = Array.nth a o nat_of_integer" lemma [code]: "Array.nth a n = nth' a (of_nat n)" by (simp add: nth'_def) definition upd' where [code del]: "upd' a i x = Array.upd (nat_of_integer i) x a \ return ()" lemma [code]: "Array.upd i x a = upd' a (of_nat i) x \ return a" by (simp add: upd'_def upd_return) lemma [code]: "Array.map_entry i f a = do { x \ Array.nth a i; Array.upd i (f x) a }" by (rule Heap_eqI) (simp add: bind_def guard_def map_entry_def execute_simps) lemma [code]: "Array.swap i x a = do { y \ Array.nth a i; Array.upd i x a; return y }" by (rule Heap_eqI) (simp add: bind_def guard_def swap_def execute_simps) lemma [code]: "Array.freeze a = do { n \ Array.len a; Heap_Monad.fold_map (\i. Array.nth a i) [0..x. fst (the (if x < Array.length h a then Some (Array.get h a ! x, h) else None))) [0.. Array.len a; Heap_Monad.fold_map (Array.nth a) [0.. Array.len a; Heap_Monad.fold_map (Array.nth a) [0..SML\ code_printing type_constructor array \ (SML) "_/ array" code_printing constant Array \ (SML) "raise/ (Fail/ \"bare Array\")" code_printing constant Array.new' \ (SML) "(fn/ ()/ =>/ Array.array/ (IntInf.toInt _,/ (_)))" code_printing constant Array.of_list \ (SML) "(fn/ ()/ =>/ Array.fromList/ _)" code_printing constant Array.make' \ (SML) "(fn/ ()/ =>/ Array.tabulate/ (IntInf.toInt _,/ _ o IntInf.fromInt))" code_printing constant Array.len' \ (SML) "(fn/ ()/ =>/ IntInf.fromInt (Array.length/ _))" code_printing constant Array.nth' \ (SML) "(fn/ ()/ =>/ Array.sub/ ((_),/ IntInf.toInt _))" code_printing constant Array.upd' \ (SML) "(fn/ ()/ =>/ Array.update/ ((_),/ IntInf.toInt _,/ (_)))" code_printing constant "HOL.equal :: 'a array \ 'a array \ bool" \ (SML) infixl 6 "=" code_reserved SML Array text \OCaml\ code_printing type_constructor array \ (OCaml) "_/ array" code_printing constant Array \ (OCaml) "failwith/ \"bare Array\"" code_printing constant Array.new' \ (OCaml) "(fun/ ()/ ->/ Array.make/ (Z.to'_int/ _)/ _)" code_printing constant Array.of_list \ (OCaml) "(fun/ ()/ ->/ Array.of'_list/ _)" code_printing constant Array.make' \ (OCaml) "(fun/ ()/ ->/ Array.init/ (Z.to'_int/ _)/ (fun k'_ ->/ _/ (Z.of'_int/ k'_)))" code_printing constant Array.len' \ (OCaml) "(fun/ ()/ ->/ Z.of'_int/ (Array.length/ _))" code_printing constant Array.nth' \ (OCaml) "(fun/ ()/ ->/ Array.get/ _/ (Z.to'_int/ _))" code_printing constant Array.upd' \ (OCaml) "(fun/ ()/ ->/ Array.set/ _/ (Z.to'_int/ _)/ _)" code_printing constant "HOL.equal :: 'a array \ 'a array \ bool" \ (OCaml) infixl 4 "=" code_reserved OCaml Array text \Haskell\ code_printing type_constructor array \ (Haskell) "Heap.STArray/ Heap.RealWorld/ _" code_printing constant Array \ (Haskell) "error/ \"bare Array\"" code_printing constant Array.new' \ (Haskell) "Heap.newArray" code_printing constant Array.of_list \ (Haskell) "Heap.newListArray" code_printing constant Array.make' \ (Haskell) "Heap.newFunArray" code_printing constant Array.len' \ (Haskell) "Heap.lengthArray" code_printing constant Array.nth' \ (Haskell) "Heap.readArray" code_printing constant Array.upd' \ (Haskell) "Heap.writeArray" code_printing constant "HOL.equal :: 'a array \ 'a array \ bool" \ (Haskell) infix 4 "==" code_printing class_instance array :: HOL.equal \ (Haskell) - text \Scala\ -code_printing type_constructor array \ (Scala) "!collection.mutable.ArraySeq[_]" +code_printing type_constructor array \ (Scala) "!Array.T[_]" code_printing constant Array \ (Scala) "!sys.error(\"bare Array\")" code_printing constant Array.new' \ (Scala) "('_: Unit)/ => / Array.alloc((_))((_))" code_printing constant Array.make' \ (Scala) "('_: Unit)/ =>/ Array.make((_))((_))" code_printing constant Array.len' \ (Scala) "('_: Unit)/ =>/ Array.len((_))" code_printing constant Array.nth' \ (Scala) "('_: Unit)/ =>/ Array.nth((_), (_))" code_printing constant Array.upd' \ (Scala) "('_: Unit)/ =>/ Array.upd((_), (_), (_))" code_printing constant Array.freeze \ (Scala) "('_: Unit)/ =>/ Array.freeze((_))" code_printing constant "HOL.equal :: 'a array \ 'a array \ bool" \ (Scala) infixl 5 "==" end diff --git a/src/HOL/Imperative_HOL/Heap_Monad.thy b/src/HOL/Imperative_HOL/Heap_Monad.thy --- a/src/HOL/Imperative_HOL/Heap_Monad.thy +++ b/src/HOL/Imperative_HOL/Heap_Monad.thy @@ -1,693 +1,702 @@ (* Title: HOL/Imperative_HOL/Heap_Monad.thy Author: John Matthews, Galois Connections; Alexander Krauss, Lukas Bulwahn & Florian Haftmann, TU Muenchen *) section \A monad with a polymorphic heap and primitive reasoning infrastructure\ theory Heap_Monad imports Heap "HOL-Library.Monad_Syntax" begin subsection \The monad\ subsubsection \Monad construction\ text \Monadic heap actions either produce values and transform the heap, or fail\ datatype 'a Heap = Heap "heap \ ('a \ heap) option" declare [[code drop: "Code_Evaluation.term_of :: 'a::typerep Heap \ Code_Evaluation.term"]] primrec execute :: "'a Heap \ heap \ ('a \ heap) option" where [code del]: "execute (Heap f) = f" lemma Heap_cases [case_names succeed fail]: fixes f and h assumes succeed: "\x h'. execute f h = Some (x, h') \ P" assumes fail: "execute f h = None \ P" shows P using assms by (cases "execute f h") auto lemma Heap_execute [simp]: "Heap (execute f) = f" by (cases f) simp_all lemma Heap_eqI: "(\h. execute f h = execute g h) \ f = g" by (cases f, cases g) (auto simp: fun_eq_iff) named_theorems execute_simps "simplification rules for execute" lemma execute_Let [execute_simps]: "execute (let x = t in f x) = (let x = t in execute (f x))" by (simp add: Let_def) subsubsection \Specialised lifters\ definition tap :: "(heap \ 'a) \ 'a Heap" where [code del]: "tap f = Heap (\h. Some (f h, h))" lemma execute_tap [execute_simps]: "execute (tap f) h = Some (f h, h)" by (simp add: tap_def) definition heap :: "(heap \ 'a \ heap) \ 'a Heap" where [code del]: "heap f = Heap (Some \ f)" lemma execute_heap [execute_simps]: "execute (heap f) = Some \ f" by (simp add: heap_def) definition guard :: "(heap \ bool) \ (heap \ 'a \ heap) \ 'a Heap" where [code del]: "guard P f = Heap (\h. if P h then Some (f h) else None)" lemma execute_guard [execute_simps]: "\ P h \ execute (guard P f) h = None" "P h \ execute (guard P f) h = Some (f h)" by (simp_all add: guard_def) subsubsection \Predicate classifying successful computations\ definition success :: "'a Heap \ heap \ bool" where "success f h \ execute f h \ None" lemma successI: "execute f h \ None \ success f h" by (simp add: success_def) lemma successE: assumes "success f h" obtains r h' where "execute f h = Some (r, h')" using assms by (auto simp: success_def) named_theorems success_intros "introduction rules for success" lemma success_tapI [success_intros]: "success (tap f) h" by (rule successI) (simp add: execute_simps) lemma success_heapI [success_intros]: "success (heap f) h" by (rule successI) (simp add: execute_simps) lemma success_guardI [success_intros]: "P h \ success (guard P f) h" by (rule successI) (simp add: execute_guard) lemma success_LetI [success_intros]: "x = t \ success (f x) h \ success (let x = t in f x) h" by (simp add: Let_def) lemma success_ifI: "(c \ success t h) \ (\ c \ success e h) \ success (if c then t else e) h" by (simp add: success_def) subsubsection \Predicate for a simple relational calculus\ text \ The \effect\ predicate states that when a computation \c\ runs with the heap \h\ will result in return value \r\ and a heap \h'\, i.e.~no exception occurs. \ definition effect :: "'a Heap \ heap \ heap \ 'a \ bool" where effect_def: "effect c h h' r \ execute c h = Some (r, h')" lemma effectI: "execute c h = Some (r, h') \ effect c h h' r" by (simp add: effect_def) lemma effectE: assumes "effect c h h' r" obtains "r = fst (the (execute c h))" and "h' = snd (the (execute c h))" and "success c h" proof (rule that) from assms have *: "execute c h = Some (r, h')" by (simp add: effect_def) then show "success c h" by (simp add: success_def) from * have "fst (the (execute c h)) = r" and "snd (the (execute c h)) = h'" by simp_all then show "r = fst (the (execute c h))" and "h' = snd (the (execute c h))" by simp_all qed lemma effect_success: "effect c h h' r \ success c h" by (simp add: effect_def success_def) lemma success_effectE: assumes "success c h" obtains r h' where "effect c h h' r" using assms by (auto simp add: effect_def success_def) lemma effect_deterministic: assumes "effect f h h' a" and "effect f h h'' b" shows "a = b" and "h' = h''" using assms unfolding effect_def by auto named_theorems effect_intros "introduction rules for effect" and effect_elims "elimination rules for effect" lemma effect_LetI [effect_intros]: assumes "x = t" "effect (f x) h h' r" shows "effect (let x = t in f x) h h' r" using assms by simp lemma effect_LetE [effect_elims]: assumes "effect (let x = t in f x) h h' r" obtains "effect (f t) h h' r" using assms by simp lemma effect_ifI: assumes "c \ effect t h h' r" and "\ c \ effect e h h' r" shows "effect (if c then t else e) h h' r" by (cases c) (simp_all add: assms) lemma effect_ifE: assumes "effect (if c then t else e) h h' r" obtains "c" "effect t h h' r" | "\ c" "effect e h h' r" using assms by (cases c) simp_all lemma effect_tapI [effect_intros]: assumes "h' = h" "r = f h" shows "effect (tap f) h h' r" by (rule effectI) (simp add: assms execute_simps) lemma effect_tapE [effect_elims]: assumes "effect (tap f) h h' r" obtains "h' = h" and "r = f h" using assms by (rule effectE) (auto simp add: execute_simps) lemma effect_heapI [effect_intros]: assumes "h' = snd (f h)" "r = fst (f h)" shows "effect (heap f) h h' r" by (rule effectI) (simp add: assms execute_simps) lemma effect_heapE [effect_elims]: assumes "effect (heap f) h h' r" obtains "h' = snd (f h)" and "r = fst (f h)" using assms by (rule effectE) (simp add: execute_simps) lemma effect_guardI [effect_intros]: assumes "P h" "h' = snd (f h)" "r = fst (f h)" shows "effect (guard P f) h h' r" by (rule effectI) (simp add: assms execute_simps) lemma effect_guardE [effect_elims]: assumes "effect (guard P f) h h' r" obtains "h' = snd (f h)" "r = fst (f h)" "P h" using assms by (rule effectE) (auto simp add: execute_simps elim!: successE, cases "P h", auto simp add: execute_simps) subsubsection \Monad combinators\ definition return :: "'a \ 'a Heap" where [code del]: "return x = heap (Pair x)" lemma execute_return [execute_simps]: "execute (return x) = Some \ Pair x" by (simp add: return_def execute_simps) lemma success_returnI [success_intros]: "success (return x) h" by (rule successI) (simp add: execute_simps) lemma effect_returnI [effect_intros]: "h = h' \ effect (return x) h h' x" by (rule effectI) (simp add: execute_simps) lemma effect_returnE [effect_elims]: assumes "effect (return x) h h' r" obtains "r = x" "h' = h" using assms by (rule effectE) (simp add: execute_simps) definition raise :: "String.literal \ 'a Heap" \ \the literal is just decoration\ where "raise s = Heap (\_. None)" code_datatype raise \ \avoid \<^const>\Heap\ formally\ lemma execute_raise [execute_simps]: "execute (raise s) = (\_. None)" by (simp add: raise_def) lemma effect_raiseE [effect_elims]: assumes "effect (raise x) h h' r" obtains "False" using assms by (rule effectE) (simp add: success_def execute_simps) definition bind :: "'a Heap \ ('a \ 'b Heap) \ 'b Heap" where [code del]: "bind f g = Heap (\h. case execute f h of Some (x, h') \ execute (g x) h' | None \ None)" adhoc_overloading Monad_Syntax.bind Heap_Monad.bind lemma execute_bind [execute_simps]: "execute f h = Some (x, h') \ execute (f \ g) h = execute (g x) h'" "execute f h = None \ execute (f \ g) h = None" by (simp_all add: bind_def) lemma execute_bind_case: "execute (f \ g) h = (case (execute f h) of Some (x, h') \ execute (g x) h' | None \ None)" by (simp add: bind_def) lemma execute_bind_success: "success f h \ execute (f \ g) h = execute (g (fst (the (execute f h)))) (snd (the (execute f h)))" by (cases f h rule: Heap_cases) (auto elim: successE simp add: bind_def) lemma success_bind_executeI: "execute f h = Some (x, h') \ success (g x) h' \ success (f \ g) h" by (auto intro!: successI elim: successE simp add: bind_def) lemma success_bind_effectI [success_intros]: "effect f h h' x \ success (g x) h' \ success (f \ g) h" by (auto simp add: effect_def success_def bind_def) lemma effect_bindI [effect_intros]: assumes "effect f h h' r" "effect (g r) h' h'' r'" shows "effect (f \ g) h h'' r'" using assms apply (auto intro!: effectI elim!: effectE successE) apply (subst execute_bind, simp_all) done lemma effect_bindE [effect_elims]: assumes "effect (f \ g) h h'' r'" obtains h' r where "effect f h h' r" "effect (g r) h' h'' r'" using assms by (auto simp add: effect_def bind_def split: option.split_asm) lemma execute_bind_eq_SomeI: assumes "execute f h = Some (x, h')" and "execute (g x) h' = Some (y, h'')" shows "execute (f \ g) h = Some (y, h'')" using assms by (simp add: bind_def) lemma return_bind [simp]: "return x \ f = f x" by (rule Heap_eqI) (simp add: execute_simps) lemma bind_return [simp]: "f \ return = f" by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits) lemma bind_bind [simp]: "(f \ g) \ k = (f :: 'a Heap) \ (\x. g x \ k)" by (rule Heap_eqI) (simp add: bind_def execute_simps split: option.splits) lemma raise_bind [simp]: "raise e \ f = raise e" by (rule Heap_eqI) (simp add: execute_simps) subsection \Generic combinators\ subsubsection \Assertions\ definition assert :: "('a \ bool) \ 'a \ 'a Heap" where "assert P x = (if P x then return x else raise STR ''assert'')" lemma execute_assert [execute_simps]: "P x \ execute (assert P x) h = Some (x, h)" "\ P x \ execute (assert P x) h = None" by (simp_all add: assert_def execute_simps) lemma success_assertI [success_intros]: "P x \ success (assert P x) h" by (rule successI) (simp add: execute_assert) lemma effect_assertI [effect_intros]: "P x \ h' = h \ r = x \ effect (assert P x) h h' r" by (rule effectI) (simp add: execute_assert) lemma effect_assertE [effect_elims]: assumes "effect (assert P x) h h' r" obtains "P x" "r = x" "h' = h" using assms by (rule effectE) (cases "P x", simp_all add: execute_assert success_def) lemma assert_cong [fundef_cong]: assumes "P = P'" assumes "\x. P' x \ f x = f' x" shows "(assert P x \ f) = (assert P' x \ f')" by (rule Heap_eqI) (insert assms, simp add: assert_def) subsubsection \Plain lifting\ definition lift :: "('a \ 'b) \ 'a \ 'b Heap" where "lift f = return o f" lemma lift_collapse [simp]: "lift f x = return (f x)" by (simp add: lift_def) lemma bind_lift: "(f \ lift g) = (f \ (\x. return (g x)))" by (simp add: lift_def comp_def) subsubsection \Iteration -- warning: this is rarely useful!\ primrec fold_map :: "('a \ 'b Heap) \ 'a list \ 'b list Heap" where "fold_map f [] = return []" | "fold_map f (x # xs) = do { y \ f x; ys \ fold_map f xs; return (y # ys) }" lemma fold_map_append: "fold_map f (xs @ ys) = fold_map f xs \ (\xs. fold_map f ys \ (\ys. return (xs @ ys)))" by (induct xs) simp_all lemma execute_fold_map_unchanged_heap [execute_simps]: assumes "\x. x \ set xs \ \y. execute (f x) h = Some (y, h)" shows "execute (fold_map f xs) h = Some (List.map (\x. fst (the (execute (f x) h))) xs, h)" using assms proof (induct xs) case Nil show ?case by (simp add: execute_simps) next case (Cons x xs) from Cons.prems obtain y where y: "execute (f x) h = Some (y, h)" by auto moreover from Cons.prems Cons.hyps have "execute (fold_map f xs) h = Some (map (\x. fst (the (execute (f x) h))) xs, h)" by auto ultimately show ?case by (simp, simp only: execute_bind(1), simp add: execute_simps) qed subsection \Partial function definition setup\ definition Heap_ord :: "'a Heap \ 'a Heap \ bool" where "Heap_ord = img_ord execute (fun_ord option_ord)" definition Heap_lub :: "'a Heap set \ 'a Heap" where "Heap_lub = img_lub execute Heap (fun_lub (flat_lub None))" lemma Heap_lub_empty: "Heap_lub {} = Heap Map.empty" by(simp add: Heap_lub_def img_lub_def fun_lub_def flat_lub_def) lemma heap_interpretation: "partial_function_definitions Heap_ord Heap_lub" proof - have "partial_function_definitions (fun_ord option_ord) (fun_lub (flat_lub None))" by (rule partial_function_lift) (rule flat_interpretation) then have "partial_function_definitions (img_ord execute (fun_ord option_ord)) (img_lub execute Heap (fun_lub (flat_lub None)))" by (rule partial_function_image) (auto intro: Heap_eqI) then show "partial_function_definitions Heap_ord Heap_lub" by (simp only: Heap_ord_def Heap_lub_def) qed interpretation heap: partial_function_definitions Heap_ord Heap_lub rewrites "Heap_lub {} \ Heap Map.empty" by (fact heap_interpretation)(simp add: Heap_lub_empty) lemma heap_step_admissible: "option.admissible (\f:: 'a => ('b * 'c) option. \h h' r. f h = Some (r, h') \ P x h h' r)" proof (rule ccpo.admissibleI) fix A :: "('a \ ('b * 'c) option) set" assume ch: "Complete_Partial_Order.chain option.le_fun A" and IH: "\f\A. \h h' r. f h = Some (r, h') \ P x h h' r" from ch have ch': "\x. Complete_Partial_Order.chain option_ord {y. \f\A. y = f x}" by (rule chain_fun) show "\h h' r. option.lub_fun A h = Some (r, h') \ P x h h' r" proof (intro allI impI) fix h h' r assume "option.lub_fun A h = Some (r, h')" from flat_lub_in_chain[OF ch' this[unfolded fun_lub_def]] have "Some (r, h') \ {y. \f\A. y = f h}" by simp then have "\f\A. f h = Some (r, h')" by auto with IH show "P x h h' r" by auto qed qed lemma admissible_heap: "heap.admissible (\f. \x h h' r. effect (f x) h h' r \ P x h h' r)" proof (rule admissible_fun[OF heap_interpretation]) fix x show "ccpo.admissible Heap_lub Heap_ord (\a. \h h' r. effect a h h' r \ P x h h' r)" unfolding Heap_ord_def Heap_lub_def proof (intro admissible_image partial_function_lift flat_interpretation) show "option.admissible ((\a. \h h' r. effect a h h' r \ P x h h' r) \ Heap)" unfolding comp_def effect_def execute.simps by (rule heap_step_admissible) qed (auto simp add: Heap_eqI) qed lemma fixp_induct_heap: fixes F :: "'c \ 'c" and U :: "'c \ 'b \ 'a Heap" and C :: "('b \ 'a Heap) \ 'c" and P :: "'b \ heap \ heap \ 'a \ bool" assumes mono: "\x. monotone (fun_ord Heap_ord) Heap_ord (\f. U (F (C f)) x)" assumes eq: "f \ C (ccpo.fixp (fun_lub Heap_lub) (fun_ord Heap_ord) (\f. U (F (C f))))" assumes inverse2: "\f. U (C f) = f" assumes step: "\f x h h' r. (\x h h' r. effect (U f x) h h' r \ P x h h' r) \ effect (U (F f) x) h h' r \ P x h h' r" assumes defined: "effect (U f x) h h' r" shows "P x h h' r" using step defined heap.fixp_induct_uc[of U F C, OF mono eq inverse2 admissible_heap, of P] unfolding effect_def execute.simps by blast declaration \Partial_Function.init "heap" \<^term>\heap.fixp_fun\ \<^term>\heap.mono_body\ @{thm heap.fixp_rule_uc} @{thm heap.fixp_induct_uc} (SOME @{thm fixp_induct_heap})\ abbreviation "mono_Heap \ monotone (fun_ord Heap_ord) Heap_ord" lemma Heap_ordI: assumes "\h. execute x h = None \ execute x h = execute y h" shows "Heap_ord x y" using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def by blast lemma Heap_ordE: assumes "Heap_ord x y" obtains "execute x h = None" | "execute x h = execute y h" using assms unfolding Heap_ord_def img_ord_def fun_ord_def flat_ord_def by atomize_elim blast lemma bind_mono [partial_function_mono]: assumes mf: "mono_Heap B" and mg: "\y. mono_Heap (\f. C y f)" shows "mono_Heap (\f. B f \ (\y. C y f))" proof (rule monotoneI) fix f g :: "'a \ 'b Heap" assume fg: "fun_ord Heap_ord f g" from mf have 1: "Heap_ord (B f) (B g)" by (rule monotoneD) (rule fg) from mg have 2: "\y'. Heap_ord (C y' f) (C y' g)" by (rule monotoneD) (rule fg) have "Heap_ord (B f \ (\y. C y f)) (B g \ (\y. C y f))" (is "Heap_ord ?L ?R") proof (rule Heap_ordI) fix h from 1 show "execute ?L h = None \ execute ?L h = execute ?R h" by (rule Heap_ordE[where h = h]) (auto simp: execute_bind_case) qed also have "Heap_ord (B g \ (\y'. C y' f)) (B g \ (\y'. C y' g))" (is "Heap_ord ?L ?R") proof (rule Heap_ordI) fix h show "execute ?L h = None \ execute ?L h = execute ?R h" proof (cases "execute (B g) h") case None then have "execute ?L h = None" by (auto simp: execute_bind_case) thus ?thesis .. next case Some then obtain r h' where "execute (B g) h = Some (r, h')" by (metis surjective_pairing) then have "execute ?L h = execute (C r f) h'" "execute ?R h = execute (C r g) h'" by (auto simp: execute_bind_case) with 2[of r] show ?thesis by (auto elim: Heap_ordE) qed qed finally (heap.leq_trans) show "Heap_ord (B f \ (\y. C y f)) (B g \ (\y'. C y' g))" . qed subsection \Code generator setup\ subsubsection \SML and OCaml\ code_printing type_constructor Heap \ (SML) "(unit/ ->/ _)" code_printing constant bind \ (SML) "!(fn/ f'_/ =>/ fn/ ()/ =>/ f'_/ (_/ ())/ ())" code_printing constant return \ (SML) "!(fn/ ()/ =>/ _)" code_printing constant Heap_Monad.raise \ (SML) "!(raise/ Fail/ _)" code_printing type_constructor Heap \ (OCaml) "(unit/ ->/ _)" code_printing constant bind \ (OCaml) "!(fun/ f'_/ ()/ ->/ f'_/ (_/ ())/ ())" code_printing constant return \ (OCaml) "!(fun/ ()/ ->/ _)" code_printing constant Heap_Monad.raise \ (OCaml) "failwith" subsubsection \Haskell\ text \Adaption layer\ code_printing code_module "Heap" \ (Haskell) \ module Heap(ST, RealWorld, STRef, newSTRef, readSTRef, writeSTRef, STArray, newArray, newListArray, newFunArray, lengthArray, readArray, writeArray) where import Control.Monad(liftM) import Control.Monad.ST(RealWorld, ST) import Data.STRef(STRef, newSTRef, readSTRef, writeSTRef) import qualified Data.Array.ST type STArray s a = Data.Array.ST.STArray s Integer a newArray :: Integer -> a -> ST s (STArray s a) newArray k = Data.Array.ST.newArray (0, k - 1) newListArray :: [a] -> ST s (STArray s a) newListArray xs = Data.Array.ST.newListArray (0, (fromInteger . toInteger . length) xs - 1) xs newFunArray :: Integer -> (Integer -> a) -> ST s (STArray s a) newFunArray k f = Data.Array.ST.newListArray (0, k - 1) (map f [0..k-1]) lengthArray :: STArray s a -> ST s Integer lengthArray a = liftM (\(_, l) -> l + 1) (Data.Array.ST.getBounds a) readArray :: STArray s a -> Integer -> ST s a readArray = Data.Array.ST.readArray writeArray :: STArray s a -> Integer -> a -> ST s () writeArray = Data.Array.ST.writeArray\ code_reserved Haskell Heap text \Monad\ code_printing type_constructor Heap \ (Haskell) "Heap.ST/ Heap.RealWorld/ _" code_monad bind Haskell code_printing constant return \ (Haskell) "return" code_printing constant Heap_Monad.raise \ (Haskell) "error" subsubsection \Scala\ code_printing code_module "Heap" \ (Scala) \object Heap { - def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g (f ()) () + def bind[A, B](f: Unit => A, g: A => Unit => B): Unit => B = (_: Unit) => g(f(()))(()) } class Ref[A](x: A) { var value = x } object Ref { def apply[A](x: A): Ref[A] = new Ref[A](x) def lookup[A](r: Ref[A]): A = r.value def update[A](r: Ref[A], x: A): Unit = { r.value = x } } object Array { - import collection.mutable.ArraySeq - def alloc[A](n: BigInt)(x: A): ArraySeq[A] = - ArraySeq.fill(n.toInt)(x) - def make[A](n: BigInt)(f: BigInt => A): ArraySeq[A] = - ArraySeq.tabulate(n.toInt)((k: Int) => f(BigInt(k))) - def len[A](a: ArraySeq[A]): BigInt = - BigInt(a.length) - def nth[A](a: ArraySeq[A], n: BigInt): A = - a(n.toInt) - def upd[A](a: ArraySeq[A], n: BigInt, x: A): Unit = - a.update(n.toInt, x) - def freeze[A](a: ArraySeq[A]): List[A] = - a.toList + class T[A](n: Int) + { + val array: Array[AnyRef] = new Array[AnyRef](n) + def apply(i: Int): A = array(i).asInstanceOf[A] + def update(i: Int, x: A): Unit = array(i) = x.asInstanceOf[AnyRef] + def length: Int = array.length + def toList: List[A] = array.toList.asInstanceOf[List[A]] + override def toString: String = array.mkString("Array.T(", ",", ")") + } + def make[A](n: BigInt)(f: BigInt => A): T[A] = + { + val m = n.toInt + val a = new T[A](m) + for (i <- 0 until m) a(i) = f(i) + a + } + def alloc[A](n: BigInt)(x: A): T[A] = make(n)(_ => x) + def len[A](a: T[A]): BigInt = BigInt(a.length) + def nth[A](a: T[A], n: BigInt): A = a(n.toInt) + def upd[A](a: T[A], n: BigInt, x: A): Unit = a.update(n.toInt, x) + def freeze[A](a: T[A]): List[A] = a.toList } + \ code_reserved Scala Heap Ref Array code_printing type_constructor Heap \ (Scala) "(Unit/ =>/ _)" code_printing constant bind \ (Scala) "Heap.bind" code_printing constant return \ (Scala) "('_: Unit)/ =>/ _" code_printing constant Heap_Monad.raise \ (Scala) "!sys.error((_))" subsubsection \Target variants with less units\ setup \ let open Code_Thingol; val imp_program = let val is_bind = curry (=) \<^const_name>\bind\; val is_return = curry (=) \<^const_name>\return\; val dummy_name = ""; val dummy_case_term = IVar NONE; (*assumption: dummy values are not relevant for serialization*) val unitT = \<^type_name>\unit\ `%% []; val unitt = IConst { sym = Code_Symbol.Constant \<^const_name>\Unity\, typargs = [], dicts = [], dom = [], annotation = NONE }; fun dest_abs ((v, ty) `|=> t, _) = ((v, ty), t) | dest_abs (t, ty) = let val vs = fold_varnames cons t []; val v = singleton (Name.variant_list vs) "x"; val ty' = (hd o fst o unfold_fun) ty; in ((SOME v, ty'), t `$ IVar (SOME v)) end; fun force (t as IConst { sym = Code_Symbol.Constant c, ... } `$ t') = if is_return c then t' else t `$ unitt | force t = t `$ unitt; fun tr_bind'' [(t1, _), (t2, ty2)] = let val ((v, ty), t) = dest_abs (t2, ty2); in ICase { term = force t1, typ = ty, clauses = [(IVar v, tr_bind' t)], primitive = dummy_case_term } end and tr_bind' t = case unfold_app t of (IConst { sym = Code_Symbol.Constant c, dom = ty1 :: ty2 :: _, ... }, [x1, x2]) => if is_bind c then tr_bind'' [(x1, ty1), (x2, ty2)] else force t | _ => force t; fun imp_monad_bind'' ts = (SOME dummy_name, unitT) `|=> ICase { term = IVar (SOME dummy_name), typ = unitT, clauses = [(unitt, tr_bind'' ts)], primitive = dummy_case_term } fun imp_monad_bind' (const as { sym = Code_Symbol.Constant c, dom = dom, ... }) ts = if is_bind c then case (ts, dom) of ([t1, t2], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] | ([t1, t2, t3], ty1 :: ty2 :: _) => imp_monad_bind'' [(t1, ty1), (t2, ty2)] `$ t3 | (ts, _) => imp_monad_bind (eta_expand 2 (const, ts)) else IConst const `$$ map imp_monad_bind ts and imp_monad_bind (IConst const) = imp_monad_bind' const [] | imp_monad_bind (t as IVar _) = t | imp_monad_bind (t as _ `$ _) = (case unfold_app t of (IConst const, ts) => imp_monad_bind' const ts | (t, ts) => imp_monad_bind t `$$ map imp_monad_bind ts) | imp_monad_bind (v_ty `|=> t) = v_ty `|=> imp_monad_bind t | imp_monad_bind (ICase { term = t, typ = ty, clauses = clauses, primitive = t0 }) = ICase { term = imp_monad_bind t, typ = ty, clauses = (map o apply2) imp_monad_bind clauses, primitive = imp_monad_bind t0 }; in (Code_Symbol.Graph.map o K o map_terms_stmt) imp_monad_bind end; in Code_Target.add_derived_target ("SML_imp", [("SML", imp_program)]) #> Code_Target.add_derived_target ("OCaml_imp", [("OCaml", imp_program)]) #> Code_Target.add_derived_target ("Scala_imp", [("Scala", imp_program)]) end \ hide_const (open) Heap heap guard fold_map end diff --git a/src/Pure/General/linear_set.scala b/src/Pure/General/linear_set.scala --- a/src/Pure/General/linear_set.scala +++ b/src/Pure/General/linear_set.scala @@ -1,159 +1,164 @@ /* Title: Pure/General/linear_set.scala Author: Makarius Author: Fabian Immler, TU Munich Sets with canonical linear order, or immutable linked-lists. */ package isabelle -import scala.collection.SetLike -import scala.collection.generic.{SetFactory, CanBuildFrom, GenericSetTemplate, GenericCompanion} -import scala.collection.mutable.{Builder, SetBuilder} -import scala.language.higherKinds +import scala.collection.mutable +import scala.collection.immutable.SetOps +import scala.collection.{IterableFactory, IterableFactoryDefaults} -object Linear_Set extends SetFactory[Linear_Set] +object Linear_Set extends IterableFactory[Linear_Set] { private val empty_val: Linear_Set[Nothing] = new Linear_Set[Nothing](None, None, Map(), Map()) override def empty[A]: Linear_Set[A] = empty_val.asInstanceOf[Linear_Set[A]] - implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Linear_Set[A]] = setCanBuildFrom[A] - def newBuilder[A]: Builder[A, Linear_Set[A]] = new SetBuilder[A, Linear_Set[A]](empty[A]) + def from[A](entries: IterableOnce[A]): Linear_Set[A] = (empty[A] /: entries)(_.incl(_)) + + override def newBuilder[A]: mutable.Builder[A, Linear_Set[A]] = new Builder[A] + private class Builder[A] extends mutable.Builder[A, Linear_Set[A]] + { + private var res = empty[A] + override def clear() { res = empty[A] } + override def addOne(elem: A): this.type = { res = res.incl(elem); this } + override def result(): Linear_Set[A] = res + } class Duplicate[A](x: A) extends Exception class Undefined[A](x: A) extends Exception class Next_Undefined[A](x: Option[A]) extends Exception } final class Linear_Set[A] private( start: Option[A], end: Option[A], val nexts: Map[A, A], prevs: Map[A, A]) - extends scala.collection.immutable.Set[A] - with GenericSetTemplate[A, Linear_Set] - with SetLike[A, Linear_Set[A]] + extends Iterable[A] + with SetOps[A, Linear_Set, Linear_Set[A]] + with IterableFactoryDefaults[A, Linear_Set] { - override def companion: GenericCompanion[Linear_Set] = Linear_Set - - /* relative addressing */ def next(elem: A): Option[A] = if (contains(elem)) nexts.get(elem) else throw new Linear_Set.Undefined(elem) def prev(elem: A): Option[A] = if (contains(elem)) prevs.get(elem) else throw new Linear_Set.Undefined(elem) def get_after(hook: Option[A]): Option[A] = hook match { case None => start case Some(elem) => next(elem) } def insert_after(hook: Option[A], elem: A): Linear_Set[A] = if (contains(elem)) throw new Linear_Set.Duplicate(elem) else hook match { case None => start match { case None => new Linear_Set[A](Some(elem), Some(elem), Map(), Map()) case Some(elem1) => new Linear_Set[A](Some(elem), end, nexts + (elem -> elem1), prevs + (elem1 -> elem)) } case Some(elem1) => if (!contains(elem1)) throw new Linear_Set.Undefined(elem1) else nexts.get(elem1) match { case None => new Linear_Set[A](start, Some(elem), nexts + (elem1 -> elem), prevs + (elem -> elem1)) case Some(elem2) => new Linear_Set[A](start, end, nexts + (elem1 -> elem) + (elem -> elem2), prevs + (elem2 -> elem) + (elem -> elem1)) } } - def append_after(hook: Option[A], elems: Traversable[A]): Linear_Set[A] = // FIXME reverse fold + def append_after(hook: Option[A], elems: Iterable[A]): Linear_Set[A] = // FIXME reverse fold ((hook, this) /: elems) { case ((last, set), elem) => (Some(elem), set.insert_after(last, elem)) }._2 def delete_after(hook: Option[A]): Linear_Set[A] = hook match { case None => start match { case None => throw new Linear_Set.Next_Undefined[A](None) case Some(elem1) => nexts.get(elem1) match { case None => empty case Some(elem2) => new Linear_Set[A](Some(elem2), end, nexts - elem1, prevs - elem2) } } case Some(elem1) => if (!contains(elem1)) throw new Linear_Set.Undefined(elem1) else nexts.get(elem1) match { case None => throw new Linear_Set.Next_Undefined(Some(elem1)) case Some(elem2) => nexts.get(elem2) match { case None => new Linear_Set[A](start, Some(elem1), nexts - elem1, prevs - elem2) case Some(elem3) => new Linear_Set[A](start, end, nexts - elem2 + (elem1 -> elem3), prevs - elem2 + (elem3 -> elem1)) } } } /* Set methods */ - override def stringPrefix = "Linear_Set" - override def isEmpty: Boolean = start.isEmpty override def size: Int = if (isEmpty) 0 else nexts.size + 1 def contains(elem: A): Boolean = nonEmpty && (end.get == elem || nexts.isDefinedAt(elem)) private def make_iterator(from: Option[A]): Iterator[A] = new Iterator[A] { private var next_elem = from def hasNext(): Boolean = next_elem.isDefined def next(): A = next_elem match { case Some(elem) => next_elem = nexts.get(elem) elem case None => Iterator.empty.next() } } override def iterator: Iterator[A] = make_iterator(start) def iterator(elem: A): Iterator[A] = if (contains(elem)) make_iterator(Some(elem)) else throw new Linear_Set.Undefined(elem) def iterator(from: A, to: A): Iterator[A] = if (contains(to)) nexts.get(to) match { case None => iterator(from) case Some(stop) => iterator(from).takeWhile(_ != stop) } else throw new Linear_Set.Undefined(to) def reverse: Linear_Set[A] = new Linear_Set(end, start, prevs, nexts) override def last: A = reverse.head - def + (elem: A): Linear_Set[A] = insert_after(end, elem) + def incl(elem: A): Linear_Set[A] = insert_after(end, elem) + def excl(elem: A): Linear_Set[A] = delete_after(prev(elem)) - def - (elem: A): Linear_Set[A] = delete_after(prev(elem)) + override def iterableFactory: IterableFactory[Linear_Set] = Linear_Set + + override def toString: String = mkString("Linear_Set(", ", ", ")") } diff --git a/src/Pure/General/multi_map.scala b/src/Pure/General/multi_map.scala --- a/src/Pure/General/multi_map.scala +++ b/src/Pure/General/multi_map.scala @@ -1,83 +1,91 @@ /* Title: Pure/General/multi_map.scala Author: Makarius Maps with multiple entries per key. */ package isabelle - -import scala.collection.GenTraversableOnce -import scala.collection.generic.{ImmutableMapFactory, CanBuildFrom} +import scala.collection.mutable +import scala.collection.{IterableFactory, MapFactory, MapFactoryDefaults} +import scala.collection.immutable.{Iterable, MapOps} -object Multi_Map extends ImmutableMapFactory[Multi_Map] +object Multi_Map extends MapFactory[Multi_Map] { private val empty_val: Multi_Map[Any, Nothing] = new Multi_Map[Any, Nothing](Map.empty) - override def empty[A, B]: Multi_Map[A, B] = empty_val.asInstanceOf[Multi_Map[A, B]] + def empty[A, B]: Multi_Map[A, B] = empty_val.asInstanceOf[Multi_Map[A, B]] - implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Multi_Map[A, B]] = - new MapCanBuildFrom[A, B] + def from[A, B](entries: IterableOnce[(A, B)]): Multi_Map[A, B] = + (empty[A, B] /: entries)({ case (m, (a, b)) => m.insert(a, b) }) + + override def newBuilder[A, B]: mutable.Builder[(A, B), Multi_Map[A, B]] = new Builder[A, B] + private class Builder[A, B] extends mutable.Builder[(A, B), Multi_Map[A, B]] + { + private var res = empty[A, B] + override def clear() { res = empty[A, B] } + override def addOne(p: (A, B)): this.type = { res = res.insert(p._1, p._2); this } + override def result(): Multi_Map[A, B] = res + } } - final class Multi_Map[A, +B] private(protected val rep: Map[A, List[B]]) - extends scala.collection.immutable.Map[A, B] - with scala.collection.immutable.MapLike[A, B, Multi_Map[A, B]] + extends Iterable[(A, B)] + with MapOps[A, B, Multi_Map, Multi_Map[A, B]] + with MapFactoryDefaults[A, B, Multi_Map, Iterable] { /* Multi_Map operations */ def iterator_list: Iterator[(A, List[B])] = rep.iterator def get_list(a: A): List[B] = rep.getOrElse(a, Nil) def insert[B1 >: B](a: A, b: B1): Multi_Map[A, B1] = { val bs = get_list(a) if (bs.contains(b)) this else new Multi_Map(rep + (a -> (b :: bs))) } def remove[B1 >: B](a: A, b: B1): Multi_Map[A, B1] = { val bs = get_list(a) if (bs.contains(b)) { bs.filterNot(_ == b) match { case Nil => new Multi_Map(rep - a) case bs1 => new Multi_Map(rep + (a -> bs1)) } } else this } def ++[B1 >: B] (other: Multi_Map[A, B1]): Multi_Map[A, B1] = if (this eq other) this else if (isEmpty) other else (this.asInstanceOf[Multi_Map[A, B1]] /: other.rep.iterator) { case (m1, (a, bs)) => (bs :\ m1) { case (b, m2) => m2.insert(a, b) } } /* Map operations */ - override def stringPrefix = "Multi_Map" - override def empty: Multi_Map[A, Nothing] = Multi_Map.empty override def isEmpty: Boolean = rep.isEmpty override def keySet: Set[A] = rep.keySet override def iterator: Iterator[(A, B)] = for ((a, bs) <- rep.iterator; b <- bs.iterator) yield (a, b) def get(a: A): Option[B] = get_list(a).headOption - def + [B1 >: B](p: (A, B1)): Multi_Map[A, B1] = insert(p._1, p._2) + override def updated[B1 >: B](a: A, b: B1): Multi_Map[A, B1] = insert(a, b) - override def ++ [B1 >: B](entries: GenTraversableOnce[(A, B1)]): Multi_Map[A, B1] = - (this.asInstanceOf[Multi_Map[A, B1]] /: entries)(_ + _) + override def removed(a: A): Multi_Map[A, B] = + if (rep.isDefinedAt(a)) new Multi_Map(rep - a) else this - def - (a: A): Multi_Map[A, B] = - if (rep.isDefinedAt(a)) new Multi_Map(rep - a) else this + override def mapFactory: MapFactory[Multi_Map] = Multi_Map + + override def toString: String = mkString("Multi_Map(", ", ", ")") } diff --git a/src/Pure/General/scan.scala b/src/Pure/General/scan.scala --- a/src/Pure/General/scan.scala +++ b/src/Pure/General/scan.scala @@ -1,512 +1,511 @@ /* Title: Pure/General/scan.scala Author: Makarius Efficient scanning of keywords and tokens. */ package isabelle import scala.annotation.tailrec import scala.collection.{IndexedSeq, Traversable, TraversableOnce} -import scala.collection.immutable.PagedSeq import scala.util.matching.Regex import scala.util.parsing.input.{OffsetPosition, Position => InputPosition, - Reader, CharSequenceReader} + Reader, CharSequenceReader, PagedSeq} import scala.util.parsing.combinator.RegexParsers import java.io.{File => JFile, BufferedInputStream, FileInputStream, InputStream} import java.net.URL object Scan { /** context of partial line-oriented scans **/ abstract class Line_Context case object Finished extends Line_Context case class Quoted(quote: String) extends Line_Context case object Verbatim extends Line_Context case class Cartouche(depth: Int) extends Line_Context case class Comment_Prefix(symbol: Symbol.Symbol) extends Line_Context case class Cartouche_Comment(depth: Int) extends Line_Context case class Comment(depth: Int) extends Line_Context /** parser combinators **/ object Parsers extends Parsers trait Parsers extends RegexParsers { override val whiteSpace: Regex = "".r /* optional termination */ def opt_term[T](p: => Parser[T]): Parser[Option[T]] = p ^^ (x => Some(x)) | """\z""".r ^^ (_ => None) /* repeated symbols */ def repeated(pred: Symbol.Symbol => Boolean, min_count: Int, max_count: Int): Parser[String] = new Parser[String] { def apply(in: Input) = { val start = in.offset val end = in.source.length val matcher = new Symbol.Matcher(in.source) var i = start var count = 0 var finished = false while (!finished && i < end && count < max_count) { val n = matcher(i, end) val sym = in.source.subSequence(i, i + n).toString if (pred(sym)) { i += n; count += 1 } else finished = true } if (count < min_count) Failure("bad input", in) else Success(in.source.subSequence(start, i).toString, in.drop(i - start)) } }.named("repeated") def one(pred: Symbol.Symbol => Boolean): Parser[String] = repeated(pred, 1, 1) def maybe(pred: Symbol.Symbol => Boolean): Parser[String] = repeated(pred, 0, 1) def many(pred: Symbol.Symbol => Boolean): Parser[String] = repeated(pred, 0, Integer.MAX_VALUE) def many1(pred: Symbol.Symbol => Boolean): Parser[String] = repeated(pred, 1, Integer.MAX_VALUE) /* character */ def character(pred: Char => Boolean): Symbol.Symbol => Boolean = (s: Symbol. Symbol) => s.length == 1 && pred(s.charAt(0)) /* quoted strings */ private def quoted_body(quote: Symbol.Symbol): Parser[String] = { rep(many1(sym => sym != quote && sym != "\\") | "\\" + quote | "\\\\" | ("""\\\d\d\d""".r ^? { case x if x.substring(1, 4).toInt <= 255 => x })) ^^ (_.mkString) } def quoted(quote: Symbol.Symbol): Parser[String] = { quote ~ quoted_body(quote) ~ quote ^^ { case x ~ y ~ z => x + y + z } }.named("quoted") def quoted_content(quote: Symbol.Symbol, source: String): String = { require(parseAll(quoted(quote), source).successful, "no quoted text") val body = source.substring(1, source.length - 1) if (body.exists(_ == '\\')) { val content = rep(many1(sym => sym != quote && sym != "\\") | "\\" ~> (quote | "\\" | """\d\d\d""".r ^^ { case x => x.toInt.toChar.toString })) parseAll(content ^^ (_.mkString), body).get } else body } def quoted_line(quote: Symbol.Symbol, ctxt: Line_Context): Parser[(String, Line_Context)] = { ctxt match { case Finished => quote ~ quoted_body(quote) ~ opt_term(quote) ^^ { case x ~ y ~ Some(z) => (x + y + z, Finished) case x ~ y ~ None => (x + y, Quoted(quote)) } case Quoted(q) if q == quote => quoted_body(quote) ~ opt_term(quote) ^^ { case x ~ Some(y) => (x + y, Finished) case x ~ None => (x, ctxt) } case _ => failure("") } }.named("quoted_line") def recover_quoted(quote: Symbol.Symbol): Parser[String] = quote ~ quoted_body(quote) ^^ { case x ~ y => x + y } /* verbatim text */ private def verbatim_body: Parser[String] = rep(many1(sym => sym != "*") | """\*(?!\})""".r) ^^ (_.mkString) def verbatim: Parser[String] = { "{*" ~ verbatim_body ~ "*}" ^^ { case x ~ y ~ z => x + y + z } }.named("verbatim") def verbatim_content(source: String): String = { require(parseAll(verbatim, source).successful, "no verbatim text") source.substring(2, source.length - 2) } def verbatim_line(ctxt: Line_Context): Parser[(String, Line_Context)] = { ctxt match { case Finished => "{*" ~ verbatim_body ~ opt_term("*}") ^^ { case x ~ y ~ Some(z) => (x + y + z, Finished) case x ~ y ~ None => (x + y, Verbatim) } case Verbatim => verbatim_body ~ opt_term("*}") ^^ { case x ~ Some(y) => (x + y, Finished) case x ~ None => (x, Verbatim) } case _ => failure("") } }.named("verbatim_line") val recover_verbatim: Parser[String] = "{*" ~ verbatim_body ^^ { case x ~ y => x + y } /* nested text cartouches */ def cartouche_depth(depth: Int): Parser[(String, Int)] = new Parser[(String, Int)] { require(depth >= 0, "bad cartouche depth") def apply(in: Input) = { val start = in.offset val end = in.source.length val matcher = new Symbol.Matcher(in.source) var i = start var d = depth var finished = false while (!finished && i < end) { val n = matcher(i, end) val sym = in.source.subSequence(i, i + n).toString if (Symbol.is_open(sym)) { i += n; d += 1 } else if (Symbol.is_close(sym) && d > 0) { i += n; d -= 1; if (d == 0) finished = true } else if (d > 0) i += n else finished = true } if (i == start) Failure("bad input", in) else Success((in.source.subSequence(start, i).toString, d), in.drop(i - start)) } }.named("cartouche_depth") def cartouche: Parser[String] = cartouche_depth(0) ^? { case (x, d) if d == 0 => x } def cartouche_line(ctxt: Line_Context): Parser[(String, Line_Context)] = { def cartouche_context(d: Int): Line_Context = if (d == 0) Finished else Cartouche(d) ctxt match { case Finished => cartouche_depth(0) ^^ { case (c, d) => (c, cartouche_context(d)) } case Cartouche(depth) => cartouche_depth(depth) ^^ { case (c, d) => (c, cartouche_context(d)) } case _ => failure("") } } val recover_cartouche: Parser[String] = cartouche_depth(0) ^^ (_._1) def cartouche_content(source: String): String = { def err(): Nothing = error("Malformed text cartouche: " + quote(source)) val source1 = Library.try_unprefix(Symbol.open_decoded, source) orElse Library.try_unprefix(Symbol.open, source) getOrElse err() Library.try_unsuffix(Symbol.close_decoded, source1) orElse Library.try_unsuffix(Symbol.close, source1) getOrElse err() } /* nested comments */ private def comment_depth(depth: Int): Parser[(String, Int)] = new Parser[(String, Int)] { require(depth >= 0, "bad comment depth") val comment_text: Parser[List[String]] = rep1(many1(sym => sym != "*" && sym != "(") | """\*(?!\))|\((?!\*)""".r) def apply(in: Input) = { var rest = in def try_parse[A](p: Parser[A]): Boolean = { parse(p ^^^ (()), rest) match { case Success(_, next) => { rest = next; true } case _ => false } } var d = depth var finished = false while (!finished) { if (try_parse("(*")) d += 1 else if (d > 0 && try_parse("*)")) { d -= 1; if (d == 0) finished = true } else if (d == 0 || !try_parse(comment_text)) finished = true } if (in.offset < rest.offset) Success((in.source.subSequence(in.offset, rest.offset).toString, d), rest) else Failure("comment expected", in) } }.named("comment_depth") def comment: Parser[String] = comment_depth(0) ^? { case (x, d) if d == 0 => x } def comment_line(ctxt: Line_Context): Parser[(String, Line_Context)] = { val depth = ctxt match { case Finished => 0 case Comment(d) => d case _ => -1 } if (depth >= 0) comment_depth(depth) ^^ { case (x, 0) => (x, Finished) case (x, d) => (x, Comment(d)) } else failure("") } val recover_comment: Parser[String] = comment_depth(0) ^^ (_._1) def comment_content(source: String): String = { require(parseAll(comment, source).successful, "no comment") source.substring(2, source.length - 2) } /* keyword */ def literal(lexicon: Lexicon): Parser[String] = new Parser[String] { def apply(in: Input) = { val result = lexicon.scan(in) if (result.isEmpty) Failure("keyword expected", in) else Success(result, in.drop(result.length)) } }.named("keyword") } /** Lexicon -- position tree **/ object Lexicon { /* representation */ private sealed case class Tree(branches: Map[Char, (String, Tree)]) private val empty_tree = Tree(Map()) val empty: Lexicon = new Lexicon(empty_tree) def apply(elems: String*): Lexicon = empty ++ elems } final class Lexicon private(rep: Lexicon.Tree) { /* auxiliary operations */ private def dest(tree: Lexicon.Tree, result: List[String]): List[String] = (result /: tree.branches.toList) ((res, entry) => entry match { case (_, (s, tr)) => if (s.isEmpty) dest(tr, res) else dest(tr, s :: res) }) private def lookup(str: CharSequence): Option[(Boolean, Lexicon.Tree)] = { val len = str.length @tailrec def look(tree: Lexicon.Tree, tip: Boolean, i: Int): Option[(Boolean, Lexicon.Tree)] = { if (i < len) { tree.branches.get(str.charAt(i)) match { case Some((s, tr)) => look(tr, s.nonEmpty, i + 1) case None => None } } else Some(tip, tree) } look(rep, false, 0) } def completions(str: CharSequence): List[String] = lookup(str) match { case Some((true, tree)) => dest(tree, List(str.toString)) case Some((false, tree)) => dest(tree, Nil) case None => Nil } /* pseudo Set methods */ def raw_iterator: Iterator[String] = dest(rep, Nil).iterator def iterator: Iterator[String] = dest(rep, Nil).sorted.iterator override def toString: String = iterator.mkString("Lexicon(", ", ", ")") def is_empty: Boolean = rep.branches.isEmpty def contains(elem: String): Boolean = lookup(elem) match { case Some((tip, _)) => tip case _ => false } /* build lexicon */ def + (elem: String): Lexicon = if (contains(elem)) this else { val len = elem.length def extend(tree: Lexicon.Tree, i: Int): Lexicon.Tree = if (i < len) { val c = elem.charAt(i) val end = (i + 1 == len) tree.branches.get(c) match { case Some((s, tr)) => Lexicon.Tree(tree.branches + (c -> (if (end) elem else s, extend(tr, i + 1)))) case None => Lexicon.Tree(tree.branches + (c -> (if (end) elem else "", extend(Lexicon.empty_tree, i + 1)))) } } else tree new Lexicon(extend(rep, 0)) } def ++ (elems: TraversableOnce[String]): Lexicon = (this /: elems)(_ + _) def ++ (other: Lexicon): Lexicon = if (this eq other) this else if (is_empty) other else this ++ other.raw_iterator def -- (remove: Traversable[String]): Lexicon = if (remove.exists(contains)) Lexicon.empty ++ iterator.filterNot(a => remove.exists(b => a == b)) else this /* scan */ def scan(in: Reader[Char]): String = { val source = in.source val offset = in.offset val len = source.length - offset @tailrec def scan_tree(tree: Lexicon.Tree, result: String, i: Int): String = { if (i < len) { tree.branches.get(source.charAt(offset + i)) match { case Some((s, tr)) => scan_tree(tr, if (s.isEmpty) result else s, i + 1) case None => result } } else result } scan_tree(rep, "", 0) } } /** read stream without decoding: efficient length operation **/ private class Restricted_Seq(seq: IndexedSeq[Char], start: Int, end: Int) extends CharSequence { def charAt(i: Int): Char = if (0 <= i && i < length) seq(start + i) else throw new IndexOutOfBoundsException def length: Int = end - start // avoid expensive seq.length def subSequence(i: Int, j: Int): CharSequence = if (0 <= i && i <= j && j <= length) new Restricted_Seq(seq, start + i, start + j) else throw new IndexOutOfBoundsException override def toString: String = { val buf = new StringBuilder(length) for (offset <- start until end) buf.append(seq(offset)) buf.toString } } abstract class Byte_Reader extends Reader[Char] with AutoCloseable private def make_byte_reader(stream: InputStream, stream_length: Int): Byte_Reader = { val buffered_stream = new BufferedInputStream(stream) val seq = new PagedSeq( (buf: Array[Char], offset: Int, length: Int) => { var i = 0 var c = 0 var eof = false while (!eof && i < length) { c = buffered_stream.read if (c == -1) eof = true else { buf(offset + i) = c.toChar; i += 1 } } if (i > 0) i else -1 }) val restricted_seq = new Restricted_Seq(seq, 0, stream_length) class Paged_Reader(override val offset: Int) extends Byte_Reader { override lazy val source: CharSequence = restricted_seq def first: Char = if (seq.isDefinedAt(offset)) seq(offset) else '\u001a' def rest: Paged_Reader = if (seq.isDefinedAt(offset)) new Paged_Reader(offset + 1) else this def pos: InputPosition = new OffsetPosition(source, offset) def atEnd: Boolean = !seq.isDefinedAt(offset) override def drop(n: Int): Paged_Reader = new Paged_Reader(offset + n) def close { buffered_stream.close } } new Paged_Reader(0) } def byte_reader(file: JFile): Byte_Reader = make_byte_reader(new FileInputStream(file), file.length.toInt) def byte_reader(url: URL): Byte_Reader = { val connection = url.openConnection val stream = connection.getInputStream val stream_length = connection.getContentLength make_byte_reader(stream, stream_length) } def reader_is_utf8(reader: Reader[Char]): Boolean = reader.isInstanceOf[Byte_Reader] def reader_decode_utf8(is_utf8: Boolean, s: String): String = if (is_utf8) UTF8.decode_permissive(s) else s def reader_decode_utf8(reader: Reader[Char], s: String): String = reader_decode_utf8(reader_is_utf8(reader), s) /* plain text reader */ def char_reader(text: CharSequence): CharSequenceReader = new CharSequenceReader(text) } diff --git a/src/Pure/General/uuid.scala b/src/Pure/General/uuid.scala --- a/src/Pure/General/uuid.scala +++ b/src/Pure/General/uuid.scala @@ -1,20 +1,22 @@ /* Title: Pure/General/uuid.scala Author: Makarius Universally unique identifiers. */ package isabelle object UUID { type T = java.util.UUID def random(): T = java.util.UUID.randomUUID() def random_string(): String = random().toString def unapply(s: String): Option[T] = try { Some(java.util.UUID.fromString(s)) } catch { case _: IllegalArgumentException => None } + + def unapply(body: XML.Body): Option[T] = unapply(XML.content(body)) } diff --git a/src/Pure/ROOT.ML b/src/Pure/ROOT.ML --- a/src/Pure/ROOT.ML +++ b/src/Pure/ROOT.ML @@ -1,356 +1,357 @@ (* Title: Pure/ROOT.ML Author: Makarius Main entry point for the Isabelle/Pure bootstrap process. Note: When this file is open in the Prover IDE, the ML files of Isabelle/Pure can be explored interactively. This is a separate copy of Pure within Pure: it does not affect the running logic session. *) chapter "Isabelle/Pure bootstrap"; ML_file "ML/ml_name_space.ML"; section "Bootstrap phase 0: Poly/ML setup"; ML_file "ML/ml_init.ML"; ML_file "ML/ml_system.ML"; ML_file "System/distribution.ML"; ML_file "General/basics.ML"; ML_file "General/symbol_explode.ML"; ML_file "Concurrent/multithreading.ML"; ML_file "Concurrent/unsynchronized.ML"; ML_file "Concurrent/synchronized.ML"; ML_file "Concurrent/counter.ML"; ML_file "ML/ml_heap.ML"; ML_file "ML/ml_profiling.ML"; ML_file "ML/ml_print_depth0.ML"; ML_file "ML/ml_pretty.ML"; ML_file "ML/ml_compiler0.ML"; section "Bootstrap phase 1: towards ML within position context"; subsection "Library of general tools"; ML_file "library.ML"; ML_file "General/print_mode.ML"; ML_file "General/alist.ML"; ML_file "General/table.ML"; ML_file "General/random.ML"; ML_file "General/value.ML"; ML_file "General/properties.ML"; ML_file "General/output.ML"; ML_file "PIDE/markup.ML"; ML_file "General/utf8.ML"; ML_file "General/scan.ML"; ML_file "General/source.ML"; ML_file "General/symbol.ML"; ML_file "General/position.ML"; ML_file "General/symbol_pos.ML"; ML_file "General/input.ML"; ML_file "General/comment.ML"; ML_file "General/antiquote.ML"; ML_file "ML/ml_lex.ML"; ML_file "ML/ml_compiler1.ML"; section "Bootstrap phase 2: towards ML within Isar context"; subsection "Library of general tools"; ML_file "General/integer.ML"; ML_file "General/stack.ML"; ML_file "General/queue.ML"; ML_file "General/heap.ML"; ML_file "General/same.ML"; ML_file "General/ord_list.ML"; ML_file "General/balanced_tree.ML"; ML_file "General/linear_set.ML"; ML_file "General/buffer.ML"; ML_file "General/pretty.ML"; ML_file "General/rat.ML"; ML_file "PIDE/xml.ML"; ML_file "General/path.ML"; ML_file "General/url.ML"; ML_file "System/bash_syntax.ML"; ML_file "General/file.ML"; ML_file "General/long_name.ML"; ML_file "General/binding.ML"; ML_file "General/socket_io.ML"; ML_file "General/seq.ML"; ML_file "General/timing.ML"; ML_file "General/sha1.ML"; ML_file "PIDE/byte_message.ML"; ML_file "PIDE/yxml.ML"; ML_file "PIDE/protocol_message.ML"; ML_file "PIDE/document_id.ML"; ML_file "General/change_table.ML"; ML_file "General/graph.ML"; ML_file "System/options.ML"; subsection "Fundamental structures"; ML_file "name.ML"; ML_file "term.ML"; ML_file "context.ML"; ML_file "config.ML"; ML_file "context_position.ML"; ML_file "soft_type_system.ML"; subsection "Concurrency within the ML runtime"; ML_file "ML/exn_properties.ML"; ML_file_no_debug "ML/exn_debugger.ML"; ML_file "Concurrent/thread_data_virtual.ML"; ML_file "Concurrent/isabelle_thread.ML"; ML_file "Concurrent/single_assignment.ML"; ML_file "Concurrent/par_exn.ML"; ML_file "Concurrent/task_queue.ML"; ML_file "Concurrent/future.ML"; ML_file "Concurrent/event_timer.ML"; ML_file "Concurrent/timeout.ML"; ML_file "Concurrent/lazy.ML"; ML_file "Concurrent/par_list.ML"; ML_file "Concurrent/mailbox.ML"; ML_file "Concurrent/cache.ML"; ML_file "PIDE/active.ML"; ML_file "Thy/export.ML"; subsection "Inner syntax"; ML_file "Syntax/type_annotation.ML"; ML_file "Syntax/term_position.ML"; ML_file "Syntax/lexicon.ML"; ML_file "Syntax/ast.ML"; ML_file "Syntax/syntax_ext.ML"; ML_file "Syntax/parser.ML"; ML_file "Syntax/syntax_trans.ML"; ML_file "Syntax/mixfix.ML"; ML_file "Syntax/printer.ML"; ML_file "Syntax/syntax.ML"; subsection "Core of tactical proof system"; ML_file "term_ord.ML"; ML_file "term_subst.ML"; ML_file "General/completion.ML"; ML_file "General/name_space.ML"; ML_file "sorts.ML"; ML_file "type.ML"; ML_file "logic.ML"; ML_file "Syntax/simple_syntax.ML"; ML_file "net.ML"; ML_file "item_net.ML"; ML_file "envir.ML"; ML_file "consts.ML"; ML_file "term_xml.ML"; ML_file "primitive_defs.ML"; ML_file "sign.ML"; ML_file "defs.ML"; ML_file "term_sharing.ML"; ML_file "pattern.ML"; ML_file "unify.ML"; ML_file "theory.ML"; ML_file "proofterm.ML"; ML_file "thm.ML"; ML_file "more_pattern.ML"; ML_file "more_unify.ML"; ML_file "more_thm.ML"; ML_file "facts.ML"; ML_file "thm_name.ML"; ML_file "global_theory.ML"; ML_file "pure_thy.ML"; ML_file "drule.ML"; ML_file "morphism.ML"; ML_file "variable.ML"; ML_file "conv.ML"; ML_file "goal_display.ML"; ML_file "tactical.ML"; ML_file "search.ML"; ML_file "tactic.ML"; ML_file "raw_simplifier.ML"; ML_file "conjunction.ML"; ML_file "assumption.ML"; subsection "Isar -- Intelligible Semi-Automated Reasoning"; (*ML support and global execution*) ML_file "ML/ml_syntax.ML"; ML_file "ML/ml_env.ML"; ML_file "ML/ml_options.ML"; ML_file "ML/ml_print_depth.ML"; ML_file_no_debug "Isar/runtime.ML"; ML_file "PIDE/execution.ML"; ML_file "ML/ml_compiler.ML"; ML_file "skip_proof.ML"; ML_file "goal.ML"; (*outer syntax*) ML_file "Isar/keyword.ML"; ML_file "Isar/token.ML"; ML_file "Isar/parse.ML"; ML_file "Thy/document_source.ML"; ML_file "Thy/thy_header.ML"; ML_file "Thy/document_marker.ML"; (*proof context*) ML_file "Isar/object_logic.ML"; ML_file "Isar/rule_cases.ML"; ML_file "Isar/auto_bind.ML"; ML_file "type_infer.ML"; ML_file "Syntax/local_syntax.ML"; ML_file "Isar/proof_context.ML"; ML_file "type_infer_context.ML"; ML_file "Syntax/syntax_phases.ML"; ML_file "Isar/args.ML"; (*theory specifications*) ML_file "Isar/local_defs.ML"; ML_file "Isar/local_theory.ML"; ML_file "Isar/entity.ML"; ML_file "PIDE/command_span.ML"; ML_file "Thy/thy_element.ML"; ML_file "Thy/markdown.ML"; ML_file "Thy/latex.ML"; (*ML with context and antiquotations*) ML_file "ML/ml_context.ML"; ML_file "ML/ml_antiquotation.ML"; ML_file "ML/ml_compiler2.ML"; ML_file "ML/ml_pid.ML"; section "Bootstrap phase 3: towards theory Pure and final ML toplevel setup"; (*basic proof engine*) ML_file "par_tactical.ML"; ML_file "context_tactic.ML"; ML_file "Isar/proof_display.ML"; ML_file "Isar/attrib.ML"; ML_file "Isar/context_rules.ML"; ML_file "Isar/method.ML"; ML_file "Isar/proof.ML"; ML_file "Isar/element.ML"; ML_file "Isar/obtain.ML"; ML_file "Isar/subgoal.ML"; ML_file "Isar/calculation.ML"; (*local theories and targets*) ML_file "Isar/locale.ML"; ML_file "Isar/generic_target.ML"; ML_file "Isar/bundle.ML"; ML_file "Isar/overloading.ML"; ML_file "axclass.ML"; ML_file "Isar/class.ML"; ML_file "Isar/named_target.ML"; ML_file "Isar/expression.ML"; ML_file "Isar/interpretation.ML"; ML_file "Isar/class_declaration.ML"; ML_file "Isar/target_context.ML"; ML_file "Isar/experiment.ML"; ML_file "simplifier.ML"; ML_file "Tools/plugin.ML"; (*executable theory content*) ML_file "Isar/code.ML"; (*specifications*) ML_file "Isar/spec_rules.ML"; ML_file "Isar/specification.ML"; ML_file "Isar/parse_spec.ML"; ML_file "Isar/typedecl.ML"; (*toplevel transactions*) ML_file "Isar/proof_node.ML"; ML_file "Isar/toplevel.ML"; (*proof term operations*) ML_file "Proof/proof_rewrite_rules.ML"; ML_file "Proof/proof_syntax.ML"; ML_file "Proof/proof_checker.ML"; ML_file "Proof/extraction.ML"; (*Isabelle system*) ML_file "System/bash.ML"; ML_file "System/isabelle_system.ML"; (*theory documents*) ML_file "Thy/term_style.ML"; ML_file "Isar/outer_syntax.ML"; ML_file "ML/ml_antiquotations.ML"; ML_file "Thy/document_antiquotation.ML"; ML_file "Thy/thy_output.ML"; ML_file "Thy/document_antiquotations.ML"; ML_file "General/graph_display.ML"; ML_file "pure_syn.ML"; ML_file "PIDE/command.ML"; ML_file "PIDE/query_operation.ML"; ML_file "PIDE/resources.ML"; ML_file "Thy/thy_info.ML"; ML_file "thm_deps.ML"; ML_file "Thy/export_theory.ML"; ML_file "Thy/sessions.ML"; ML_file "PIDE/session.ML"; ML_file "PIDE/document.ML"; (*theory and proof operations*) ML_file "Isar/isar_cmd.ML"; subsection "Isabelle/Isar system"; ML_file "System/command_line.ML"; ML_file "System/message_channel.ML"; ML_file "System/isabelle_process.ML"; ML_file "System/scala.ML"; ML_file "System/scala_compiler.ML"; ML_file "System/isabelle_tool.ML"; ML_file "Thy/bibtex.ML"; ML_file "PIDE/protocol.ML"; ML_file "General/output_primitives_virtual.ML"; subsection "Miscellaneous tools and packages for Pure Isabelle"; ML_file "ML/ml_pp.ML"; ML_file "ML/ml_thms.ML"; ML_file "ML/ml_file.ML"; ML_file "Tools/build.ML"; ML_file "Tools/named_thms.ML"; ML_file "Tools/print_operation.ML"; ML_file "Tools/rail.ML"; ML_file "Tools/rule_insts.ML"; ML_file "Tools/thy_deps.ML"; ML_file "Tools/class_deps.ML"; ML_file "Tools/find_theorems.ML"; ML_file "Tools/find_consts.ML"; ML_file "Tools/simplifier_trace.ML"; ML_file_no_debug "Tools/debugger.ML"; ML_file "Tools/named_theorems.ML"; ML_file "Tools/doc.ML"; ML_file "Tools/jedit.ML"; ML_file "Tools/ghc.ML"; ML_file "Tools/generated_files.ML" + diff --git a/src/Pure/ROOT.scala b/src/Pure/ROOT.scala --- a/src/Pure/ROOT.scala +++ b/src/Pure/ROOT.scala @@ -1,23 +1,24 @@ /* Title: Pure/ROOT.scala Author: Makarius Root of isabelle package. */ package object isabelle { val ERROR = Exn.ERROR val error = Exn.error _ def cat_error(msgs: String*): Nothing = Exn.cat_error(msgs:_*) def using[A <: AutoCloseable, B](a: A)(f: A => B): B = Library.using(a)(f) val space_explode = Library.space_explode _ val split_lines = Library.split_lines _ val cat_lines = Library.cat_lines _ val terminate_lines = Library.terminate_lines _ val quote = Library.quote _ val commas = Library.commas _ val commas_quote = Library.commas_quote _ val proper_string = Library.proper_string _ def proper_list[A](list: List[A]): Option[List[A]] = Library.proper_list(list) } + diff --git a/src/Pure/System/bash.scala b/src/Pure/System/bash.scala --- a/src/Pure/System/bash.scala +++ b/src/Pure/System/bash.scala @@ -1,205 +1,205 @@ /* Title: Pure/System/bash.scala Author: Makarius GNU bash processes, with propagation of interrupts. */ package isabelle import java.io.{File => JFile, BufferedReader, InputStreamReader, BufferedWriter, OutputStreamWriter} import scala.annotation.tailrec object Bash { /* concrete syntax */ private def bash_chr(c: Byte): String = { val ch = c.toChar ch match { case '\t' => "$'\\t'" case '\n' => "$'\\n'" case '\f' => "$'\\f'" case '\r' => "$'\\r'" case _ => if (Symbol.is_ascii_letter(ch) || Symbol.is_ascii_digit(ch) || "+,-./:_".contains(ch)) Symbol.ascii(ch) else if (c < 0) "$'\\x" + Integer.toHexString(256 + c) + "'" else if (c < 16) "$'\\x0" + Integer.toHexString(c) + "'" else if (c < 32 || c >= 127) "$'\\x" + Integer.toHexString(c) + "'" else "\\" + ch } } def string(s: String): String = if (s == "") "\"\"" else UTF8.bytes(s).iterator.map(bash_chr).mkString def strings(ss: List[String]): String = ss.iterator.map(Bash.string).mkString(" ") /* process and result */ type Watchdog = (Time, Process => Boolean) def process(script: String, cwd: JFile = null, env: Map[String, String] = Isabelle_System.settings(), redirect: Boolean = false, cleanup: () => Unit = () => ()): Process = new Process(script, cwd, env, redirect, cleanup) class Process private[Bash]( script: String, cwd: JFile, env: Map[String, String], redirect: Boolean, cleanup: () => Unit) { private val timing_file = Isabelle_System.tmp_file("bash_timing") private val timing = Synchronized[Option[Timing]](None) def get_timing: Timing = timing.value getOrElse Timing.zero private val script_file = Isabelle_System.tmp_file("bash_script") File.write(script_file, script) private val proc = Isabelle_System.process( List(File.platform_path(Path.variable("ISABELLE_BASH_PROCESS")), "-", File.standard_path(timing_file), "bash", File.standard_path(script_file)), cwd = cwd, env = env, redirect = redirect) // channels val stdin: BufferedWriter = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, UTF8.charset)) val stdout: BufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream, UTF8.charset)) val stderr: BufferedReader = new BufferedReader(new InputStreamReader(proc.getErrorStream, UTF8.charset)) // signals private val pid = stdout.readLine @tailrec private def kill(signal: String, count: Int = 1): Boolean = { count <= 0 || { Isabelle_System.kill(signal, pid) val running = Isabelle_System.kill("0", pid)._2 == 0 if (running) { Time.seconds(0.1).sleep kill(signal, count - 1) } else false } } def terminate(): Unit = Isabelle_Thread.try_uninterruptible { kill("INT", count = 7) && kill("TERM", count = 3) && kill("KILL") proc.destroy do_cleanup() } def interrupt(): Unit = Isabelle_Thread.try_uninterruptible { Isabelle_System.kill("INT", pid) } // JVM shutdown hook private val shutdown_hook = Isabelle_Thread.create(() => terminate()) try { Runtime.getRuntime.addShutdownHook(shutdown_hook) } catch { case _: IllegalStateException => } // cleanup private def do_cleanup() { try { Runtime.getRuntime.removeShutdownHook(shutdown_hook) } catch { case _: IllegalStateException => } script_file.delete timing.change { case None => if (timing_file.isFile) { val t = Word.explode(File.read(timing_file)) match { case List(Value.Long(elapsed), Value.Long(cpu)) => Timing(Time.ms(elapsed), Time.ms(cpu), Time.zero) case _ => Timing.zero } timing_file.delete Some(t) } else Some(Timing.zero) case some => some } cleanup() } // join def join: Int = { val rc = proc.waitFor do_cleanup() rc } // result def result( progress_stdout: String => Unit = (_: String) => (), progress_stderr: String => Unit = (_: String) => (), watchdog: Option[Watchdog] = None, strict: Boolean = true): Process_Result = { stdin.close val out_lines = Future.thread("bash_stdout") { File.read_lines(stdout, progress_stdout) } val err_lines = Future.thread("bash_stderr") { File.read_lines(stderr, progress_stderr) } val watchdog_thread = for ((time, check) <- watchdog) yield { Future.thread("bash_watchdog") { while (proc.isAlive) { time.sleep if (check(this)) interrupt() } } } val rc = try { join } catch { case Exn.Interrupt() => terminate(); Exn.Interrupt.return_code } watchdog_thread.foreach(_.cancel) if (strict && rc == Exn.Interrupt.return_code) throw Exn.Interrupt() - Process_Result(rc, out_lines.join, err_lines.join, false, get_timing) + Process_Result(rc, out_lines.join, err_lines.join, get_timing) } } } diff --git a/src/Pure/System/process_result.scala b/src/Pure/System/process_result.scala --- a/src/Pure/System/process_result.scala +++ b/src/Pure/System/process_result.scala @@ -1,82 +1,85 @@ /* Title: Pure/System/process_result.scala Author: Makarius Result of system process. */ package isabelle object Process_Result { def print_return_code(rc: Int): String = "Return code: " + rc + rc_text(rc) def print_rc(rc: Int): String = "return code " + rc + rc_text(rc) def rc_text(rc: Int): String = return_code_text.get(rc) match { case None => "" case Some(text) => " (" + text + ")" } private val return_code_text = Map(0 -> "OK", 1 -> "ERROR", 2 -> "FAILURE", 127 -> "COMMAND NOT FOUND", 130 -> "INTERRUPT", 131 -> "QUIT SIGNAL", 137 -> "KILL SIGNAL", 138 -> "BUS ERROR", 139 -> "SEGMENTATION VIOLATION", + 142 -> "TIMEOUT", 143 -> "TERMINATION SIGNAL") + + val timeout_rc = 142 } final case class Process_Result( rc: Int, out_lines: List[String] = Nil, err_lines: List[String] = Nil, - timeout: Boolean = false, timing: Timing = Timing.zero) { def out: String = cat_lines(out_lines) def err: String = cat_lines(err_lines) def output(outs: List[String]): Process_Result = copy(out_lines = out_lines ::: outs.flatMap(split_lines)) def errors(errs: List[String]): Process_Result = copy(err_lines = err_lines ::: errs.flatMap(split_lines)) def error(err: String): Process_Result = if (err.isEmpty) this else errors(List(err)) - def was_timeout: Process_Result = copy(rc = 1, timeout = true) - def ok: Boolean = rc == 0 def interrupted: Boolean = rc == Exn.Interrupt.return_code + def timeout_rc: Process_Result = copy(rc = Process_Result.timeout_rc) + def timeout: Boolean = rc == Process_Result.timeout_rc + def error_rc: Process_Result = if (interrupted) this else copy(rc = rc max 1) def errors_rc(errs: List[String]): Process_Result = if (errs.isEmpty) this else errors(errs).error_rc def check_rc(pred: Int => Boolean): Process_Result = if (pred(rc)) this else if (interrupted) throw Exn.Interrupt() else Exn.error(err) def check: Process_Result = check_rc(_ == 0) def print_return_code: String = Process_Result.print_return_code(rc) def print_rc: String = Process_Result.print_rc(rc) def print: Process_Result = { Output.warning(err) Output.writeln(out) copy(out_lines = Nil, err_lines = Nil) } def print_stdout: Process_Result = { Output.warning(err, stdout = true) Output.writeln(out, stdout = true) copy(out_lines = Nil, err_lines = Nil) } } diff --git a/src/Pure/System/scala.scala b/src/Pure/System/scala.scala --- a/src/Pure/System/scala.scala +++ b/src/Pure/System/scala.scala @@ -1,247 +1,247 @@ /* Title: Pure/System/scala.scala Author: Makarius Support for Scala at runtime. */ package isabelle import java.io.{File => JFile, StringWriter, PrintWriter} import scala.tools.nsc.{GenericRunnerSettings, ConsoleWriter, NewLinePrintWriter} import scala.tools.nsc.interpreter.{IMain, Results} - +import scala.tools.nsc.interpreter.shell.ReplReporterImpl object Scala { /** registered functions **/ abstract class Fun(val name: String) extends Function[String, String] { override def toString: String = name def position: Properties.T = here.position def here: Scala_Project.Here def apply(arg: String): String } class Functions(val functions: Fun*) extends Isabelle_System.Service lazy val functions: List[Fun] = Isabelle_System.make_services(classOf[Functions]).flatMap(_.functions) /** demo functions **/ object Echo extends Fun("echo") { val here = Scala_Project.here def apply(arg: String): String = arg } object Sleep extends Fun("sleep") { val here = Scala_Project.here def apply(seconds: String): String = { val t = seconds match { case Value.Double(s) => Time.seconds(s) case _ => error("Malformed argument: " + quote(seconds)) } val t0 = Time.now() t.sleep val t1 = Time.now() (t1 - t0).toString } } /** compiler **/ object Compiler { def context( error: String => Unit = Exn.error, jar_dirs: List[JFile] = Nil): Context = { def find_jars(dir: JFile): List[String] = File.find_files(dir, file => file.getName.endsWith(".jar")). map(File.absolute_name) val class_path = for { prop <- List("isabelle.scala.classpath", "java.class.path") path = System.getProperty(prop, "") if path != "\"\"" elem <- space_explode(JFile.pathSeparatorChar, path) } yield elem val settings = new GenericRunnerSettings(error) settings.classpath.value = (class_path ::: jar_dirs.flatMap(find_jars)).mkString(JFile.pathSeparator) new Context(settings) } def default_print_writer: PrintWriter = new NewLinePrintWriter(new ConsoleWriter, true) class Context private [Compiler](val settings: GenericRunnerSettings) { override def toString: String = settings.toString def interpreter( print_writer: PrintWriter = default_print_writer, class_loader: ClassLoader = null): IMain = { - new IMain(settings, print_writer) + new IMain(settings, new ReplReporterImpl(settings, print_writer)) { override def parentClassLoader: ClassLoader = if (class_loader == null) super.parentClassLoader else class_loader } } def toplevel(interpret: Boolean, source: String): List[String] = { val out = new StringWriter val interp = interpreter(new PrintWriter(out)) val ok = interp.withLabel("\u0001") { if (interpret) interp.interpret(source) == Results.Success else (new interp.ReadEvalPrint).compile(source) } out.close val Error = """(?s)^\S* error: (.*)$""".r val errors = space_explode('\u0001', Library.strip_ansi_color(out.toString)). collect({ case Error(msg) => "Scala error: " + Library.trim_line(msg) }) if (!ok && errors.isEmpty) List("Error") else errors } } } object Toplevel extends Fun("scala_toplevel") { val here = Scala_Project.here def apply(arg: String): String = { val (interpret, source) = YXML.parse_body(arg) match { case Nil => (false, "") case List(XML.Text(source)) => (false, source) case body => import XML.Decode._; pair(bool, string)(body) } val errors = try { Compiler.context().toplevel(interpret, source) } catch { case ERROR(msg) => List(msg) } locally { import XML.Encode._; YXML.string_of_body(list(string)(errors)) } } } /** invoke Scala functions from ML **/ /* invoke function */ object Tag extends Enumeration { val NULL, OK, ERROR, FAIL, INTERRUPT = Value } def function(name: String, arg: String): (Tag.Value, String) = functions.find(fun => fun.name == name) match { case Some(fun) => Exn.capture { fun(arg) } match { case Exn.Res(null) => (Tag.NULL, "") case Exn.Res(res) => (Tag.OK, res) case Exn.Exn(Exn.Interrupt()) => (Tag.INTERRUPT, "") case Exn.Exn(e) => (Tag.ERROR, Exn.message(e)) } case None => (Tag.FAIL, "Unknown Isabelle/Scala function: " + quote(name)) } /* protocol handler */ class Handler extends Session.Protocol_Handler { private var session: Session = null private var futures = Map.empty[String, Future[Unit]] override def init(session: Session): Unit = synchronized { this.session = session } override def exit(): Unit = synchronized { for ((id, future) <- futures) cancel(id, future) futures = Map.empty } private def result(id: String, tag: Scala.Tag.Value, res: String): Unit = synchronized { if (futures.isDefinedAt(id)) { session.protocol_command("Scala.result", id, tag.id.toString, res) futures -= id } } private def cancel(id: String, future: Future[Unit]) { future.cancel result(id, Scala.Tag.INTERRUPT, "") } private def invoke_scala(msg: Prover.Protocol_Output): Boolean = synchronized { msg.properties match { case Markup.Invoke_Scala(name, id, thread) => def body { val (tag, res) = Scala.function(name, msg.text) result(id, tag, res) } val future = if (thread) { Future.thread(name = Isabelle_Thread.make_name(base = "invoke_scala"))(body) } else Future.fork(body) futures += (id -> future) true case _ => false } } private def cancel_scala(msg: Prover.Protocol_Output): Boolean = synchronized { msg.properties match { case Markup.Cancel_Scala(id) => futures.get(id) match { case Some(future) => cancel(id, future) case None => } true case _ => false } } override val functions = List( Markup.Invoke_Scala.name -> invoke_scala, Markup.Cancel_Scala.name -> cancel_scala) } } class Scala_Functions extends Scala.Functions( Scala.Echo, Scala.Sleep, Scala.Toplevel, Doc.Doc_Names, Bibtex.Check_Database, Isabelle_Tool.Isabelle_Tools) diff --git a/src/Pure/Thy/file_format.scala b/src/Pure/Thy/file_format.scala --- a/src/Pure/Thy/file_format.scala +++ b/src/Pure/Thy/file_format.scala @@ -1,98 +1,98 @@ /* Title: Pure/Thy/file_format.scala Author: Makarius -Support for user-defined file formats. +Support for user-defined file formats, associated with active session. */ package isabelle object File_Format { sealed case class Theory_Context(name: Document.Node.Name, content: String) /* registry */ lazy val registry: Registry = new Registry(Isabelle_System.make_services(classOf[File_Format])) final class Registry private [File_Format](file_formats: List[File_Format]) { override def toString: String = file_formats.mkString("File_Format.Environment(", ",", ")") def get(name: String): Option[File_Format] = file_formats.find(_.detect(name)) def get(name: Document.Node.Name): Option[File_Format] = get(name.node) def get_theory(name: Document.Node.Name): Option[File_Format] = get(name.theory) def is_theory(name: Document.Node.Name): Boolean = get_theory(name).isDefined def start_session(session: isabelle.Session): Session = new Session(file_formats.map(_.start(session)).filterNot(_ == No_Agent)) } /* session */ final class Session private[File_Format](agents: List[Agent]) { override def toString: String = agents.mkString("File_Format.Session(", ", ", ")") def prover_options(options: Options): Options = (options /: agents)({ case (opts, agent) => agent.prover_options(opts) }) def stop_session { agents.foreach(_.stop) } } trait Agent { def prover_options(options: Options): Options = options def stop {} } object No_Agent extends Agent } abstract class File_Format extends Isabelle_System.Service { def format_name: String override def toString: String = "File_Format(" + format_name + ")" def file_ext: String def detect(name: String): Boolean = name.endsWith("." + file_ext) /* implicit theory context: name and content */ def theory_suffix: String = "" def theory_content(name: String): String = "" def make_theory_name(resources: Resources, name: Document.Node.Name): Option[Document.Node.Name] = { for { (_, thy) <- Thy_Header.split_file_name(name.node) if detect(name.node) && theory_suffix.nonEmpty } yield { val thy_node = resources.append(name.node, Path.explode(theory_suffix)) Document.Node.Name(thy_node, name.master_dir, thy) } } def make_theory_content(resources: Resources, thy_name: Document.Node.Name): Option[String] = { for { (prefix, suffix) <- Thy_Header.split_file_name(thy_name.node) if detect(prefix) && suffix == theory_suffix (_, thy) <- Thy_Header.split_file_name(prefix) s <- proper_string(theory_content(thy)) } yield s } def html_document(snapshot: Document.Snapshot): Option[Presentation.HTML_Document] = None /* PIDE session agent */ def start(session: isabelle.Session): File_Format.Agent = File_Format.No_Agent } diff --git a/src/Pure/Thy/html.scala b/src/Pure/Thy/html.scala --- a/src/Pure/Thy/html.scala +++ b/src/Pure/Thy/html.scala @@ -1,400 +1,404 @@ /* Title: Pure/Thy/html.scala Author: Makarius HTML presentation elements. */ package isabelle object HTML { /* output text with control symbols */ private val control = Map( Symbol.sub -> "sub", Symbol.sub_decoded -> "sub", Symbol.sup -> "sup", Symbol.sup_decoded -> "sup", Symbol.bold -> "b", Symbol.bold_decoded -> "b") private val control_block = Map( Symbol.bsub -> "", Symbol.bsub_decoded -> "", Symbol.esub -> "", Symbol.esub_decoded -> "", Symbol.bsup -> "", Symbol.bsup_decoded -> "", Symbol.esup -> "", Symbol.esup_decoded -> "") def is_control(sym: Symbol.Symbol): Boolean = control.isDefinedAt(sym) def output_char_permissive(c: Char, s: StringBuilder) { c match { case '<' => s ++= "<" case '>' => s ++= ">" case '&' => s ++= "&" case _ => s += c } } def output(text: String, s: StringBuilder, hidden: Boolean, permissive: Boolean) { def output_char(c: Char): Unit = if (permissive) output_char_permissive(c, s) else XML.output_char(c, s) def output_string(str: String): Unit = str.iterator.foreach(output_char) def output_hidden(body: => Unit): Unit = if (hidden) { s ++= ""; body; s ++= "" } def output_symbol(sym: Symbol.Symbol): Unit = if (sym != "") { control_block.get(sym) match { case Some(html) if html.startsWith(" s ++= html; output_hidden(output_string(sym)) case Some(html) => output_hidden(output_string(sym)); s ++= html case None => if (hidden && Symbol.is_control_encoded(sym)) { output_hidden(output_string(Symbol.control_prefix)) s ++= "" output_string(Symbol.control_name(sym).get) s ++= "" output_hidden(output_string(Symbol.control_suffix)) } else output_string(sym) } } var ctrl = "" for (sym <- Symbol.iterator(text)) { if (is_control(sym)) { output_symbol(ctrl); ctrl = sym } else { control.get(ctrl) match { case Some(elem) if Symbol.is_controllable(sym) => output_hidden(output_symbol(ctrl)) s += '<'; s ++= elem; s += '>' output_symbol(sym) s ++= "' case _ => output_symbol(ctrl) output_symbol(sym) } ctrl = "" } } output_symbol(ctrl) } def output(text: String): String = Library.make_string(output(text, _, hidden = false, permissive = true)) /* output XML as HTML */ private val structural_elements = Set("head", "body", "meta", "div", "pre", "p", "title", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "dl", "li", "dt", "dd") def output(body: XML.Body, s: StringBuilder, hidden: Boolean, structural: Boolean) { def elem(markup: Markup) { s ++= markup.name for ((a, b) <- markup.properties) { s += ' ' s ++= a s += '=' s += '"' output(b, s, hidden = hidden, permissive = false) s += '"' } } def tree(t: XML.Tree): Unit = t match { case XML.Elem(markup, Nil) => s += '<'; elem(markup); s ++= "/>" case XML.Elem(markup, ts) => if (structural && structural_elements(markup.name)) s += '\n' s += '<'; elem(markup); s += '>' ts.foreach(tree) s ++= "' if (structural && structural_elements(markup.name)) s += '\n' case XML.Text(txt) => output(txt, s, hidden = hidden, permissive = true) } body.foreach(tree) } def output(body: XML.Body, hidden: Boolean, structural: Boolean): String = Library.make_string(output(body, _, hidden, structural)) def output(tree: XML.Tree, hidden: Boolean, structural: Boolean): String = output(List(tree), hidden, structural) /* attributes */ class Attribute(val name: String, value: String) { def xml: XML.Attribute = name -> value def apply(elem: XML.Elem): XML.Elem = elem + xml } def id(s: String): Attribute = new Attribute("id", s) def class_(name: String): Attribute = new Attribute("class", name) def width(w: Int): Attribute = new Attribute("width", w.toString) def height(h: Int): Attribute = new Attribute("height", h.toString) def size(w: Int, h: Int)(elem: XML.Elem): XML.Elem = width(w)(height(h)(elem)) /* structured markup operators */ def text(txt: String): XML.Body = if (txt.isEmpty) Nil else List(XML.Text(txt)) val break: XML.Body = List(XML.elem("br")) val nl: XML.Body = List(XML.Text("\n")) class Operator(val name: String) { def apply(body: XML.Body): XML.Elem = XML.elem(name, body) def apply(att: Attribute, body: XML.Body): XML.Elem = att(apply(body)) def apply(c: String, body: XML.Body): XML.Elem = apply(class_(c), body) } class Heading(name: String) extends Operator(name) { def apply(txt: String): XML.Elem = super.apply(text(txt)) def apply(att: Attribute, txt: String): XML.Elem = super.apply(att, text(txt)) def apply(c: String, txt: String): XML.Elem = super.apply(c, text(txt)) } val div = new Operator("div") val span = new Operator("span") val pre = new Operator("pre") val par = new Operator("p") val emph = new Operator("em") val bold = new Operator("b") val code = new Operator("code") val item = new Operator("li") val list = new Operator("ul") val enum = new Operator("ol") val descr = new Operator("dl") val dt = new Operator("dt") val dd = new Operator("dd") val title = new Heading("title") val chapter = new Heading("h1") val section = new Heading("h2") val subsection = new Heading("h3") val subsubsection = new Heading("h4") val paragraph = new Heading("h5") val subparagraph = new Heading("h6") def itemize(items: List[XML.Body]): XML.Elem = list(items.map(item(_))) def enumerate(items: List[XML.Body]): XML.Elem = enum(items.map(item(_))) def description(items: List[(XML.Body, XML.Body)]): XML.Elem = descr(items.flatMap({ case (x, y) => List(dt(x), dd(y)) })) def link(href: String, body: XML.Body): XML.Elem = XML.Elem(Markup("a", List("href" -> href)), if (body.isEmpty) text(href) else body) def link(path: Path, body: XML.Body): XML.Elem = link(path.implode, body) def image(src: String, alt: String = ""): XML.Elem = XML.Elem(Markup("img", List("src" -> src) ::: proper_string(alt).map("alt" -> _).toList), Nil) def source(body: XML.Body): XML.Elem = pre("source", body) def source(src: String): XML.Elem = source(text(src)) def style(s: String): XML.Elem = XML.elem("style", text(s)) def style_file(href: String): XML.Elem = XML.Elem(Markup("link", List("rel" -> "stylesheet", "type" -> "text/css", "href" -> href)), Nil) def style_file(path: Path): XML.Elem = style_file(Url.print_file(path.file)) def script(s: String): XML.Elem = XML.elem("script", text(s)) def script_file(href: String): XML.Elem = XML.Elem(Markup("script", List("src" -> href)), Nil) def script_file(path: Path): XML.Elem = script_file(Url.print_file(path.file)) /* messages */ // background val writeln_message: Attribute = class_("writeln_message") val warning_message: Attribute = class_("warning_message") val error_message: Attribute = class_("error_message") // underline val writeln: Attribute = class_("writeln") val warning: Attribute = class_("warning") val error: Attribute = class_("error") /* tooltips */ def tooltip(item: XML.Body, tip: XML.Body): XML.Elem = span(item ::: List(div("tooltip", tip))) def tooltip_errors(item: XML.Body, msgs: List[XML.Body]): XML.Elem = HTML.error(tooltip(item, msgs.map(msg => error_message(pre(msg))))) /* GUI elements */ object GUI { private def optional_value(text: String): XML.Attributes = proper_string(text).map(a => "value" -> a).toList private def optional_name(name: String): XML.Attributes = proper_string(name).map(a => "name" -> a).toList private def optional_title(tooltip: String): XML.Attributes = proper_string(tooltip).map(a => "title" -> a).toList private def optional_submit(submit: Boolean): XML.Attributes = if (submit) List("onChange" -> "this.form.submit()") else Nil private def optional_checked(selected: Boolean): XML.Attributes = if (selected) List("checked" -> "") else Nil private def optional_action(action: String): XML.Attributes = proper_string(action).map(a => "action" -> a).toList private def optional_onclick(script: String): XML.Attributes = proper_string(script).map(a => "onclick" -> a).toList private def optional_onchange(script: String): XML.Attributes = proper_string(script).map(a => "onchange" -> a).toList def button(body: XML.Body, name: String = "", tooltip: String = "", submit: Boolean = false, script: String = ""): XML.Elem = XML.Elem( Markup("button", List("type" -> (if (submit) "submit" else "button"), "value" -> "true") ::: optional_name(name) ::: optional_title(tooltip) ::: optional_onclick(script)), body) def checkbox(body: XML.Body, name: String = "", tooltip: String = "", submit: Boolean = false, selected: Boolean = false, script: String = ""): XML.Elem = XML.elem("label", XML.elem( Markup("input", List("type" -> "checkbox", "value" -> "true") ::: optional_name(name) ::: optional_title(tooltip) ::: optional_submit(submit) ::: optional_checked(selected) ::: optional_onchange(script))) :: body) def text_field(columns: Int = 0, text: String = "", name: String = "", tooltip: String = "", submit: Boolean = false, script: String = ""): XML.Elem = XML.elem(Markup("input", List("type" -> "text") ::: (if (columns > 0) List("size" -> columns.toString) else Nil) ::: optional_value(text) ::: optional_name(name) ::: optional_title(tooltip) ::: optional_submit(submit) ::: optional_onchange(script))) def parameter(text: String = "", name: String = ""): XML.Elem = XML.elem( Markup("input", List("type" -> "hidden") ::: optional_value(text) ::: optional_name(name))) def form(body: XML.Body, name: String = "", action: String = "", http_post: Boolean = false) : XML.Elem = XML.Elem( Markup("form", optional_name(name) ::: optional_action(action) ::: (if (http_post) List("method" -> "post") else Nil)), body) } /* GUI layout */ object Wrap_Panel { object Alignment extends Enumeration { val left, right, center = Value } def apply(contents: List[XML.Elem], name: String = "", action: String = "", alignment: Alignment.Value = Alignment.right): XML.Elem = { val body = Library.separate(XML.Text(" "), contents) GUI.form(List(div(body) + ("style" -> ("text-align: " + alignment))), name = name, action = action) } } /* document */ val header: String = XML.header + """ """ + val footer: String = """""" + val head_meta: XML.Elem = XML.Elem(Markup("meta", List("http-equiv" -> "Content-Type", "content" -> "text/html; charset=utf-8")), Nil) def output_document(head: XML.Body, body: XML.Body, css: String = "isabelle.css", hidden: Boolean = true, structural: Boolean = true): String = { cat_lines( - List(header, + List( + header, output( XML.elem("head", head_meta :: (if (css == "") Nil else List(style_file(css))) ::: head), hidden = hidden, structural = structural), output(XML.elem("body", body), - hidden = hidden, structural = structural))) + hidden = hidden, structural = structural), + footer)) } /* fonts */ def fonts_url(): String => String = (for (entry <- Isabelle_Fonts.fonts(hidden = true)) yield (entry.path.file_name -> Url.print_file(entry.path.file))).toMap def fonts_dir(prefix: String)(ttf_name: String): String = prefix + "/" + ttf_name def fonts_css(make_url: String => String = fonts_url()): String = { def font_face(entry: Isabelle_Fonts.Entry): String = cat_lines( List( "@font-face {", " font-family: '" + entry.family + "';", " src: url('" + make_url(entry.path.file_name) + "') format('truetype');") ::: (if (entry.is_bold) List(" font-weight: bold;") else Nil) ::: (if (entry.is_italic) List(" font-style: italic;") else Nil) ::: List("}")) ("/* Isabelle fonts */" :: Isabelle_Fonts.fonts(hidden = true).map(font_face)) .mkString("", "\n\n", "\n") } /* document directory */ def isabelle_css: Path = Path.explode("~~/etc/isabelle.css") def write_isabelle_css(dir: Path, make_url: String => String = fonts_dir("fonts")) { File.write(dir + isabelle_css.base, fonts_css(make_url) + "\n\n" + File.read(isabelle_css)) } def init_dir(dir: Path): Unit = write_isabelle_css(Isabelle_System.make_directory(dir)) def write_document(dir: Path, name: String, head: XML.Body, body: XML.Body, css: String = isabelle_css.file_name, hidden: Boolean = true, structural: Boolean = true) { init_dir(dir) File.write(dir + Path.basic(name), output_document(head, body, css = css, hidden = hidden, structural = structural)) } } diff --git a/src/Pure/Tools/build_job.scala b/src/Pure/Tools/build_job.scala --- a/src/Pure/Tools/build_job.scala +++ b/src/Pure/Tools/build_job.scala @@ -1,539 +1,538 @@ /* Title: Pure/Tools/build_job.scala Author: Makarius Build job running prover process, with rudimentary PIDE session. */ package isabelle import scala.collection.mutable object Build_Job { /* theory markup/messages from database */ def read_theory( db_context: Sessions.Database_Context, resources: Resources, session: String, theory: String, unicode_symbols: Boolean = false): Option[Command] = { def read(name: String): Export.Entry = db_context.get_export(List(session), theory, name) def read_xml(name: String): XML.Body = YXML.parse_body( Symbol.output(unicode_symbols, UTF8.decode_permissive(read(name).uncompressed)), cache = db_context.cache) (read(Export.DOCUMENT_ID).text, split_lines(read(Export.FILES).text)) match { case (Value.Long(id), thy_file :: blobs_files) => val node_name = resources.file_node(Path.explode(thy_file), theory = theory) val results = Command.Results.make( for (elem @ XML.Elem(Markup(_, Markup.Serial(i)), _) <- read_xml(Export.MESSAGES)) yield i -> elem) val blobs = blobs_files.map(file => { val path = Path.explode(file) val name = resources.file_node(path) val src_path = File.relative_path(node_name.master_dir_path, path).getOrElse(path) Command.Blob(name, src_path, None) }) val blobs_xml = for (i <- (1 to blobs.length).toList) yield read_xml(Export.MARKUP + i) val blobs_info = Command.Blobs_Info( for { (Command.Blob(name, src_path, _), xml) <- blobs zip blobs_xml } yield { val text = XML.content(xml) val chunk = Symbol.Text_Chunk(text) val digest = SHA1.digest(Symbol.encode(text)) Exn.Res(Command.Blob(name, src_path, Some((digest, chunk)))) }) val thy_xml = read_xml(Export.MARKUP) val thy_source = XML.content(thy_xml) val markups_index = Command.Markup_Index.markup :: blobs.map(Command.Markup_Index.blob) val markups = Command.Markups.make( for ((index, xml) <- markups_index.zip(thy_xml :: blobs_xml)) yield index -> Markup_Tree.from_XML(xml)) val command = Command.unparsed(thy_source, theory = true, id = id, node_name = node_name, blobs_info = blobs_info, results = results, markups = markups) Some(command) case _ => None } } /* print messages */ def print_log( options: Options, session_name: String, theories: List[String] = Nil, verbose: Boolean = false, progress: Progress = new Progress, margin: Double = Pretty.default_margin, breakgain: Double = Pretty.default_breakgain, metric: Pretty.Metric = Symbol.Metric, unicode_symbols: Boolean = false) { val store = Sessions.store(options) val resources = Resources.empty val session = new Session(options, resources) using(store.open_database_context())(db_context => { val result = db_context.input_database(session_name)((db, _) => { val theories = store.read_theories(db, session_name) val errors = store.read_errors(db, session_name) store.read_build(db, session_name).map(info => (theories, errors, info.return_code)) }) result match { case None => error("Missing build database for session " + quote(session_name)) case Some((used_theories, errors, rc)) => val bad_theories = theories.filterNot(used_theories.toSet) if (bad_theories.nonEmpty) error("Unknown theories " + commas_quote(bad_theories)) val print_theories = if (theories.isEmpty) used_theories else used_theories.filter(theories.toSet) for (thy <- print_theories) { val thy_heading = "\nTheory " + quote(thy) + ":" read_theory(db_context, resources, session_name, thy, unicode_symbols = unicode_symbols) match { case None => progress.echo(thy_heading + " MISSING") case Some(command) => val snapshot = Document.State.init.snippet(command) val rendering = new Rendering(snapshot, options, session) val messages = rendering.text_messages(Text.Range.full) .filter(message => verbose || Protocol.is_exported(message.info)) if (messages.nonEmpty) { val line_document = Line.Document(command.source) progress.echo(thy_heading) for (Text.Info(range, elem) <- messages) { val line = line_document.position(range.start).line1 val pos = Position.Line_File(line, command.node_name.node) progress.echo( Protocol.message_text(elem, heading = true, pos = pos, margin = margin, breakgain = breakgain, metric = metric)) } } } } if (errors.nonEmpty) { val msg = Symbol.output(unicode_symbols, cat_lines(errors)) progress.echo("\nBuild errors:\n" + Output.error_message_text(msg)) } if (rc != 0) progress.echo("\n" + Process_Result.print_return_code(rc)) } }) } /* Isabelle tool wrapper */ val isabelle_tool = Isabelle_Tool("log", "print messages from build database", Scala_Project.here, args => { /* arguments */ var unicode_symbols = false var theories: List[String] = Nil var margin = Pretty.default_margin var options = Options.init() var verbose = false val getopts = Getopts(""" Usage: isabelle log [OPTIONS] SESSION Options are: -T NAME restrict to given theories (multiple options possible) -U output Unicode symbols -m MARGIN margin for pretty printing (default: """ + margin + """) -o OPTION override Isabelle system OPTION (via NAME=VAL or NAME) -v print all messages, including information, tracing etc. Print messages from the build database of the given session, without any checks against current sources: results from a failed build can be printed as well. """, "T:" -> (arg => theories = theories ::: List(arg)), "U" -> (_ => unicode_symbols = true), "m:" -> (arg => margin = Value.Double.parse(arg)), "o:" -> (arg => options = options + arg), "v" -> (_ => verbose = true)) val more_args = getopts(args) val session_name = more_args match { case List(session_name) => session_name case _ => getopts.usage() } val progress = new Console_Progress() print_log(options, session_name, theories = theories, verbose = verbose, margin = margin, progress = progress, unicode_symbols = unicode_symbols) }) } class Build_Job(progress: Progress, session_name: String, val info: Sessions.Info, deps: Sessions.Deps, store: Sessions.Store, do_store: Boolean, verbose: Boolean, val numa_node: Option[Int], command_timings0: List[Properties.T]) { val options: Options = NUMA.policy_options(info.options, numa_node) private val sessions_structure = deps.sessions_structure private val future_result: Future[Process_Result] = Future.thread("build", uninterruptible = true) { val parent = info.parent.getOrElse("") val base = deps(parent) val result_base = deps(session_name) val env = Isabelle_System.settings() + ("ISABELLE_ML_DEBUGGER" -> options.bool("ML_debugger").toString) val is_pure = Sessions.is_pure(session_name) val use_prelude = if (is_pure) Thy_Header.ml_roots.map(_._1) else Nil val eval_store = if (do_store) { (if (info.theories.nonEmpty) List("ML_Heap.share_common_data ()") else Nil) ::: List("ML_Heap.save_child " + ML_Syntax.print_string_bytes(File.platform_path(store.output_heap(session_name)))) } else Nil val resources = new Resources(sessions_structure, base, command_timings = command_timings0) val session = new Session(options, resources) { override val cache: XML.Cache = store.cache override def build_blobs_info(name: Document.Node.Name): Command.Blobs_Info = { result_base.load_commands.get(name.expand) match { case Some(spans) => val syntax = result_base.theory_syntax(name) Command.build_blobs_info(syntax, name, spans) case None => Command.Blobs_Info.none } } } object Build_Session_Errors { private val promise: Promise[List[String]] = Future.promise def result: Exn.Result[List[String]] = promise.join_result def cancel: Unit = promise.cancel def apply(errs: List[String]) { try { promise.fulfill(errs) } catch { case _: IllegalStateException => } } } val export_consumer = Export.consumer(store.open_database(session_name, output = true), store.cache) val stdout = new StringBuilder(1000) val stderr = new StringBuilder(1000) val command_timings = new mutable.ListBuffer[Properties.T] val theory_timings = new mutable.ListBuffer[Properties.T] val session_timings = new mutable.ListBuffer[Properties.T] val runtime_statistics = new mutable.ListBuffer[Properties.T] val task_statistics = new mutable.ListBuffer[Properties.T] def fun( name: String, acc: mutable.ListBuffer[Properties.T], unapply: Properties.T => Option[Properties.T]): (String, Session.Protocol_Function) = { name -> ((msg: Prover.Protocol_Output) => unapply(msg.properties) match { case Some(props) => acc += props; true case _ => false }) } session.init_protocol_handler(new Session.Protocol_Handler { override def exit() { Build_Session_Errors.cancel } private def build_session_finished(msg: Prover.Protocol_Output): Boolean = { val (rc, errors) = try { val (rc, errs) = { import XML.Decode._ pair(int, list(x => x))(Symbol.decode_yxml(msg.text)) } val errors = for (err <- errs) yield { val prt = Protocol_Message.expose_no_reports(err) Pretty.string_of(prt, metric = Symbol.Metric) } (rc, errors) } catch { case ERROR(err) => (2, List(err)) } session.protocol_command("Prover.stop", rc.toString) Build_Session_Errors(errors) true } private def loading_theory(msg: Prover.Protocol_Output): Boolean = msg.properties match { case Markup.Loading_Theory(Markup.Name(name)) => progress.theory(Progress.Theory(name, session = session_name)) false case _ => false } private def export(msg: Prover.Protocol_Output): Boolean = msg.properties match { case Protocol.Export(args) => export_consumer(session_name, args, msg.bytes) true case _ => false } override val functions = List( Markup.Build_Session_Finished.name -> build_session_finished, Markup.Loading_Theory.name -> loading_theory, Markup.EXPORT -> export, fun(Markup.Theory_Timing.name, theory_timings, Markup.Theory_Timing.unapply), fun(Markup.Session_Timing.name, session_timings, Markup.Session_Timing.unapply), fun(Markup.Task_Statistics.name, task_statistics, Markup.Task_Statistics.unapply)) }) session.command_timings += Session.Consumer("command_timings") { case Session.Command_Timing(props) => for { elapsed <- Markup.Elapsed.unapply(props) elapsed_time = Time.seconds(elapsed) if elapsed_time.is_relevant && elapsed_time >= options.seconds("command_timing_threshold") } command_timings += props.filter(Markup.command_timing_property) } session.runtime_statistics += Session.Consumer("ML_statistics") { case Session.Runtime_Statistics(props) => runtime_statistics += props } session.finished_theories += Session.Consumer[Document.Snapshot]("finished_theories") { case snapshot => val rendering = new Rendering(snapshot, options, session) def export(name: String, xml: XML.Body, compress: Boolean = true) { val theory_name = snapshot.node_name.theory val args = Protocol.Export.Args(theory_name = theory_name, name = name, compress = compress) val bytes = Bytes(Symbol.encode(YXML.string_of_body(xml))) if (!bytes.is_empty) export_consumer(session_name, args, bytes) } def export_text(name: String, text: String, compress: Boolean = true): Unit = export(name, List(XML.Text(text)), compress = compress) for (command <- snapshot.snippet_command) { export_text(Export.DOCUMENT_ID, command.id.toString, compress = false) } export_text(Export.FILES, cat_lines(snapshot.node_files.map(_.symbolic.node)), compress = false) for (((_, xml), i) <- snapshot.xml_markup_blobs().zipWithIndex) { export(Export.MARKUP + (i + 1), xml) } export(Export.MARKUP, snapshot.xml_markup()) export(Export.MESSAGES, snapshot.messages.map(_._1)) val citations = Library.distinct(rendering.citations(Text.Range.full).map(_.info)) export_text(Export.CITATIONS, cat_lines(citations)) } session.all_messages += Session.Consumer[Any]("build_session_output") { case msg: Prover.Output => val message = msg.message if (msg.is_stdout) { stdout ++= Symbol.encode(XML.content(message)) } else if (msg.is_stderr) { stderr ++= Symbol.encode(XML.content(message)) } else if (msg.is_exit) { val err = "Prover terminated" + (msg.properties match { case Markup.Process_Result(result) => ": " + result.print_rc case _ => "" }) Build_Session_Errors(List(err)) } case _ => } val eval_main = Command_Line.ML_tool("Isabelle_Process.init_build ()" :: eval_store) val process = Isabelle_Process(session, options, sessions_structure, store, logic = parent, raw_ml_system = is_pure, use_prelude = use_prelude, eval_main = eval_main, cwd = info.dir.file, env = env) val build_errors = Isabelle_Thread.interrupt_handler(_ => process.terminate) { Exn.capture { process.await_startup } match { case Exn.Res(_) => val resources_yxml = resources.init_session_yxml val args_yxml = YXML.string_of_body( { import XML.Encode._ pair(string, list(pair(Options.encode, list(pair(string, properties)))))( (session_name, info.theories)) }) session.protocol_command("build_session", resources_yxml, args_yxml) Build_Session_Errors.result case Exn.Exn(exn) => Exn.Res(List(Exn.message(exn))) } } val process_result = Isabelle_Thread.interrupt_handler(_ => process.terminate) { process.await_shutdown } session.stop() val export_errors = export_consumer.shutdown(close = true).map(Output.error_message_text) val (document_output, document_errors) = try { if (build_errors.isInstanceOf[Exn.Res[_]] && process_result.ok && info.documents.nonEmpty) { using(store.open_database_context())(db_context => { val documents = Presentation.build_documents(session_name, deps, db_context, output_sources = info.document_output, output_pdf = info.document_output, progress = progress, verbose = verbose) db_context.output_database(session_name)(db => documents.foreach(_.write(db, session_name))) (documents.flatMap(_.log_lines), Nil) }) } else (Nil, Nil) } catch { case exn: Presentation.Build_Error => (exn.log_lines, List(exn.message)) case Exn.Interrupt.ERROR(msg) => (Nil, List(msg)) } val result = { val theory_timing = theory_timings.iterator.map( { case props @ Markup.Name(name) => name -> props }).toMap val used_theory_timings = for { (name, _) <- deps(session_name).used_theories } yield theory_timing.getOrElse(name.theory, Markup.Name(name.theory)) val more_output = Library.trim_line(stdout.toString) :: command_timings.toList.map(Protocol.Command_Timing_Marker.apply) ::: used_theory_timings.map(Protocol.Theory_Timing_Marker.apply) ::: session_timings.toList.map(Protocol.Session_Timing_Marker.apply) ::: runtime_statistics.toList.map(Protocol.ML_Statistics_Marker.apply) ::: task_statistics.toList.map(Protocol.Task_Statistics_Marker.apply) ::: document_output process_result.output(more_output) .error(Library.trim_line(stderr.toString)) .errors_rc(export_errors ::: document_errors) } build_errors match { case Exn.Res(build_errs) => val errs = build_errs ::: document_errors if (errs.isEmpty) result else { result.error_rc.output( errs.flatMap(s => split_lines(Output.error_message_text(s))) ::: errs.map(Protocol.Error_Message_Marker.apply)) } case Exn.Exn(Exn.Interrupt()) => if (result.ok) result.copy(rc = Exn.Interrupt.return_code) else result case Exn.Exn(exn) => throw exn } } def terminate: Unit = future_result.cancel def is_finished: Boolean = future_result.is_finished private val timeout_request: Option[Event_Timer.Request] = { if (info.timeout > Time.zero) Some(Event_Timer.request(Time.now() + info.timeout) { terminate }) else None } def join: (Process_Result, Option[String]) = { val result1 = future_result.join val was_timeout = timeout_request match { case None => false case Some(request) => !request.cancel } val result2 = - if (result1.interrupted) { - if (was_timeout) result1.error(Output.error_message_text("Timeout")).was_timeout - else result1.error(Output.error_message_text("Interrupt")) - } + if (result1.ok) result1 + else if (was_timeout) result1.error(Output.error_message_text("Timeout")).timeout_rc + else if (result1.interrupted) result1.error(Output.error_message_text("Interrupt")) else result1 val heap_digest = if (result2.ok && do_store && store.output_heap(session_name).is_file) Some(Sessions.write_heap_digest(store.output_heap(session_name))) else None (result2, heap_digest) } } diff --git a/src/Pure/Tools/server.scala b/src/Pure/Tools/server.scala --- a/src/Pure/Tools/server.scala +++ b/src/Pure/Tools/server.scala @@ -1,584 +1,597 @@ /* Title: Pure/Tools/server.scala Author: Makarius Resident Isabelle servers. Message formats: - short message (single line): NAME ARGUMENT - long message (multiple lines): BYTE_LENGTH NAME ARGUMENT Argument formats: - Unit as empty string - XML.Elem in YXML notation - JSON.T in standard notation */ package isabelle import java.io.{BufferedInputStream, BufferedOutputStream, InputStreamReader, OutputStreamWriter, IOException} import java.net.{Socket, SocketException, SocketTimeoutException, ServerSocket, InetAddress} object Server { /* message argument */ object Argument { def is_name_char(c: Char): Boolean = Symbol.is_ascii_letter(c) || Symbol.is_ascii_digit(c) || c == '_' || c == '.' def split(msg: String): (String, String) = { val name = msg.takeWhile(is_name_char) val argument = msg.substring(name.length).dropWhile(Symbol.is_ascii_blank) (name, argument) } def print(arg: Any): String = arg match { case () => "" case t: XML.Elem => YXML.string_of_tree(t) case t: JSON.T => JSON.Format(t) } def parse(argument: String): Any = if (argument == "") () else if (YXML.detect_elem(argument)) YXML.parse_elem(argument) else JSON.parse(argument, strict = false) def unapply(argument: String): Option[Any] = try { Some(parse(argument)) } catch { case ERROR(_) => None } } /* input command */ type Command_Body = PartialFunction[(Context, Any), Any] abstract class Command(val command_name: String) { def command_body: Command_Body override def toString: String = command_name } class Commands(commands: Command*) extends Isabelle_System.Service { def entries: List[Command] = commands.toList } private lazy val command_table: Map[String, Command] = (Map.empty[String, Command] /: Isabelle_System.make_services(classOf[Commands]).flatMap(_.entries))( { case (cmds, cmd) => val name = cmd.command_name if (cmds.isDefinedAt(name)) error("Duplicate Isabelle server command: " + quote(name)) else cmds + (name -> cmd) }) /* output reply */ class Error(val message: String, val json: JSON.Object.T = JSON.Object.empty) extends RuntimeException(message) def json_error(exn: Throwable): JSON.Object.T = exn match { case e: Error => Reply.error_message(e.message) ++ e.json case ERROR(msg) => Reply.error_message(msg) case _ if Exn.is_interrupt(exn) => Reply.error_message(Exn.message(exn)) case _ => JSON.Object.empty } object Reply extends Enumeration { val OK, ERROR, FINISHED, FAILED, NOTE = Value def message(msg: String, kind: String = ""): JSON.Object.T = JSON.Object(Markup.KIND -> proper_string(kind).getOrElse(Markup.WRITELN), "message" -> msg) def error_message(msg: String): JSON.Object.T = message(msg, kind = Markup.ERROR) def unapply(msg: String): Option[(Reply.Value, Any)] = { if (msg == "") None else { val (name, argument) = Argument.split(msg) for { reply <- try { Some(withName(name)) } catch { case _: NoSuchElementException => None } arg <- Argument.unapply(argument) } yield (reply, arg) } } } + /* handler: port, password, thread */ + + abstract class Handler(port0: Int) + { + val socket: ServerSocket = new ServerSocket(port0, 50, Server.localhost) + def port: Int = socket.getLocalPort + val password: String = UUID.random_string() + + override def toString: String = print(port, password) + + def handle(connection: Server.Connection): Unit + + private lazy val thread: Thread = + Isabelle_Thread.fork(name = "server_handler") { + var finished = false + while (!finished) { + Exn.capture(socket.accept) match { + case Exn.Res(client) => + Isabelle_Thread.fork(name = "server_connection") { + using(Connection(client))(connection => + if (connection.read_password(password)) handle(connection)) + } + case Exn.Exn(_) => finished = true + } + } + } + + def start { thread } + def join { thread.join } + def stop { socket.close; join } + } + + /* socket connection */ object Connection { def apply(socket: Socket): Connection = new Connection(socket) } class Connection private(socket: Socket) extends AutoCloseable { override def toString: String = socket.toString def close() { socket.close } def set_timeout(t: Time) { socket.setSoTimeout(t.ms.toInt) } private val in = new BufferedInputStream(socket.getInputStream) private val out = new BufferedOutputStream(socket.getOutputStream) private val out_lock: AnyRef = new Object def tty_loop(): TTY_Loop = new TTY_Loop( new OutputStreamWriter(out), new InputStreamReader(in), writer_lock = out_lock) def read_password(password: String): Boolean = try { Byte_Message.read_line(in).map(_.text) == Some(password) } catch { case _: IOException => false } def read_message(): Option[String] = try { Byte_Message.read_line_message(in).map(_.text) } catch { case _: IOException => None } + def await_close(): Unit = + try { Byte_Message.read(in, 1); socket.close() } + catch { case _: IOException => } + def write_message(msg: String): Unit = out_lock.synchronized { Byte_Message.write_line_message(out, Bytes(UTF8.bytes(msg))) } def reply(r: Reply.Value, arg: Any) { val argument = Argument.print(arg) write_message(if (argument == "") r.toString else r.toString + " " + argument) } def reply_ok(arg: Any) { reply(Reply.OK, arg) } def reply_error(arg: Any) { reply(Reply.ERROR, arg) } def reply_error_message(message: String, more: JSON.Object.Entry*): Unit = reply_error(Reply.error_message(message) ++ more) def notify(arg: Any) { reply(Reply.NOTE, arg) } } /* context with output channels */ class Context private[Server](val server: Server, connection: Connection) extends AutoCloseable { context => def command_list: List[String] = command_table.keys.toList.sorted def reply(r: Reply.Value, arg: Any) { connection.reply(r, arg) } def notify(arg: Any) { connection.notify(arg) } def message(kind: String, msg: String, more: JSON.Object.Entry*): Unit = notify(Reply.message(msg, kind = kind) ++ more) def writeln(msg: String, more: JSON.Object.Entry*): Unit = message(Markup.WRITELN, msg, more:_*) def warning(msg: String, more: JSON.Object.Entry*): Unit = message(Markup.WARNING, msg, more:_*) def error_message(msg: String, more: JSON.Object.Entry*): Unit = message(Markup.ERROR, msg, more:_*) def progress(more: JSON.Object.Entry*): Connection_Progress = new Connection_Progress(context, more:_*) override def toString: String = connection.toString /* asynchronous tasks */ private val _tasks = Synchronized(Set.empty[Task]) def make_task(body: Task => JSON.Object.T): Task = { val task = new Task(context, body) _tasks.change(_ + task) task } def remove_task(task: Task): Unit = _tasks.change(_ - task) def cancel_task(id: UUID.T): Unit = _tasks.change(tasks => { tasks.find(task => task.id == id).foreach(_.cancel); tasks }) def close() { while(_tasks.change_result(tasks => { tasks.foreach(_.cancel); (tasks.nonEmpty, tasks) })) { _tasks.value.foreach(_.join) } } } class Connection_Progress private[Server](context: Context, more: JSON.Object.Entry*) extends Progress { override def echo(msg: String): Unit = context.writeln(msg, more:_*) override def echo_warning(msg: String): Unit = context.warning(msg, more:_*) override def echo_error_message(msg: String): Unit = context.error_message(msg, more:_*) override def theory(theory: Progress.Theory) { val entries: List[JSON.Object.Entry] = List("theory" -> theory.theory, "session" -> theory.session) ::: (theory.percentage match { case None => Nil case Some(p) => List("percentage" -> p) }) context.writeln(theory.message, entries ::: more.toList:_*) } override def nodes_status(nodes_status: Document_Status.Nodes_Status) { val json = for ((name, node_status) <- nodes_status.present) - yield name.json + ("status" -> nodes_status(name).json) + yield name.json + ("status" -> node_status.json) context.notify(JSON.Object(Markup.KIND -> Markup.NODES_STATUS, Markup.NODES_STATUS -> json)) } override def toString: String = context.toString } class Task private[Server](val context: Context, body: Task => JSON.Object.T) { task => val id: UUID.T = UUID.random() val ident: JSON.Object.Entry = ("task" -> id.toString) val progress: Connection_Progress = context.progress(ident) def cancel { progress.stop } private lazy val thread = Isabelle_Thread.fork(name = "server_task") { Exn.capture { body(task) } match { case Exn.Res(res) => context.reply(Reply.FINISHED, res + ident) case Exn.Exn(exn) => val err = json_error(exn) if (err.isEmpty) throw exn else context.reply(Reply.FAILED, err + ident) } progress.stop context.remove_task(task) } def start { thread } def join { thread.join } } /* server info */ val localhost_name: String = "127.0.0.1" def localhost: InetAddress = InetAddress.getByName(localhost_name) def print_address(port: Int): String = localhost_name + ":" + port def print(port: Int, password: String): String = print_address(port) + " (password " + quote(password) + ")" object Info { private val Pattern = ("""server "([^"]*)" = \Q""" + localhost_name + """\E:(\d+) \(password "([^"]*)"\)""").r def parse(s: String): Option[Info] = s match { case Pattern(name, Value.Int(port), password) => Some(Info(name, port, password)) case _ => None } def apply(name: String, port: Int, password: String): Info = new Info(name, port, password) } class Info private(val name: String, val port: Int, val password: String) { def address: String = print_address(port) override def toString: String = "server " + quote(name) + " = " + print(port, password) def connection(): Connection = { val connection = Connection(new Socket(localhost, port)) connection.write_message(password) connection } def active(): Boolean = try { using(connection())(connection => { connection.set_timeout(Time.seconds(2.0)) connection.read_message() match { case Some(Reply(Reply.OK, _)) => true case _ => false } }) } catch { case _: IOException => false case _: SocketException => false case _: SocketTimeoutException => false } } /* per-user servers */ val default_name = "isabelle" object Data { val database = Path.explode("$ISABELLE_HOME_USER/servers.db") val name = SQL.Column.string("name").make_primary_key val port = SQL.Column.int("port") val password = SQL.Column.string("password") val table = SQL.Table("isabelle_servers", List(name, port, password)) } def list(db: SQLite.Database): List[Info] = if (db.tables.contains(Data.table.name)) { db.using_statement(Data.table.select())(stmt => stmt.execute_query().iterator(res => Info( res.string(Data.name), res.int(Data.port), res.string(Data.password))).toList.sortBy(_.name)) } else Nil def find(db: SQLite.Database, name: String): Option[Info] = list(db).find(server_info => server_info.name == name && server_info.active) def init( name: String = default_name, port: Int = 0, existing_server: Boolean = false, log: Logger = No_Logger): (Info, Option[Server]) = { using(SQLite.open_database(Data.database))(db => { db.transaction { Isabelle_System.chmod("600", Data.database) db.create_table(Data.table) list(db).filterNot(_.active).foreach(server_info => db.using_statement(Data.table.delete(Data.name.where_equal(server_info.name)))( _.execute)) } db.transaction { find(db, name) match { case Some(server_info) => (server_info, None) case None => if (existing_server) error("Isabelle server " + quote(name) + " not running") val server = new Server(port, log) val server_info = Info(name, server.port, server.password) db.using_statement(Data.table.delete(Data.name.where_equal(name)))(_.execute) db.using_statement(Data.table.insert())(stmt => { stmt.string(1) = server_info.name stmt.int(2) = server_info.port stmt.string(3) = server_info.password stmt.execute() }) server.start (server_info, Some(server)) } } }) } def exit(name: String = default_name): Boolean = { using(SQLite.open_database(Data.database))(db => db.transaction { find(db, name) match { case Some(server_info) => using(server_info.connection())(_.write_message("shutdown")) while(server_info.active) { Time.seconds(0.05).sleep } true case None => false } }) } /* Isabelle tool wrapper */ val isabelle_tool = Isabelle_Tool("server", "manage resident Isabelle servers", Scala_Project.here, args => { var console = false var log_file: Option[Path] = None var operation_list = false var operation_exit = false var name = default_name var port = 0 var existing_server = false val getopts = Getopts(""" Usage: isabelle server [OPTIONS] Options are: -L FILE logging on FILE -c console interaction with specified server -l list servers (alternative operation) -n NAME explicit server name (default: """ + default_name + """) -p PORT explicit server port -s assume existing server, no implicit startup -x exit specified server (alternative operation) Manage resident Isabelle servers. """, "L:" -> (arg => log_file = Some(Path.explode(File.standard_path(arg)))), "c" -> (_ => console = true), "l" -> (_ => operation_list = true), "n:" -> (arg => name = arg), "p:" -> (arg => port = Value.Int.parse(arg)), "s" -> (_ => existing_server = true), "x" -> (_ => operation_exit = true)) val more_args = getopts(args) if (more_args.nonEmpty) getopts.usage() if (operation_list) { for { server_info <- using(SQLite.open_database(Data.database))(list) if server_info.active } Output.writeln(server_info.toString, stdout = true) } else if (operation_exit) { val ok = Server.exit(name) sys.exit(if (ok) 0 else 2) } else { val log = Logger.make(log_file) val (server_info, server) = init(name, port = port, existing_server = existing_server, log = log) Output.writeln(server_info.toString, stdout = true) if (console) { using(server_info.connection())(connection => connection.tty_loop().join) } server.foreach(_.join) } }) } -class Server private(_port: Int, val log: Logger) +class Server private(port0: Int, val log: Logger) extends Server.Handler(port0) { server => - private val server_socket = new ServerSocket(_port, 50, Server.localhost) - private val _sessions = Synchronized(Map.empty[UUID.T, Headless.Session]) def err_session(id: UUID.T): Nothing = error("No session " + Library.single_quote(id.toString)) def the_session(id: UUID.T): Headless.Session = _sessions.value.getOrElse(id, err_session(id)) def add_session(entry: (UUID.T, Headless.Session)) { _sessions.change(_ + entry) } def remove_session(id: UUID.T): Headless.Session = { _sessions.change_result(sessions => sessions.get(id) match { case Some(session) => (session, sessions - id) case None => err_session(id) }) } def shutdown() { - server_socket.close + server.socket.close val sessions = _sessions.change_result(sessions => (sessions, Map.empty)) for ((_, session) <- sessions) { try { val result = session.stop() if (!result.ok) log("Session shutdown failed: " + result.print_rc) } catch { case ERROR(msg) => log("Session shutdown failed: " + msg) } } } - def port: Int = server_socket.getLocalPort - val password: String = UUID.random_string() + override def join { super.join; shutdown() } - override def toString: String = Server.print(port, password) - - private def handle(connection: Server.Connection) + override def handle(connection: Server.Connection) { using(new Server.Context(server, connection))(context => { - if (connection.read_password(password)) { - connection.reply_ok( - JSON.Object( - "isabelle_id" -> Isabelle_System.isabelle_id(), - "isabelle_version" -> Distribution.version)) + connection.reply_ok( + JSON.Object( + "isabelle_id" -> Isabelle_System.isabelle_id(), + "isabelle_version" -> Distribution.version)) - var finished = false - while (!finished) { - connection.read_message() match { - case None => finished = true - case Some("") => context.notify("Command 'help' provides list of commands") - case Some(msg) => - val (name, argument) = Server.Argument.split(msg) - Server.command_table.get(name) match { - case Some(cmd) => - argument match { - case Server.Argument(arg) => - if (cmd.command_body.isDefinedAt((context, arg))) { - Exn.capture { cmd.command_body((context, arg)) } match { - case Exn.Res(task: Server.Task) => - connection.reply_ok(JSON.Object(task.ident)) - task.start - case Exn.Res(res) => connection.reply_ok(res) - case Exn.Exn(exn) => - val err = Server.json_error(exn) - if (err.isEmpty) throw exn else connection.reply_error(err) - } + var finished = false + while (!finished) { + connection.read_message() match { + case None => finished = true + case Some("") => context.notify("Command 'help' provides list of commands") + case Some(msg) => + val (name, argument) = Server.Argument.split(msg) + Server.command_table.get(name) match { + case Some(cmd) => + argument match { + case Server.Argument(arg) => + if (cmd.command_body.isDefinedAt((context, arg))) { + Exn.capture { cmd.command_body((context, arg)) } match { + case Exn.Res(task: Server.Task) => + connection.reply_ok(JSON.Object(task.ident)) + task.start + case Exn.Res(res) => connection.reply_ok(res) + case Exn.Exn(exn) => + val err = Server.json_error(exn) + if (err.isEmpty) throw exn else connection.reply_error(err) } - else { - connection.reply_error_message( - "Bad argument for command " + Library.single_quote(name), - "argument" -> argument) - } - case _ => + } + else { connection.reply_error_message( - "Malformed argument for command " + Library.single_quote(name), + "Bad argument for command " + Library.single_quote(name), "argument" -> argument) - } - case None => connection.reply_error("Bad command " + Library.single_quote(name)) - } - } + } + case _ => + connection.reply_error_message( + "Malformed argument for command " + Library.single_quote(name), + "argument" -> argument) + } + case None => connection.reply_error("Bad command " + Library.single_quote(name)) + } } } }) } - - private lazy val server_thread: Thread = - Isabelle_Thread.fork(name = "server") { - var finished = false - while (!finished) { - Exn.capture(server_socket.accept) match { - case Exn.Res(socket) => - Isabelle_Thread.fork(name = "server_connection") - { using(Server.Connection(socket))(handle) } - case Exn.Exn(_) => finished = true - } - } - } - - def start { server_thread } - - def join { server_thread.join; shutdown() } } diff --git a/src/Tools/jEdit/lib/Tools/jedit_client b/src/Tools/jEdit/lib/Tools/jedit_client --- a/src/Tools/jEdit/lib/Tools/jedit_client +++ b/src/Tools/jEdit/lib/Tools/jedit_client @@ -1,108 +1,108 @@ #!/usr/bin/env bash # # Author: Makarius # # DESCRIPTION: Isabelle/jEdit client for already running application ## settings SERVER_NAME="${ISABELLE_IDENTIFIER:-Isabelle}" eval "declare -a JAVA_ARGS=($JEDIT_JAVA_SYSTEM_OPTIONS $JEDIT_JAVA_OPTIONS)" ## diagnostics PRG="$(basename "$0")" function usage() { echo echo "Usage: isabelle $PRG [OPTIONS] [FILES ...]" echo echo " Options are:" echo " -c only check presence of server" echo " -n only report server name" - echo " -s NAME server name (default $SERVER_NAME)" + echo " -s NAME server name (default \"$SERVER_NAME\")" echo echo " Connect to already running Isabelle/jEdit instance and open FILES" echo exit 1 } function fail() { echo "$1" >&2 exit 2 } function failed() { fail "Failed!" } ## process command line # options CHECK_ONLY="false" NAME_ONLY="false" while getopts "cns:" OPT do case "$OPT" in c) CHECK_ONLY="true" ;; n) NAME_ONLY="true" ;; s) SERVER_NAME="$OPTARG" ;; \?) usage ;; esac done shift $(($OPTIND - 1)) # args declare -a ARGS=() while [ "$#" -gt 0 ] do ARGS["${#ARGS[@]}"]="$(platform_path "$1")" shift done ## main if [ "$CHECK_ONLY" = true ] then [ -f "$JEDIT_SETTINGS/$SERVER_NAME" ] exit $? fi if [ "$NAME_ONLY" = true ] then echo "$SERVER_NAME" exit fi isabelle jedit -b || exit $? if [ -f "$JEDIT_SETTINGS/$SERVER_NAME" ] then exec isabelle java "${JAVA_ARGS[@]}" \ -jar $(platform_path "$JEDIT_HOME/dist/jedit.jar") \ "-settings=$(platform_path "$JEDIT_SETTINGS")" \ -server="$SERVER_NAME" -reuseview "${ARGS[@]}" else fail "Isabelle/jEdit server \"$SERVER_NAME\" not active" fi