├── CODE_OF_CONDUCT.md ├── LICENSE ├── Makefile ├── README.md ├── RELEASE_NOTES.md ├── interp.d ├── md2sexpr.d ├── parser.d ├── query.d └── tree-query.d /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # GNU Kind Communications Guidelines 2 | 3 | by Richard Stallman 4 | ## Purpose 5 | 6 | The GNU Project encourages contributions from anyone who wishes to advance the development of the GNU system, regardless of gender, race, ethnic group, physical appearance, religion, cultural background, and any other demographic characteristics, as well as personal political views. 7 | 8 | People are sometimes discouraged from participating in GNU development because of certain patterns of communication that strike them as unfriendly, unwelcoming, rejecting, or harsh. This discouragement particularly affects members of disprivileged demographics, but it is not limited to them. Therefore, we ask all contributors to make a conscious effort, in GNU Project discussions, to communicate in ways that avoid that outcome—to avoid practices that will predictably and unnecessarily risk putting some contributors off. 9 | 10 | These guidelines suggest specific ways to accomplish that goal. 11 | 12 | ## Guidelines 13 | 14 | - Please assume other participants are posting in good faith, even if you disagree with what they say. When people present code or text as their own work, please accept it as their work. Please do not criticize people for wrongs that you only speculate they may have done; stick to what they actually say and actually do. 15 | - Please think about how to treat other participants with respect, especially when you disagree with them. For instance, call them by the names they use, and honor their preferences about their gender identity[1]. 16 | - Please do not take a harsh tone towards other participants, and especially don't make personal attacks against them. Go out of your way to show that you are criticizing a statement, not a person. 17 | - Please recognize that criticism of your statements is not a personal attack on you. If you feel that someone has attacked you, or offended your personal dignity, please don't “hit back” with another personal attack. That tends to start a vicious circle of escalating verbal aggression. A private response, politely stating your feelings as feelings, and asking for peace, may calm things down. Write it, set it aside for hours or a day, revise it to remove the anger, and only then send it. 18 | - Please avoid statements about the presumed typical desires, capabilities or actions of some demographic group. They can offend people in that group, and they are always off-topic in GNU Project discussions. 19 | - Please be especially kind to other contributors when saying they made a mistake. Programming means making lots of mistakes, and we all do so—this is why regression tests are useful. Conscientious programmers make mistakes, and then fix them. It is helpful to show contributors that being imperfect is normal, so we don't hold it against them, and that we appreciate their imperfect contributions though we hope they follow through by fixing any problems in them. 20 | - Likewise, be kind when pointing out to other contributors that they should stop using certain nonfree software. For their own sake, they ought to free themselves, but we welcome their contributions to our software packages even if they don't do that. So these reminders should be gentle and not too frequent—don't nag. 21 | - By contrast, to suggest that others run a nonfree program opposes the basic principles of GNU, so it is not allowed in GNU Project discussions. 22 | - Please respond to what people actually said, not to exaggerations of their views. Your criticism will not be constructive if it is aimed at a target other than their real views. 23 | - If in a discussion someone brings up a tangent to the topic at hand, please keep the discussion on track by focusing on the current topic rather than the tangent. This is not to say that the tangent is bad, or not interesting to discuss—only that it shouldn't interfere with discussion of the issue at hand. In most cases, it is also off-topic, so those interested ought to discuss it somewhere else. 24 | - If you think the tangent is an important and pertinent issue, please bring it up as a separate discussion, with a Subject field to fit, and consider waiting for the end of the current discussion. 25 | - Rather than trying to have the last word, look for the times when there is no need to reply, perhaps because you already made the relevant point clear enough. If you know something about the game of Go, this analogy might clarify that: when the other player's move is not strong enough to require a direct response, it is advantageous to give it none and instead move elsewhere. 26 | - Please don't argue unceasingly for your preferred course of action when a decision for some other course has already been made. That tends to block the activity's progress. 27 | - If others have irritated you, perhaps by disregarding these guidelines, please don't excoriate them, and especially please don't hold a grudge against them. The constructive approach is to encourage and help other people to do better. When they are trying to learn to do better, please give them plenty of chances. 28 | - If other participants complain about the way you express your ideas, please make an effort to cater to them. You can find ways to express the same points while making others more comfortable. You are more likely to persuade others if you don't arouse ire about secondary things. 29 | - Please don't raise unrelated political issues in GNU Project discussions, because they are off-topic. The only political positions that the GNU Project endorses are (1) that users should have control of their own computing (for instance, through free software) and (2) supporting basic human rights in computing. We don't require you as a contributor to agree with these two points, but you do need to accept that our decisions will be based on them. 30 | 31 | By making an effort to follow these guidelines, we will encourage more contribution to our projects, and our discussions will be friendlier and reach conclusions more easily. 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY = md2sexpr-build 2 | 3 | # Compile a debug build for quick development 4 | tree-query: tree-query.d interp.d query.d parser.d 5 | dmd -g -debug -check=invariant -unittest tree-query.d interp.d query.d parser.d 6 | 7 | md2sexpr-build: 8 | ~/dlang/ldc-1.23.0/bin/ldc2 --link-defaultlib-shared=false -O3 -release md2sexpr.d parser.d 9 | 10 | # Compile with LLVM 11 | tree-query-build: 12 | ldc2 --link-defaultlib-shared=false -O2 -release tree-query.d interp.d query.d parser.d 13 | strip tree-query 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `tree-query` 2 | 3 | > This README is TODO. If you'd like to use this software in a project, **don't hestiate to reach out to me.** 4 | 5 | `tree-query` is a tool that lets you execute queries on ordinary directories of files like text and Markdown, inspired by Roam Research's query syntax. 6 | 7 | It is a replacement for Roam's query system. It supports everything Roam does, except for block references. 8 | 9 | [Join us on Discord](https://discord.gg/7B9ywS5x) 10 | 11 | ## Quickstart 12 | 13 | **Query in current directory:** 14 | ``` 15 | tree-query '{and: [[Page 1]] [[Page 2]]}' . 16 | ``` 17 | [*Learn to navigate to a working directory with `cd`*](https://linuxize.com/post/linux-cd-command/) 18 | 19 | **Query in a folder:** 20 | ``` 21 | tree-query '{and: [[Page 1]] [[Page 2]]}' /Users/steve/myfoldername/ 22 | ``` 23 | *Learn to get the location of a folder on [macOS](https://osxdaily.com/2009/11/23/copy-a-files-path-to-the-terminal-by-dragging-and-dropping/), [Windows](https://www.top-password.com/blog/copy-full-path-of-a-folder-file-in-windows/), or [GNU+Linux](https://unix.stackexchange.com/questions/102551/mouse-shortcut-to-copy-the-path-to-a-file-in-the-gnome-file-manager).* 24 | 25 | Or query in multiple folders and files: 26 | 27 | ``` 28 | tree-query '{and: [[Page 1]] [[Page 2]]}' /Users/steve/myfoldername/ file1 29 | ``` 30 | 31 | **Query stdin with pipes:** 32 | ``` 33 | cat myfile | tree-query '{and: [[Page 1]] [[Page 2]]}' 34 | ``` 35 | [*Learn to build powerful no-code applications using pipes*](https://youtu.be/tc4ROCJYbm0?t=360) 36 | 37 | ## Installation 38 | ### [Download a copy](https://github.com/CrazyPython/tree-query/releases/tag/v0.1.1) 39 | The more convenient method. Click above for instructions. 40 | 41 | ### Build from source 42 | 43 | On FreeBSD, GNU+Linux, and macOS, open Terminal and go: 44 | ``` 45 | curl https://dlang.org/install.sh | bash -s 46 | ``` 47 | 48 | On Windows, download and install [Git Bash](https://gitforwindows.org/) and [7-Zip to C:\Program Files](https://www.7-zip.org/), then run: 49 | ``` 50 | mkdir %USERPROFILE%\dlang 51 | set PATH="%PATH%;C:\Program Files\7-Zip" 52 | set BASH="\Program Files\Git\usr\bin\bash.exe" 53 | mkdir dlang 54 | powershell.exe -Command "wget https://dlang.org/install.sh -OutFile dlang\install.sh" 55 | ``` 56 | 57 | Then: 58 | ``` 59 | ~/dlang/install.sh install ldc-1.23.0 60 | ``` 61 | 62 | Then `cd` into the directory where you cloned this directory (`git clone https://github.com/CrazyPython/tree-query.git && cd tree-query`) and type: 63 | ``` 64 | ~/dlang/ldc-1.23.0/bin/ldc2 --link-defaultlib-shared=false -O2 -release tree-query.d interp.d query.d parser.d 65 | ``` 66 | 67 | (Non-Windows) Install to make available eveywhere: 68 | ``` 69 | chmod 700 tree-query 70 | sudo mv tree-query /usr/local/bin 71 | ``` 72 | 73 | ## Features 74 | 75 | This section is a work-in-progress. 76 | 77 | * **Fast** 78 | 79 | ## Basic usage with the command-line 80 | 81 | ### Copy result to clipboard 82 | macOS: 83 | ``` 84 | tree-query '{and: [[Page 1]] [[Page 2]]}' . | pbcopy 85 | ``` 86 | 87 | GNU+Linux: 88 | ``` 89 | tree-query '{and: [[Page 1]] [[Page 2]]}' . | xclip 90 | ``` 91 | 92 | ## Contributing 93 | 94 | **query.d**: The logic for executing Roam queries 95 | 96 | **parser.d**: The Markdown/org-mode parser, which detects the indentation level of each line and uses it to emit a stream of events for a handler like `query.d` to consume. 97 | 98 | **tree-query.d**: The command-line tool/wrapper. Recursively parses the string `{and: [[Page 1]] [[Page 2]]}` into a tree of expressions 99 | 100 | **interp.d**: Recursively evaluates boolean expressions on behalf of query.d 101 | 102 | `tree-query` has doc comments on internals and example code demonstrating how internal APIs work. (Ctrl-F for "unittest") 103 | 104 | Tree-query is written in [Dlang](https://dlang.org) but don't let that put you off- if you know C, C++, or Java, you'll pick it up very quickly. 105 | 106 | If you have any questions on D, feel free to go to #d on freenode or D Forums. People are very nice. 107 | 108 | ### Internals 109 | 110 | I've spent some time writing doc comments inside the code. They provide a conceptual explanation of how the system works. Look for `/**` and `/++`. 111 | 112 | Inside the unittests, there's an example guide on using `parser.d` as a library to build a Markdown to XML converter. 113 | 114 | ### Notes 115 | 116 | A string in D is a reference to a region of immutable memory. It is a length and a pointer. For this reason, it is is very efficient to copy. 117 | 118 | A struct is like a Java record or class. 119 | 120 | ## Known bugs 121 | - Mixing tabs and spaces in the same file is not supported, unless an explicit spaces per indent specified 122 | 123 | ## Your rights 124 | 125 | This is open-source software. 126 | 127 | We use copyleft to gurantee these rights: 128 | 129 | 0. Free for commercial use and any other purpose 130 | 1. Freedom to remix to fit your needs: You (and if you can't code, by proxy a programmer you hire) have freedom to add new query keywords, completely change the query system, add support for new formats like org-mode, or anything else 131 | 2. Freedom to help friends by sharing 132 | 3. Freedom to share remixes, commercially and noncommercially 133 | 134 | I believe knowledge management is a deeply, and everyone should have freedom over their "digital brain." A digital brain is a deeply intimate and personal thing. This means you are the sovereign of your digital brain. 135 | 136 | Compatible with permissive licenses like Apache License, MIT License, and Mozilla Public License. 137 | 138 | (C) 2021. Affero General Public License v3.0 or any later version 139 | -------------------------------------------------------------------------------- /RELEASE_NOTES.md: -------------------------------------------------------------------------------- 1 | # Release notes 2 | 3 | ## 0.1.1 4 | - Added hyperlinked documentation on usage instructions for people new to the CLI 5 | - Added missing source files, now it's possible to compile 6 | - Support for starting queries with `{query:` was enabled 7 | - Shows message when executed without a query 8 | - Fixed build instructions for Windows and added a binary release for Windows and Mac 9 | 10 | ## 0.1.0 11 | - Supports `{and:`, `{or:`, `{not:`, nested arbitrarily, querying using page references 12 | - Works on any kind of indentation, including tabs, spaces. 13 | - Caveat: Mixing tabs and spaces in one file may lead to undesired results, because a tab is interpreted as one space 14 | - Ignores text inside Markdown code blocks 15 | - Indentation is different for these code blocks. Searching with their text included as part of the parent block is not supported yet 16 | -------------------------------------------------------------------------------- /interp.d: -------------------------------------------------------------------------------- 1 | /+ A boolean expression interpreter. 2 | + Used to evaluate boolean bitfields for the query. 3 | +/ 4 | module interp; 5 | 6 | import std.variant; 7 | import std.typecons; 8 | // TCO 9 | alias BitType = uint; 10 | enum Op { AND, OR, NOT, ATOM }; 11 | bool eval_form(BitType bitstring, Form form) { 12 | if (form.op == Op.AND) { 13 | return eval_and(bitstring, form.operands); 14 | } else if (form.op == Op.OR) { 15 | return eval_or(bitstring, form.operands); 16 | } else if (form.op == Op.NOT) { 17 | return cast(bool)(!(bitstring & (1 << form.operands[0].bitshift))); 18 | //return cast(bool)(!(bitstring & (1 << form.bitshift))); 19 | } else { 20 | return cast(bool)(bitstring & (1 << form.bitshift)); 21 | } 22 | } 23 | struct Form { 24 | Op op; 25 | union { 26 | Form[] operands; 27 | // What is faster, a ubyte or a byte? 28 | ubyte bitshift; 29 | } 30 | } 31 | bool eval_and(BitType bitstring, Form[] terms) { 32 | if (terms.length == 0) { 33 | return true; 34 | } 35 | if (eval_form(bitstring, terms[0])) { 36 | return eval_and(bitstring, terms[1..$]); 37 | } else { 38 | // short-circuit evaluation 39 | return false; 40 | } 41 | } 42 | bool eval_or(BitType bitstring, Form[] terms) { 43 | if (terms.length == 0) { 44 | return false; 45 | } 46 | if (eval_form(bitstring, terms[0])) { 47 | // short-circuit evaluation 48 | return true; 49 | } else { 50 | return eval_or(bitstring, terms[1..$]); 51 | } 52 | } 53 | private Form Atom(ubyte bitshift) { 54 | Form form = { Op.ATOM, bitshift: bitshift }; 55 | return form; 56 | } 57 | unittest { 58 | assert(eval_form(0b1, Form(Op.OR, [Atom(0)])) == true); 59 | assert(eval_form(0b11, Form(Op.AND, [Atom(0), Atom(1)])) == true); 60 | assert(eval_form(0b10, Form(Op.AND, [Atom(0), Atom(1)])) == false); 61 | assert(eval_form(0b10, Form(Op.OR , [Atom(0), Atom(1)])) == true); 62 | assert(eval_form(0b111,Form(Op.AND, [Form(Op.AND, [Atom(0), Atom(2)]), Atom(1)])) == true); 63 | } 64 | -------------------------------------------------------------------------------- /md2sexpr.d: -------------------------------------------------------------------------------- 1 | import parser; 2 | import std.string; 3 | private string escape(string text) { 4 | return `"` ~ text.replace(`\`, `\\`).replace(`"`, `\"`) ~ `"`; 5 | } 6 | struct ConvertToSExprEventHandler { 7 | string start(string text) { 8 | return " (" ~ escape(text); 9 | } 10 | string end() { 11 | return ")"; 12 | } 13 | } 14 | struct ConvertToSExprListEventHandler { 15 | int[] nchildren; 16 | string start(string text) { 17 | int current; 18 | if (nchildren.length) { 19 | nchildren[$-1]++; 20 | current = nchildren[$-1]; 21 | } else { 22 | current = 0; 23 | } 24 | nchildren ~= 0; 25 | // If we are starting a list with more than one child, add 2 parens 26 | if (current == 1) { 27 | return " ((" ~ escape(text); 28 | } else { 29 | return " (" ~ escape(text); 30 | } 31 | } 32 | string end() { 33 | // If we are ending a list with more than one child, add 2 parens 34 | if (nchildren.length > 0 && nchildren[$-1] > 0) { 35 | nchildren.length--; 36 | return "))"; 37 | } else { 38 | nchildren.length--; 39 | return ")"; 40 | } 41 | } 42 | } 43 | void main(string[] args) { 44 | import std.stdio, std.file; 45 | string[] inputnames; 46 | string[] inputs; 47 | args = args[1..$]; // skip first arg, which is name of binary 48 | bool list = false; 49 | if (args.length > 0 && args[0] == "-l") { 50 | args = args[1..$]; 51 | list = true; 52 | } 53 | if (args.length == 0) { 54 | // stdin 55 | string input; 56 | string line; 57 | while ((line = readln()) !is null) 58 | input ~= line; 59 | inputnames ~= "stdin"; 60 | inputs ~= input; 61 | } 62 | void readRestArgs() { 63 | foreach (filename; args) { 64 | inputnames ~= filename; 65 | inputs ~= filename.readText; 66 | } 67 | } 68 | if (list) { 69 | readRestArgs(); 70 | for (int i = 0; i < inputs.length; ++i) { 71 | string output; 72 | parse!(ConvertToSExprListEventHandler, s => output ~= s, s => output ~=s)(inputs[i], 4, inputnames[i]); 73 | // Write each on a separate lines 74 | writeln(output); 75 | } 76 | } else { 77 | readRestArgs(); 78 | for (int i = 0; i < inputs.length; ++i) { 79 | string output; 80 | parse!(ConvertToSExprEventHandler, s => output ~= s, s => output ~=s)(inputs[i], 4, inputnames[i]); 81 | // Write each on separate lines 82 | writeln(output); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /parser.d: -------------------------------------------------------------------------------- 1 | /** Count the indent level and return where the indent level stops in "i" 2 | * A tab is counted as one indent. 3 | * Params: 4 | * i = the index to start looking from. This is mutated 5 | * by reference to indicate the index the last index 6 | * was. 7 | * spaces_per_indent = the number of spaces to treat as one indent 8 | */ 9 | int count_indents(ref int i, string input, int spaces_per_indent=4) { 10 | int nspaces = 0; 11 | if (i == input.length || !(input[i] == ' ' || input[i] == '\t')) { 12 | return 0; 13 | } 14 | for (; i < input.length; ++i) { 15 | switch (input[i]) { 16 | case ' ': nspaces++; break; 17 | case '*': nspaces++; break; 18 | case '\t': nspaces += spaces_per_indent; break; 19 | // Commented out makes it only accept "-" 20 | //case '-': return nspaces / spaces_per_indent; 21 | case '\n': nspaces = 0; break; 22 | //default : return 0; 23 | default : return nspaces / spaces_per_indent; 24 | } 25 | } 26 | return nspaces / spaces_per_indent; 27 | } 28 | unittest { 29 | int i; 30 | assert(count_indents(i = 0, " - hi") == 1); 31 | assert(count_indents(i = 0, "Foo") == 0); 32 | assert(count_indents(i = 0, " - hi") == 2); 33 | assert(count_indents(i = 0, "\t - hey") == 1); 34 | } 35 | void doNothing(T)(T _=null) {} 36 | /** A streaming parser for Markdown trees. Emits a stream of parsing events. 37 | * Params: 38 | * ParseEventHandler = struct that handles a stream of parsing events. 39 | * See [ExampleParseEventHandler] for an example. 40 | * deleStart = function that is called with the return value of 41 | * the ParseEventHandler's start(). Defaults to 42 | * doNothing 43 | * deleEnd = function that is called with the return value of 44 | * the ParseEventHandler's end(). Defaults to 45 | * doNothing 46 | * These are all compile-time (template) parameters, thus the compiler will 47 | * inline functions into generated code. 48 | */ 49 | void parse(ParseEventHandler, 50 | alias deleStart=doNothing, 51 | alias deleEnd=doNothing, 52 | bool relaxed=false, 53 | Args...) 54 | (string input, int spaces_per_indent, string title, Args args) { 55 | import std.traits; 56 | ParseEventHandler handler = ParseEventHandler(args); 57 | //const initial_indent_level = 58 | int current_indent_level; 59 | //BitType current_bits; 60 | //BitType[] stack; 61 | int line_content_start_index; 62 | int line_start_index; 63 | // Workwround for void not being a parameter type 64 | void emitBlockStart(string nodeContent) { 65 | static if (is(ReturnType!(handler.start) == void)) { 66 | handler.start(nodeContent); 67 | deleStart(); 68 | } else deleStart(handler.start(nodeContent)); 69 | } 70 | void emitBlockEnd() { 71 | static if (is(ReturnType!(handler.end) == void)) { 72 | handler.end(); 73 | deleEnd(); 74 | } else deleEnd(handler.end()); 75 | } 76 | emitBlockStart(title); 77 | for (int i = 0; i < input.length; ++i) { 78 | // emit end when on same or lower indent level, number based on difference 79 | // start on new lines 80 | switch (input[i]) { 81 | case '\n': 82 | //stack[0] & current_bits; 83 | // FIXME: Start and end based on "-" 84 | const nodeContent = input[line_start_index..i]; 85 | import std.stdio; 86 | emitBlockStart(nodeContent); 87 | i++; 88 | line_start_index = i; 89 | int new_indent_level = 90 | count_indents(i, input, spaces_per_indent); 91 | line_content_start_index = i; 92 | const extraEndings = i == input.length ? 0 : 1; 93 | foreach (_; 94 | 0..current_indent_level - new_indent_level + extraEndings) { 95 | emitBlockEnd(); 96 | } 97 | if (relaxed && new_indent_level > current_indent_level + 1) { 98 | foreach (_; 0..new_indent_level - current_indent_level - 1) 99 | { 100 | emitBlockStart(""); 101 | } 102 | } 103 | current_indent_level = new_indent_level; 104 | break; 105 | case '[': 106 | break; 107 | // Skip across multiline constructs to prevent 108 | // detect_indent 109 | case '`': 110 | if (input[i+1] == '`' && input[i+2] == '`') { 111 | // Skip 3 at a time for efficiency 112 | // TODO: SIMD this and/or PGO it 113 | for (i += 3; i < input.length; ++i) { 114 | if (input[i-2] == '`' && 115 | input[i-1] == '`' && 116 | input[i-0] == '`') { 117 | break; 118 | } 119 | } 120 | } 121 | break; 122 | default: break; 123 | } 124 | } 125 | if (line_content_start_index != input.length) { 126 | emitBlockStart(input[line_start_index .. input.length]); 127 | } 128 | for (int i = 0; i < current_indent_level + 1; ++i) { 129 | emitBlockEnd(); 130 | } 131 | // End again because we started for the title 132 | emitBlockEnd(); 133 | } 134 | /// Test the stream of parser events 135 | unittest { 136 | import std.range, std.array; 137 | struct ExampleParseEventHandler { 138 | string start(string text) { 139 | return "START" ~ text; 140 | } 141 | string end() { 142 | return "END"; 143 | } 144 | } 145 | string sample = "- ab\n\t- b\nhello\n\tworld\n\tfoo"; 146 | // A trailing newline should not affect ther esult 147 | foreach (useTrailingNewline; [false, true]) { 148 | string result; 149 | parse!(ExampleParseEventHandler, s => result ~= s, s => result ~= s) 150 | (sample ~ (useTrailingNewline ? "\n" : ""), 4, "Title"); 151 | import std.stdio; 152 | debug writeln(result); 153 | assert(result == 154 | "STARTTitleSTART- abSTART\t- bENDENDSTARThelloSTART\tworldENDSTART\tfooENDENDEND" 155 | ); 156 | } 157 | } 158 | struct A { 159 | 160 | } 161 | private struct WithConstructor { 162 | string[] member; 163 | this(string[] arg, A a) { 164 | member = arg; 165 | } 166 | void start(string text) { 167 | } 168 | void end() { 169 | } 170 | } 171 | unittest { 172 | A a; 173 | parse!(WithConstructor) 174 | ("Test", 4, "Title", ["arg"], a); 175 | } 176 | unittest { 177 | import std.stdio; 178 | struct ExampleParseEventHandler { 179 | string start(string text) { 180 | return "
" ~ text; 181 | } 182 | string end() { 183 | return "
"; 184 | } 185 | } 186 | string sample = 187 | `a 188 | b 189 | c 190 | d`; 191 | string result; 192 | parse!(ExampleParseEventHandler, s => result ~= s, s => result ~= s, true) 193 | (sample, 1, "Title"); 194 | writeln(result); 195 | assert(result == "
Title
a
b
c
d
"); 196 | } 197 | struct ConvertToXMLEventHandler { 198 | string start(string text) { 199 | return "" ~ text; 200 | } 201 | string end() { 202 | return ""; 203 | } 204 | } 205 | /*struct ConvertToOPMLEventHandler { 206 | string start(string text) { 207 | // todo: escpae 208 | return ``; 212 | } 213 | }*/ 214 | -------------------------------------------------------------------------------- /query.d: -------------------------------------------------------------------------------- 1 | /++ Query system that implements Roam queries. +/ 2 | module query; 3 | import interp; 4 | debug import std.stdio; 5 | 6 | // Unoptimized function to calculate matches for a set of 7 | // words 8 | // This should be replaced by something faster. 9 | // For instance, a regex library, that scans once, instead of once 10 | struct DumbMatcher(BitType) { 11 | string[] search_terms; 12 | this(string[] terms) { 13 | search_terms = terms; 14 | } 15 | BitType match(string str) { 16 | import std.algorithm.searching : canFind; 17 | BitType result; 18 | debug writeln("Query " ~ str); 19 | for (int i = 0; i < search_terms.length; ++i) { 20 | auto term = search_terms[i]; 21 | if (canFind(str, term)) { 22 | debug writeln("Matched with " ~ term); 23 | result |= 1 << i; 24 | } 25 | } 26 | return result; 27 | } 28 | unittest { 29 | DumbMatcher!BitType matcher = DumbMatcher(["red", "green"]); 30 | assert(matcher.match("blue") == 0b00); 31 | assert(matcher.match("red") == 0b01); 32 | assert(matcher.match("green") == 0b10); 33 | assert(matcher.match("red green") == 0b11); 34 | assert(matcher.match("blue green") == 0b10); 35 | Form form = { Op.ATOM, bitshift: 0}; 36 | assert(eval_form(matcher.match("red"), Form(Op.AND, [form]))); 37 | } 38 | unittest { 39 | DumbMatcher!BitType matcher = DumbMatcher(["[[PRIME Theory]]", "[[PRIME: Motives]]"]); 40 | assert(matcher.match("- In every moment we [act]([[PRIME: Responses]]) in pursuit of what we most [want or need]([[PRIME: Motives]]) at that moment. Something can only exert [[behavioral influence]] if it is [[salient]] at the moment") == 0b10); 41 | } 42 | } 43 | struct RegexMatcher; 44 | struct TrieMatcher; 45 | 46 | alias BitType = uint; 47 | 48 | /++Roam query. 49 | + It handles a stream of START and END events. 50 | + START means a indented block or line started 51 | + END means a indented block or line ended 52 | + 53 | + It computes a bitfield for each line. 54 | + Each bit in the bitfield corresponds to a word in the query, and represents 55 | + whether that bit was present in this line or one of its parents. 56 | +/ 57 | struct QueryHandler { 58 | bool matching = false; 59 | string[] parent_lines; // Bookkeeping data structure. Holds parent lines as strings, so we can later print them out. 60 | //string[] to_print; 61 | BitType[] bit_stack = [0]; 62 | DumbMatcher!BitType matcher; 63 | Form expression; 64 | this(string[] terms, Form form) { // Construct a QueryHandler struct 65 | debug writeln("Terms", terms); 66 | assert(terms.length < BitType.sizeof * 8); 67 | matcher = DumbMatcher!BitType(terms); 68 | expression = form; 69 | } 70 | void start(string line) { 71 | BitType own_bits = matcher.match(line); 72 | bit_stack ~= bit_stack[$-1] | own_bits; 73 | debug writeln("Own bitstring", own_bits); 74 | parent_lines ~= line; 75 | if (eval_form(bit_stack[$-1], expression)) { 76 | import std.stdio; 77 | foreach (parent_line; parent_lines) 78 | writeln(parent_line); 79 | // Simple way to avoid printing it twice 80 | parent_lines.length = 0; 81 | } 82 | } 83 | void end() { 84 | debug writeln("stacklen", bit_stack.length); 85 | bit_stack.length--; 86 | if (parent_lines.length > 0) 87 | parent_lines = parent_lines[0..$-1]; // Pop the last item 88 | } 89 | } 90 | unittest { 91 | //QueryHandler!uint handler = QueryHandler!uint(["red", "green"], ""); 92 | } 93 | -------------------------------------------------------------------------------- /tree-query.d: -------------------------------------------------------------------------------- 1 | module tree_query; 2 | import std.stdio; 3 | import std.variant; 4 | import std.string; 5 | import query; 6 | import interp; 7 | /++ 8 | + Extract the query from the input. 9 | + These forms are supported, where QUERY represents the query itself. 10 | + - QUERY 11 | + - {{query: QUERY }} 12 | + - {{query:QUERY}} 13 | + - {{[[query]]: QUERY }} 14 | + 15 | + Leading and trailing whitespace are allowed before the start and end of the query. 16 | + 17 | + Note that Roam does not accept {{ query: nor {{ query : 18 | + 19 | +/ 20 | string extractQuery(string query) { 21 | import std.string; 22 | query = strip(query); // Allow leading and trailing whitespace 23 | if (query.startsWith("{{")) { 24 | if (query.endsWith("}}")) { 25 | // "1"th index is 2 26 | auto withoutWhitespace = stripLeft(query[2..$]); 27 | enum command = "query:"; 28 | if (withoutWhitespace.startsWith(command)) { 29 | auto result = query[2+command.length..$-2].strip; 30 | return result; 31 | } else { 32 | throw new Error("Unrecognized command, command must be 'query:'"); 33 | } 34 | } else { 35 | throw new Exception("Malformed query. Must end with '}}'"); 36 | } 37 | } else { 38 | return query; 39 | } 40 | } 41 | unittest { 42 | const nakedQueries = [ 43 | "{and: [[foo]] [[bar]] }", 44 | "{or: [[foo]] [[bar]] }", 45 | "{and: [[foo]] [[bar]]}", 46 | "{and: [[foo]] {and: [[bar]] [[spam]]}}" 47 | ]; 48 | foreach (nakedQuery; nakedQueries) { 49 | assert(extractQuery(nakedQuery) == nakedQuery); 50 | assert(extractQuery("{{query:" ~ nakedQuery ~ "}}") == nakedQuery); 51 | assert(extractQuery(" {{query: " ~ nakedQuery ~ " }} ") == nakedQuery); 52 | } 53 | } 54 | struct ParsedQuery { 55 | string[] terms; 56 | Form form; 57 | } 58 | 59 | ParsedQuery parseQuery(string query) { 60 | ParsedQuery q; 61 | return q; 62 | } 63 | 64 | // TODO: Implement atom dedup 65 | // TODO: Implement support for arbitrary atoms 66 | // TODO: Allocate Form from an array for efficiency 67 | ParsedQuery booleanQuery(string query, ref ubyte bitshift) { 68 | import std.array; 69 | ParsedQuery q; 70 | debug writeln("subquery", query); 71 | query = query.strip(); 72 | auto start = query.split(" ")[0]; 73 | if (start == "{and:") { 74 | q.form.op = Op.AND; 75 | } else if (start == "{or:") { 76 | q.form.op = Op.OR; 77 | } else if (start == "{not:") { 78 | q.form.op = Op.NOT; 79 | } else { 80 | throw new Exception("Unrecognized keyword" ~ start); 81 | } 82 | // (\[\[.+\]\])|(".+") 83 | // recursive call 84 | // using the rest of the words, build a form 85 | int[] indexes; 86 | int ntoskip = 0; 87 | foreach (i, token; query[start.length..$].split("]]")) { 88 | debug writeln("Parse token", token); 89 | if (ntoskip > 0) { 90 | ntoskip--; 91 | continue; 92 | } 93 | if (token.startsWith("[[") || token.startsWith(" [[")) { 94 | auto text = token.strip() ~ "]]"; 95 | q.terms ~= text; 96 | Form inner = { Op.ATOM, bitshift: bitshift++ }; 97 | debug bitshift.writeln; 98 | q.form.operands ~= inner; 99 | } else if (token.strip().startsWith("}")) { 100 | return q; 101 | } else { 102 | auto subquery = booleanQuery( 103 | query[start.length..$].split("]]")[i..$].join("]]"), 104 | bitshift 105 | ); 106 | q.terms ~= subquery.terms; 107 | q.form.operands ~= subquery.form; 108 | ntoskip = cast(int)subquery.terms.length + 1; 109 | } 110 | } 111 | return q; 112 | } 113 | unittest { 114 | ubyte bitshift = 0; 115 | auto pq = booleanQuery("{and: [[Hi]] {or: [[Blue]] [[White]] } }", bitshift); 116 | assert(pq.terms == ["[[Hi]]", "[[Blue]]", "[[White]]"]); 117 | assert(pq.form.operands[1].op == Op.OR); 118 | assert(pq.form.operands[1].operands[0].bitshift == 1); 119 | assert(pq.form.operands[1].operands[1].bitshift == 2); 120 | } 121 | 122 | string escape(string text) { 123 | return text.replace(`\`, `\\`) 124 | .replace(`"`, `\"`) 125 | .replace(`\\n`, `\n`) 126 | .replace(`\\t`, `\t`); 127 | } 128 | unittest { 129 | import std.stdio; 130 | ubyte n = 0; 131 | auto parsed = booleanQuery("{and: [[Hi]] [[Hello]] }", n); 132 | assert(parsed.terms == ["[[Hi]]", "[[Hello]]"]); 133 | } 134 | private struct WithConstructor { 135 | string[] member; 136 | this(string[] arg, Form a) { 137 | member = arg; 138 | } 139 | void start(string text) { 140 | } 141 | void end() { 142 | } 143 | } 144 | unittest { 145 | import parser; 146 | Form form; 147 | parse!(WithConstructor) 148 | ("Test", 4, "Title", ["arg"], form); 149 | } 150 | 151 | int main(string[] args) { 152 | import std.getopt, std.file, std.stdio; 153 | // Parse arguments 154 | string query; 155 | if (args.length >= 2 && args[1].strip.startsWith("{")) { 156 | query = args[1]; 157 | args = args[2..$]; 158 | } else { 159 | throw new Exception("Query must be first parameter"); 160 | } 161 | // Read query immediately. If the user has written an invalid query, show 162 | // an error before we read in all files. 163 | ubyte n = 0; 164 | ParsedQuery qu = booleanQuery(extractQuery(query), n); 165 | string[] inputs; 166 | string[] inputnames; 167 | if (args.length == 0) { 168 | // stdin 169 | string input; 170 | string line; 171 | while ((line = readln()) !is null) 172 | input ~= line; 173 | inputnames ~= "stdin"; 174 | inputs ~= input; 175 | } 176 | foreach (filename; args) { 177 | if (filename.isDir) { 178 | import std.algorithm.iteration; 179 | filename.dirEntries(SpanMode.depth).filter!isFile.each!((string filename) { 180 | // TODO: Proper mechanism to detect and avoid binary files 181 | import std.utf; 182 | try { 183 | inputnames ~= filename; 184 | // TODO: Stream input from files for cache locality, instead of reading everything in at once 185 | inputs ~= filename.readText; 186 | } catch (UTFException) { 187 | inputnames.length--; 188 | } 189 | }); 190 | } else { 191 | assert(filename.exists); 192 | inputnames ~= filename; 193 | inputs ~= filename.readText; 194 | } 195 | } 196 | for (int i = 0; i < inputs.length; ++i) { 197 | import parser; 198 | import std.meta; 199 | parse!(QueryHandler, doNothing, doNothing, true)(inputs[i], 4, inputnames[i], qu.terms, qu.form); 200 | // Write each on a separate lines 201 | } 202 | return 0; 203 | } 204 | --------------------------------------------------------------------------------