├── .ert-runner
├── .gitignore
├── Cask
├── LICENSE
├── Makefile
├── README.org
├── screenshots
├── dropFirst.png
├── dynamicCallable.png
├── import.png
└── isExecutableFile.png
├── swift-helpful-regex.el
├── swift-helpful.el
├── swift-info
├── LICENSE
├── Makefile
├── README.md
├── dir
├── helper.el
├── images
│ ├── CollectionTypes_intro_2x.png
│ ├── UTF16_2x.png
│ ├── UTF8_2x.png
│ ├── UnicodeScalar_2x.png
│ ├── barcode_QR_2x.png
│ ├── barcode_UPC_2x.png
│ ├── bitshiftSignedAddition_2x.png
│ ├── bitshiftSignedFour_2x.png
│ ├── bitshiftSignedMinusFourValue_2x.png
│ ├── bitshiftSignedMinusFour_2x.png
│ ├── bitshiftSigned_2x.png
│ ├── bitshiftUnsigned_2x.png
│ ├── bitwiseAND_2x.png
│ ├── bitwiseNOT_2x.png
│ ├── bitwiseOR_2x.png
│ ├── bitwiseXOR_2x.png
│ ├── chessBoard_2x.png
│ ├── closureReferenceCycle01_2x.png
│ ├── closureReferenceCycle02_2x.png
│ ├── computedProperties_2x.png
│ ├── coordinateGraphComplex_2x.png
│ ├── coordinateGraphMedium_2x.png
│ ├── coordinateGraphSimple_2x.png
│ ├── initializerDelegation01_2x.png
│ ├── initializerDelegation02_2x.png
│ ├── initializersExample01_2x.png
│ ├── initializersExample02_2x.png
│ ├── initializersExample03_2x.png
│ ├── memory_increment_2x.png
│ ├── memory_share_health_maria_2x.png
│ ├── memory_share_health_oscar_2x.png
│ ├── memory_shopping_2x.png
│ ├── multilineStringWhitespace_2x.png
│ ├── overflowAddition_2x.png
│ ├── overflowSignedSubtraction_2x.png
│ ├── overflowUnsignedSubtraction_2x.png
│ ├── referenceCycle01_2x.png
│ ├── referenceCycle02_2x.png
│ ├── referenceCycle03_2x.png
│ ├── remainderInteger_2x.png
│ ├── setEulerDiagram_2x.png
│ ├── setVennDiagram_2x.png
│ ├── sharedStateClass_2x.png
│ ├── sharedStateStruct_2x.png
│ ├── snakesAndLadders_2x.png
│ ├── stackPoppedOneString_2x.png
│ ├── stackPushPop_2x.png
│ ├── stackPushedFourStrings_2x.png
│ ├── staticPropertiesVUMeter_2x.png
│ ├── stringSubstring_2x.png
│ ├── subscriptMatrix01_2x.png
│ ├── subscriptMatrix02_2x.png
│ ├── twoPhaseInitialization01_2x.png
│ ├── twoPhaseInitialization02_2x.png
│ ├── unownedOptionalReference_2x.png
│ ├── unownedReference01_2x.png
│ ├── unownedReference02_2x.png
│ ├── vectorAddition_2x.png
│ ├── weakReference01_2x.png
│ ├── weakReference02_2x.png
│ └── weakReference03_2x.png
├── screenshots
│ └── info-lookup.png
├── swift-reference.html
├── swift-reference.info
├── swift-reference.org
├── swift-reference.texi
├── swift.html
├── swift.info
├── swift.org
└── swift.texi
├── targets
└── checkdoc.el
└── test
├── swift-helpful-info-loader.el
├── swift-helpful-regex-test.el
├── swift-helpful-test.el
├── test-data
├── contains-definition.txt
├── contains-rg-command.txt
├── contains-rg-results.txt
├── contains-type-signature.txt
├── filter-definition.txt
├── filter-rg-command.txt
├── filter-rg-results.txt
├── filter-type-signature.txt
└── stdlib-mocks
│ ├── ArrayType.swift
│ ├── ExistentialCollection.swift.gyb
│ ├── NSStringAPI.swift
│ └── Sequence.swift
└── test-helper.el
/.ert-runner:
--------------------------------------------------------------------------------
1 | -L . -l test/test-helper.el test/swift-helpful-info-loader.el
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # macOS
2 | .DS_Store
3 |
4 | # Compiled
5 | *.elc
6 |
7 | # Packaging
8 | .cask
9 |
10 | # Backup files
11 | *~
12 |
13 | # Undo-tree save-files
14 | *.~undo-tree
15 |
--------------------------------------------------------------------------------
/Cask:
--------------------------------------------------------------------------------
1 |
2 | (source gnu "http://elpa.gnu.org/packages/")
3 | (source melpa)
4 |
5 | (package-file "swift-helpful.el")
6 |
7 | (development
8 | (depends-on "ert-runner")
9 | (depends-on "f"))
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | EMACS ?= emacs
2 | CASK ?= cask
3 | RM ?= rm -f
4 |
5 | LOADPATH = -L .
6 | EMACSBATCH = $(CASK) exec $(EMACS) -q -batch $(LOADPATH)
7 |
8 | compile:
9 | $(CASK) build
10 |
11 | test:
12 | $(EMACSBATCH) \
13 | -l test/test-helper.el \
14 | -l test/swift-helpful-test.el \
15 | -l test/swift-helpful-regex-test.el \
16 | -l test/swift-helpful-info-loader.el \
17 | -f ert-run-tests-batch-and-exit
18 |
19 | test-ert-runner:
20 | $(CASK) exec ert-runner
21 |
22 | checkdoc:
23 | $(EMACS) -batch -l targets/checkdoc.el
24 |
25 | clean:
26 | $(RM) *.elc
27 |
28 | .PHONY : compile test test-ert-runner checkdoc clean
29 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | * swift-helpful
2 |
3 | [[https://melpa.org/#/swift-helpful][file:https://melpa.org/packages/swift-helpful-badge.svg]]
4 |
5 | ** Overview
6 | Emacs is described as "the extensible, customizable, self-documenting, real-time display editor". Wouldn't you like
7 | the same self-documenting experience when you are writing Swift code in Emacs? ~swift-helpful~ is a package that,
8 | using information from ~swift-mode~, ~lsp-mode~ and ~swift-info~, is able to answer questions about anything you see
9 | in a Swift program.
10 |
11 | While developer tools are typically identifier-centric in the sense that they only show documentation about API,
12 | ~swift-helpful~ also shows official Apple information about keywords, attributes, etc. It's the perfect company when
13 | you are experimenting with a Swift playground in Emacs and it is equally useful for people just learning the
14 | language, or people that wants to revisit recent language additions. Also, ~swift-helpful~ is decoupled from the
15 | Apple ecosystem, so you can use it on other platforms like Windows or GNU/Linux. It's also extremely fast, so you can
16 | perfectly use it on resource-constrained platforms like a Raspberry Pi.
17 |
18 | ** Install and Configuration
19 |
20 | *** MELPA
21 |
22 | You can install ~swift-helpful~ via MELPA by just doing ~M-x package-install RET swift-helpful~.
23 |
24 | *** Quelpa
25 |
26 | You can install ~swift-helpful~ via Quelpa (https://framagit.org/steckerhalter/quelpa):
27 |
28 | #+BEGIN_SRC emacs-lisp
29 | (quelpa '(swift-helpful :repo "danielmartin/swift-helpful"
30 | :fetcher github
31 | :files ("*.el" "swift-info/*.info")))
32 | #+END_SRC
33 |
34 | *** Usage
35 |
36 | Main entry point is the ~swift-helpful~ command, which should be executed with the point placed in some Swift code.
37 |
38 | ** Features
39 |
40 | *** Contextual information about Swift keywords and attributes
41 |
42 | ~swift-helpful~ shows information about any Swift keyword or attribute. Let's say you see ~import~ in a Swift program
43 | and you want to know more about how importing modules in Swift works. Simply place the point on top of "import" and
44 | invoke ~swift-helpful~ with ~M-x swift-helpful~. The tool will show you a brief snippet of documentation about Swift
45 | modules. In many cases, the keyword will be highlighted to focus your attention on where it is mentioned in the
46 | documentation. Pressing the "Read more in manual" button opens the Swift manual section in an Info buffer so that you
47 | can read the definitive discussion about that topic.
48 |
49 | [[file:screenshots/import.png]]
50 |
51 | Information is not only limited to keywords. The Swift programming language is gradually increasing the use of
52 | attributes in the language, so ~swift-helpful~ will also show information about attributes. Let's say you don't know
53 | what ~@dynamicCallable~ means, an attribute introduced in Swift 5. Simply place the point in one occurrence of that
54 | attribute and invoke ~swift-helpful~ to read an explanation, this time coming from the official Swift Reference manual:
55 |
56 | [[file:screenshots/dynamicCallable.png]]
57 |
58 | *** API documentation coming from Language Server Protocol
59 |
60 | ~swift-helpful~ also shows documentation about API in the same way your favorite IDE does. It leverages ~lsp-mode~, if
61 | configured with my specific extension for Swift, ~lsp-sourcekit~ (https://github.com/emacs-lsp/lsp-sourcekit).
62 |
63 | Let's say you want to know more about the ~isExecutable~ method that you see in a source file from the ~SourceKit-LSP~
64 | project. If you invoke ~swift-helpful~ on that symbol, you'll see information coming from Language Server Protocol,
65 | including the method type signature, its header documentation, and two convenient buttons to search for its definition
66 | or references across the codebase.
67 |
68 | [[file:screenshots/isExecutableFile.png]]
69 |
70 | *** Swift standard library source code
71 |
72 | If you have a compiled checkout of the Swift standard library, ~swift-helpful~ is able to search it and present you with
73 | implementation source code with almost zero configuration.
74 |
75 | There's only two requirements to use this feature:
76 |
77 | - You need to install the ripgrep tool (https://github.com/BurntSushi/ripgrep), a fast directory searcher.
78 | - You need to point ~swift-helpful~ to your local checkout of the Swift standard library:
79 |
80 | #+BEGIN_SRC emacs-lisp
81 | (setq swift-helpful-stdlib-path "")
82 | #+END_SRC
83 |
84 | Let's say you want to know more about the ~dropFirst~ collection function in Swift. If you ask ~swift-helpful~ about
85 | that, you will be presented with the function implementation from ~Collection.swift~. All file paths are actual links,
86 | so clicking on them opens the standard library source file, in case you want to explore further.
87 |
88 | [[file:screenshots/dropFirst.png]]
89 | ** Development
90 |
91 | Development is automated by means of Make (https://www.gnu.org/software/make/) and Cask (https://cask.readthedocs.io), so installing those programs is encouraged before developing ~swift-helpful~.
92 |
93 | *** Installing Dependencies
94 |
95 | #+BEGIN_SRC sh
96 | cask install
97 | #+END_SRC
98 |
99 | *** Byte-compilation
100 |
101 | #+BEGIN_SRC sh
102 | make compile
103 | #+END_SRC
104 |
105 | *** Testing
106 |
107 | To minimize the chance of regressions, you can run ~swift-helpful~ regression test suite after introducing a change:
108 |
109 | #+BEGIN_SRC sh
110 | make test
111 | #+END_SRC
112 |
113 | If you want to use ert-runner:
114 |
115 | #+BEGIN_SRC sh
116 | make test-ert-runner
117 | #+END_SRC
118 |
119 | *** Lint Function Documentation
120 |
121 | Any good Emacs package should follow some basic style rules regarding its function documentation. To check that:
122 |
123 | #+BEGIN_SRC sh
124 | make checkdoc
125 | #+END_SRC
126 |
127 | See ~README.md~ inside the ~swift-info~ folder to know how to update the documentation after you have modified the documentation source code in Org.
128 |
129 | ** Acknowledgements
130 |
131 | The idea for this package was inspired by helpful.el (https://github.com/Wilfred/helpful).
132 |
--------------------------------------------------------------------------------
/screenshots/dropFirst.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/screenshots/dropFirst.png
--------------------------------------------------------------------------------
/screenshots/dynamicCallable.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/screenshots/dynamicCallable.png
--------------------------------------------------------------------------------
/screenshots/import.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/screenshots/import.png
--------------------------------------------------------------------------------
/screenshots/isExecutableFile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/screenshots/isExecutableFile.png
--------------------------------------------------------------------------------
/swift-helpful-regex.el:
--------------------------------------------------------------------------------
1 | ;;; swift-helpful-regex.el --- A minor mode to show information about Swift things at point. -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; This program is free software; you can redistribute it and/or modify
6 | ;; it under the terms of the GNU General Public License as published by
7 | ;; the Free Software Foundation, either version 3 of the License, or
8 | ;; (at your option) any later version.
9 |
10 | ;; This program is distributed in the hope that it will be useful,
11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;; GNU General Public License for more details.
14 |
15 | ;; You should have received a copy of the GNU General Public License
16 | ;; along with this program. If not, see .
17 |
18 | ;;; Commentary:
19 |
20 | ;;; Part of swift-helpful that contains regular expression logic.
21 |
22 | ;;; Code:
23 | (require 's)
24 | (require 'dash)
25 |
26 | (defvar swift-helpful--where-clause-match nil
27 | "Regular expression match of a `where' clause in a Swift generic declaration.")
28 |
29 | (defun swift-helpful--generic-replacement (where-str)
30 | "Convert `where' generic syntax in WHERE-STR to a format more appropriate for searching."
31 | (s-join ", "
32 | (-remove-first
33 | (lambda (str)
34 | (when
35 | (string-match "\\(where \\)?\\([A-Z] : [a-z]+\\)"
36 | (s-trim str))
37 | (setq swift-helpful--where-clause-match (match-string 2 str))))
38 | (-map
39 | 's-trim
40 | (split-string where-str ",")))))
41 |
42 | (defun swift-helpful--adapt-for-generics (signature)
43 | "Replace a generic Swift SIGNATURE so that \"where T : StringProtocol\" becomes ."
44 | (setq swift-helpful--where-clause-match "")
45 | (let ((str (replace-regexp-in-string
46 | "\\(where .*\\)"
47 | (lambda (match)
48 | (save-match-data
49 | (swift-helpful--generic-replacement match)))
50 | signature)))
51 | (if (not (string= "" swift-helpful--where-clause-match))
52 | (s-trim
53 | (replace-regexp-in-string
54 | "<\\([^>]*\\)>"
55 | swift-helpful--where-clause-match
56 | str
57 | t
58 | nil
59 | 1))
60 | (s-trim str))))
61 |
62 | (defun swift-helpful--prepend-public-keywords (signature)
63 | "Prepend Swift keywords like `public', `func', `var' in SIGNATURE."
64 | (let ((case-fold-search nil))
65 | (replace-regexp-in-string
66 | (format "%s%s\\)"
67 | "\\(__.+\\|mutating \\)?\\("
68 | (regexp-opt
69 | '("func" "let" "var" "class" "struct" "protocol" "extension")))
70 | "public \\1\\2"
71 | signature)))
72 |
73 | (defun swift-helpful--prepare-regex-for-sequence-api (signature)
74 | "Replace \"Element\" with the actual type element in SIGNATURE."
75 | (if (string-match
76 | "\\[\\([a-z]\\{2,\\}\\)\\]"
77 | signature)
78 | (let ((type (match-string 1 signature)))
79 | (replace-regexp-in-string
80 | type
81 | "Element"
82 | signature))
83 | signature))
84 |
85 | (defun swift-helpful--remove-non-interesting-syntax (signature)
86 | "Remove SIGNATURE parts that are not specially useful when grepping the standard library code."
87 | (s-trim (replace-regexp-in-string
88 | "Self."
89 | ""
90 | (replace-regexp-in-string
91 | "{ \\(get\\)?\\(set\\)? }"
92 | ""
93 | (replace-regexp-in-string
94 | "KeyedEncodingContainer."
95 | ""
96 | (replace-regexp-in-string
97 | "KeyedDecodingContainer."
98 | ""
99 | signature))))))
100 |
101 | (defun swift-helpful--prepare-type-signature-for-grep (signature)
102 | "Perform a series of transformations on SIGNATURE for grepping the standard library code."
103 | (swift-helpful--adapt-for-generics
104 | (swift-helpful--prepend-public-keywords
105 | (swift-helpful--prepare-regex-for-sequence-api
106 | (swift-helpful--remove-non-interesting-syntax
107 | signature)))))
108 |
109 | (defun swift-helpful--regex-new-lines-escape-chars (str escape-chars)
110 | "Build a regex sequence flexibly matching STR and escaping some ESCAPE-CHARS.
111 | Insert a regex between each char that matches a few
112 | non-interesting Swift attributes and new line/whitespace
113 | characters (we need to do this because the signature prototype
114 | may be formatted in multiple lines in the standard library
115 | code)."
116 | (mapconcat (lambda (str)
117 | (if (member str escape-chars)
118 | (format "\\%s" str)
119 | str))
120 | (mapcar #'char-to-string str)
121 | "[\\n \\(__owned\\|@inline(__always)\\|@discardableResult\\|__consuming\\)]*"))
122 |
123 | (provide 'swift-helpful-regex)
124 |
125 | ;;; swift-helpful-regex.el ends here
126 |
--------------------------------------------------------------------------------
/swift-helpful.el:
--------------------------------------------------------------------------------
1 | ;;; swift-helpful.el --- Show documentation for Swift programs. -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; Author: Daniel Martín
6 | ;; URL: https://github.com/danielmartin/swift-helpful
7 | ;; Keywords: help, swift
8 | ;; Version: 0.3
9 | ;; Package-Requires: ((emacs "25.1") (dash "2.12.0") (lsp-mode "6.0") (swift-mode "8.0.0"))
10 |
11 | ;; This program is free software; you can redistribute it and/or modify
12 | ;; it under the terms of the GNU General Public License as published by
13 | ;; the Free Software Foundation, either version 3 of the License, or
14 | ;; (at your option) any later version.
15 |
16 | ;; This program is distributed in the hope that it will be useful,
17 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | ;; GNU General Public License for more details.
20 |
21 | ;; You should have received a copy of the GNU General Public License
22 | ;; along with this program. If not, see .
23 |
24 | ;;; Commentary:
25 |
26 | ;; This extension adds a command, `swift-helpful', which, when
27 | ;; executed, shows documentation about a Swift token under
28 | ;; point. Sources of documentation include:
29 | ;;
30 | ;; - Swift official manual and reference manual (installed by this
31 | ;; extension in GNU Info format).
32 | ;;
33 | ;; - Language Server Protocol (LSP), if configured for the project.
34 | ;;
35 | ;; - Swift standard library source code (if available locally and
36 | ;; its path is correctly configured).
37 |
38 | ;;; Code:
39 |
40 | (require 'dash)
41 | (require 'info-look)
42 | (require 'lsp-mode)
43 | (require 'swift-mode)
44 | (require 'swift-helpful-regex)
45 |
46 | (defgroup swift-helpful nil
47 | "Show contextual information about Swift code."
48 | :link '(url-link "https://github.com/danielmartin/swift-helpful")
49 | :group 'swift)
50 |
51 | (defcustom swift-helpful-switch-buffer-function
52 | #'pop-to-buffer
53 | "Function called to display the *swift-helpful* buffer."
54 | :type 'function
55 | :group 'swift-helpful)
56 |
57 | (defcustom swift-helpful-doc-snippet-number-of-lines-context 5
58 | "Number of lines of documentation shown as context in documentation snippets."
59 | :type 'number
60 | :group 'swift-helpful)
61 |
62 | (defcustom swift-helpful-ripgrep-executable
63 | "rg"
64 | "Path of the ripgrep executable."
65 | :type 'string
66 | :group 'swift-helpful)
67 |
68 | (defcustom swift-helpful-stdlib-path nil
69 | "Path of a local Swift standard library checkout."
70 | :type 'string
71 | :group 'swift-helpful)
72 |
73 | (defcustom swift-helpful-debug-log nil
74 | "Whether `swift-helpful' will debug information to the Messages buffer during execution."
75 | :type 'boolean
76 | :group 'swift-helpful)
77 |
78 | (defface swift-helpful-section-title
79 | '((t (:weight bold)))
80 | "Face used for section titles in *swift-helpful* buffers.")
81 |
82 | ;; Buttons
83 | (define-button-type 'swift-helpful-manual-button
84 | 'action #'swift-helpful--manual
85 | 'symbol nil
86 | 'follow-link t
87 | 'help-echo "View this symbol in the Swift manual")
88 |
89 | (define-button-type 'swift-helpful-references-button
90 | 'action #'swift-helpful--references
91 | 'symbol nil
92 | 'source-buffer nil
93 | 'follow-link t
94 | 'help-echo "Search for references of this symbol in the codebase")
95 |
96 | (define-button-type 'swift-helpful-definition-button
97 | 'action #'swift-helpful--definition
98 | 'symbol nil
99 | 'source-buffer nil
100 | 'follow-link t
101 | 'help-echo "Search for definition of this symbol in the codebase")
102 |
103 | (define-button-type 'swift-helpful-navigate-button
104 | 'action #'swift-helpful--navigate
105 | 'path nil
106 | 'position nil
107 | 'follow-link t
108 | 'help-echo "Navigate to definition")
109 |
110 | (defun swift-helpful--navigate-button (text path &optional pos)
111 | "Return a button with TEXT caption that opens PATH and puts point at POS."
112 | (swift-helpful--button
113 | text
114 | 'swift-helpful-navigate-button
115 | 'path path
116 | 'position pos))
117 |
118 | (defun swift-helpful--navigate (button)
119 | "Navigate to the path this BUTTON represents."
120 | (find-file-other-window (substring-no-properties (button-get button 'path)))
121 | ;; We use `get-text-property' to work around an Emacs 25 bug:
122 | ;; http://git.savannah.gnu.org/cgit/emacs.git/commit/?id=f7c4bad17d83297ee9a1b57552b1944020f23aea
123 | (-when-let (pos (get-text-property button 'position
124 | (marker-buffer button)))
125 | (swift-helpful--goto-char-widen (swift-helpful--point-from-line pos))))
126 |
127 | (defun swift-helpful--make-manual-button (sym)
128 | "Make manual button for SYM."
129 | (swift-helpful--button
130 | "Read more in manual"
131 | 'swift-helpful-manual-button
132 | 'symbol sym))
133 |
134 | (defun swift-helpful--make-references-button (source-buffer sym)
135 | "Make search references button for SOURCE-BUFFER and SYM."
136 | (swift-helpful--button
137 | "Search references"
138 | 'swift-helpful-references-button
139 | 'symbol sym
140 | 'source-buffer source-buffer))
141 |
142 | (defun swift-helpful--make-definition-button (source-buffer sym)
143 | "Make search definition button for SOURCE-BUFFER and SYM."
144 | (swift-helpful--button
145 | "Go to definition"
146 | 'swift-helpful-definition-button
147 | 'symbol sym
148 | 'source-buffer source-buffer))
149 |
150 | (defun swift-helpful--button (text type &rest properties)
151 | "Create a button with some TEXT, TYPE, and PROPERTIES."
152 | (setq text (substring-no-properties text))
153 | (apply #'make-text-button
154 | text nil
155 | :type type
156 | properties))
157 |
158 | (defun swift-helpful--manual (button)
159 | "Open the manual for the system that this BUTTON represents."
160 | (let ((sym (button-get button 'symbol)))
161 | (info-lookup 'symbol sym #'swift-mode)))
162 |
163 | (defun swift-helpful--references (button)
164 | "Open the references for the system that this BUTTON represents."
165 | (let ((sym (button-get button 'symbol))
166 | (source-buffer (button-get button 'source-buffer)))
167 | (with-current-buffer source-buffer
168 | (xref-find-references sym))))
169 |
170 | (defun swift-helpful--definition (button)
171 | "Open the definition for the system that this BUTTON represents."
172 | (let ((sym (button-get button 'symbol))
173 | (source-buffer (button-get button 'source-buffer)))
174 | (with-current-buffer source-buffer
175 | (xref-find-definitions-other-window sym))))
176 |
177 | (defun swift-helpful--section-title (text)
178 | "Propertize TEXT as a section title."
179 | (format "%s\n" (propertize text 'face 'swift-helpful-section-title)))
180 |
181 | (defun swift-helpful--buffer (sym)
182 | "Return a buffer *swift-helpful* to display information about SYM."
183 | (let* ((buf-name
184 | (format "*swift-helpful %s*"
185 | sym))
186 | (buf (get-buffer buf-name)))
187 | (unless buf
188 | (setq buf (get-buffer-create buf-name)))
189 | (with-current-buffer buf
190 | (swift-helpful-mode))
191 | buf))
192 |
193 | (defun swift-helpful--in-manual-p (sym)
194 | "Return t if SYM is in a Swift or Swift-Reference manual."
195 | (let ((completions
196 | (cl-letf (((symbol-function #'message)
197 | (lambda (_format-string &rest _args))))
198 | (info-lookup->completions 'symbol 'swift-mode))))
199 | (-when-let (buf (get-buffer " temp-info-look"))
200 | (kill-buffer buf))
201 | (or (assoc sym completions)
202 | (assoc-string sym completions))))
203 |
204 | (defun swift-helpful--point-at-beginning-of-doc-snippet ()
205 | "Return the point at the beginning of the documentation snippet."
206 | (save-excursion
207 | (goto-char (point-min))
208 | (search-forward "\n")))
209 |
210 | (defun swift-helpful--goto-char-widen (pos)
211 | "Move point to POS in the current buffer.
212 | If narrowing is in effect, widen if POS isn't in the narrowed area."
213 | (when (or (< pos (point-min))
214 | (> pos (point-max)))
215 | (widen))
216 | (goto-char pos))
217 |
218 | (defun swift-helpful--generate-doc-snippet (sym)
219 | "Generate a documentation snippet from the manuals about SYM."
220 | (save-window-excursion
221 | ;; Reset the overlay, in case there was a recent Info search.
222 | (setq info-lookup-highlight-overlay nil)
223 | (info-lookup 'symbol sym #'swift-mode)
224 | (with-current-buffer "*info*"
225 | (unwind-protect
226 | ;; Get `info-lookup-highlight-overlay' and use it to produce a
227 | ;; better context for the snippet.
228 | (let ((highlight-overlay info-lookup-highlight-overlay))
229 | ;; Two cases: If we have a highlight overlay, that means we
230 | ;; found the keyword in the Info node page and we can provide
231 | ;; a more accurate doc snippet. If we don't have an overlay,
232 | ;; just show a few lines from the beginning of the useful part
233 | ;; of the Info content.
234 | (if highlight-overlay
235 | (swift-helpful--generate-doc-snippet-using-overlay highlight-overlay)
236 | (swift-helpful--generate-doc-snippet-general-algorithm)))
237 | (kill-buffer "*info*")))))
238 |
239 | (defvar swift-helpful--overlay-found nil
240 | "Flag that indicates if an `info-look' highlight overlay has been found.")
241 |
242 | (defvar swift-helpful--overlay-start-local nil
243 | "Overlay start position relative to a `swift-helpful' documentation section.")
244 |
245 | (defvar swift-helpful--overlay-end-local nil
246 | "Overlay end position relative to a `swift-helpful' documentation section.")
247 |
248 | (defun swift-helpful--generate-doc-snippet-using-overlay (overlay)
249 | "Generate a documentation snippet around an OVERLAY.
250 | OVERLAY represents a highlighted symbol reference in the Swift manuals."
251 | (swift-helpful--log "The documentation snippet is generated around a text match in the Info node.")
252 | (setq swift-helpful--overlay-found t)
253 | (let* ((overlay-start (overlay-start overlay))
254 | (overlay-end (overlay-end overlay))
255 | (beg-line (- (line-number-at-pos overlay-start)
256 | (/ swift-helpful-doc-snippet-number-of-lines-context 2)))
257 | (end-line (+ (line-number-at-pos overlay-end)
258 | (- swift-helpful-doc-snippet-number-of-lines-context
259 | (/ swift-helpful-doc-snippet-number-of-lines-context 2))))
260 | (info-buffer-string (buffer-string)))
261 | ;; Convert `overlay-start' coordinates to "local" coordinates,
262 | ;; that is, coordinates starting from `beg-line'.
263 | (setq swift-helpful--overlay-start-local (- overlay-start
264 | (swift-helpful--point-from-line beg-line)))
265 | ;; Convert `overlay-end' coordinates to "local" coordinates,
266 | ;; that is, coordinates starting from `beg-line'.
267 | (setq swift-helpful--overlay-end-local (- overlay-end
268 | (swift-helpful--point-from-line beg-line)))
269 | (with-temp-buffer
270 | (insert info-buffer-string)
271 | (let ((beg-pos (swift-helpful--point-from-line beg-line))
272 | (end-pos (swift-helpful--point-from-line end-line)))
273 | (format "%s [...]" (buffer-substring-no-properties
274 | beg-pos
275 | end-pos))))))
276 |
277 | (defun swift-helpful--generate-doc-snippet-general-algorithm ()
278 | "Generate a documentation snippet from the start of a Swift manual section.
279 | The number of lines in the documentation snippet is controlled by
280 | the `swift-helpful-doc-snippet-number-of-lines-context'
281 | variable."
282 | (swift-helpful--log "The documentation snippet is NOT generated around a text match in the Info node.")
283 | (setq swift-helpful--overlay-found nil)
284 | (let* ((beg-line (line-number-at-pos
285 | (swift-helpful--point-at-beginning-of-doc-snippet)))
286 | (end-line (1+
287 | (+ beg-line
288 | swift-helpful-doc-snippet-number-of-lines-context)))
289 | (info-buffer-string (buffer-string)))
290 | (with-temp-buffer
291 | (insert info-buffer-string)
292 | (let ((beg-pos (swift-helpful--point-from-line beg-line))
293 | (end-pos (swift-helpful--point-from-line end-line)))
294 | (format "%s [...]" (buffer-substring-no-properties
295 | beg-pos
296 | end-pos))))))
297 |
298 | (defun swift-helpful--point-from-line (line)
299 | "Return the point at the first character in LINE."
300 | (save-excursion
301 | (goto-char (point-min))
302 | (forward-line (1- line))
303 | (point)))
304 |
305 | (defun swift-helpful--generate-lsp-snippet (source-buffer)
306 | "Produce a LSP-based snippet at current point in SOURCE-BUFFER."
307 | (when (swift-helpful--lsp-info-p source-buffer)
308 | (save-window-excursion
309 | (with-current-buffer source-buffer
310 | (lsp-describe-thing-at-point))
311 | (let ((message (current-message)))
312 | (when (and
313 | (or (get-buffer "*lsp-help*") (get-buffer (help-buffer)))
314 | (or (not message)
315 | (not (string-match "No content at point" message))))
316 | (with-current-buffer (or (get-buffer "*lsp-help*") (help-buffer))
317 | (buffer-substring (point-min) (point-max))))))))
318 |
319 | (defun swift-helpful--standard-library-identifier-p (source-buffer)
320 | "Return t if the thing at point in SOURCE-BUFFER is a Swift stdlib identifier."
321 | (when (swift-helpful--lsp-info-p source-buffer)
322 | (with-current-buffer source-buffer
323 | (let ((loc (lsp-request "textDocument/definition"
324 | (lsp--text-document-position-params))))
325 | (if loc
326 | (let ((uri (gethash "uri" (car loc))))
327 | (or
328 | (string-match-p "Foundation.swiftmodule" uri)
329 | (string-match-p "Swift.swiftmodule" uri)))
330 | ;; Assume that if we don't have a definition, it may be a
331 | ;; standard library.
332 | t)))))
333 |
334 | (defun swift-helpful--lsp-info-p (source-buffer)
335 | "Return t if LSP could offer information about Swift code in SOURCE-BUFFER."
336 | (with-current-buffer source-buffer
337 | (and (bound-and-true-p lsp-mode)
338 | (derived-mode-p 'swift-mode)
339 | (lsp-workspaces))))
340 |
341 | (defun swift-helpful--type-signature-to-grep (lsp-snippet)
342 | "Return the type signature information from LSP-SNIPPET."
343 | (with-temp-buffer
344 | (insert lsp-snippet)
345 | ;; The type signature is placed in the second line of the snippet
346 | ;; and goes to the end of that line.
347 | (let ((beg-signature (progn (goto-char (point-min))
348 | (forward-line (1- 2))
349 | (point)))
350 | (end-signature (progn (end-of-line)
351 | (point))))
352 | (buffer-substring-no-properties
353 | beg-signature
354 | end-signature))))
355 |
356 | (defconst swift-helpful--highlighting-funcs
357 | '(ert--activate-font-lock-keywords
358 | highlight-quoted-mode
359 | rainbow-delimiters-mode)
360 | "Highlighting functions that are safe to run in a temporary buffer.
361 | This is used in `swift-helpful--syntax-highlight' to support extra
362 | highlighting that the user may have configured in their mode
363 | hooks.")
364 |
365 | (defconst swift-helpful-max-highlight 5000
366 | "Don't highlight code with more than this many characters.")
367 |
368 | (defun swift-helpful--syntax-highlight (source &optional mode)
369 | "Return a propertized version of SOURCE in MODE."
370 | (unless mode
371 | (setq mode #'swift-mode))
372 | (if (or
373 | (< (length source) swift-helpful-max-highlight)
374 | (eq mode 'swift-mode))
375 | (with-temp-buffer
376 | (insert source)
377 |
378 | ;; Switch to major-mode MODE, but don't run any hooks.
379 | (delay-mode-hooks (funcall mode))
380 |
381 | ;; `delayed-mode-hooks' contains mode hooks like
382 | ;; `emacs-lisp-mode-hook'. Build a list of functions that are run
383 | ;; when the mode hooks run.
384 | (let (hook-funcs)
385 | (dolist (hook delayed-mode-hooks)
386 | (let ((funcs (symbol-value hook)))
387 | (setq hook-funcs (append hook-funcs funcs))))
388 |
389 | ;; Filter hooks to those that relate to highlighting, and run them.
390 | (setq hook-funcs (-intersection hook-funcs
391 | swift-helpful--highlighting-funcs))
392 | (-map #'funcall hook-funcs))
393 |
394 | (if (fboundp 'font-lock-ensure)
395 | (font-lock-ensure)
396 | (with-no-warnings
397 | (font-lock-fontify-buffer)))
398 | (buffer-string))
399 | ;; SOURCE was too long to highlight in a reasonable amount of
400 | ;; time.
401 | (concat
402 | (propertize
403 | "// Skipping highlighting due to "
404 | 'face 'font-lock-comment-face)
405 | source)))
406 |
407 | (defun swift-helpful--rg-format-command (search-term dir)
408 | "Prepare a ripgrep command for SEARCH-TERM that search on DIR."
409 | (format
410 | "%s -U --line-number %s %s"
411 | swift-helpful-ripgrep-executable
412 | (shell-quote-argument search-term)
413 | dir))
414 |
415 | (defun swift-helpful--insert-source-code-in-buffer (source-file line source-code-buf)
416 | "Insert a Swift function at SOURCE-FILE:LINE into SOURCE-CODE-BUF."
417 | (with-temp-buffer
418 | (insert-file-contents source-file)
419 | (goto-char (point-min))
420 | (forward-line (1- line))
421 | (delay-mode-hooks (swift-mode))
422 | (swift-mode:end-of-defun)
423 | (swift-mode:beginning-of-defun)
424 | (swift-mode:narrow-to-defun)
425 | (let ((code-snippet (buffer-string)))
426 | (with-current-buffer source-code-buf
427 | (insert
428 | (concat "From "
429 | (swift-helpful--navigate-button
430 | (f-abbrev source-file)
431 | source-file
432 | line)))
433 | (insert "\n")
434 | (insert (swift-helpful--syntax-highlight
435 | code-snippet
436 | 'swift-mode))
437 | (insert "\n\n")))))
438 |
439 | (defun swift-helpful--sort-stdlib-grep-results (x y)
440 | "Sort standard library grep results X and Y by filename, alphabetically."
441 | (let* ((locx (compilation--message->loc x))
442 | (filex (caar (compilation--loc->file-struct locx)))
443 | (locy (compilation--message->loc y))
444 | (filey (caar (compilation--loc->file-struct locy))))
445 | (string< filex filey)))
446 |
447 | (defun swift-helpful--stdlib-grep (signature)
448 | "Grep for a Swift standard library SIGNATURE."
449 | (swift-helpful--log signature)
450 | (with-temp-buffer
451 | (let* ((stdlib-search-query (swift-helpful--prepare-type-signature-for-grep
452 | signature))
453 | (search-query-new-lines (swift-helpful--regex-new-lines-escape-chars
454 | stdlib-search-query '("(" ")" "[" "]")))
455 | (grep-command-format (swift-helpful--rg-format-command
456 | search-query-new-lines
457 | (expand-file-name swift-helpful-stdlib-path)))
458 | (search-results (shell-command-to-string grep-command-format))
459 | (current-file))
460 | (swift-helpful--log "Search query: %s" stdlib-search-query)
461 | (swift-helpful--log "Grep command: %s" grep-command-format)
462 | (swift-helpful--log "Query results: %s" search-results)
463 | (insert search-results)
464 | (grep-mode)
465 | (setq current-file nil)
466 | (let ((source-code-buf (get-buffer-create "*stdlib-source-code*"))
467 | (messages))
468 | (dotimes (i (count-lines (point-min) (point-max)))
469 | (goto-char (point-min))
470 | (let* ((msg (compilation-next-error i nil
471 | (or compilation-current-error
472 | compilation-messages-start
473 | (point-min)))))
474 | (push msg messages)))
475 | ;; Sort the grep results by filename.
476 | (sort messages #'swift-helpful--sort-stdlib-grep-results)
477 | (dolist (msg messages)
478 | (let* ((loc (compilation--message->loc msg))
479 | (file (caar (compilation--loc->file-struct loc)))
480 | (line (compilation--loc->line loc)))
481 | ;; Assume only one result per file.
482 | (unless (eq current-file file)
483 | (swift-helpful--log "Ripgrep result from file %s" file)
484 | (setq current-file file)
485 | (swift-helpful--insert-source-code-in-buffer
486 | file line source-code-buf))))
487 | (with-current-buffer source-code-buf
488 | (unwind-protect
489 | (buffer-string)
490 | (kill-buffer source-code-buf)))))))
491 |
492 | (defun swift-helpful--lsp-snippet-p (lsp-snippet)
493 | "Return if LSP-SNIPPET is a non-empty LSP snippet."
494 | (and lsp-snippet
495 | (char-or-string-p lsp-snippet)
496 | (not (string-blank-p lsp-snippet))))
497 |
498 | (defun swift-helpful--insert-header (sym)
499 | "Insert a section header for the symbol SYM."
500 | (insert
501 | (swift-helpful--section-title (format "%s" sym))
502 | "\n"))
503 |
504 | (defun swift-helpful--insert-lsp (sym source-buffer lsp-snippet)
505 | "Insert LSP information for the symbol SYM.
506 | SOURCE-BUFFER is the buffer where SYM comes from and the LSP
507 | information is passed in LSP-SNIPPET."
508 | (insert
509 | (swift-helpful--section-title "Signature Information (from LSP)")
510 | "\n"
511 | lsp-snippet
512 | "\n\n"
513 | (swift-helpful--section-title "Cross-references (from LSP)")
514 | "\n"
515 | (format "%s %s"
516 | (swift-helpful--make-references-button source-buffer sym)
517 | (swift-helpful--make-definition-button source-buffer sym))
518 | "\n\n"))
519 |
520 | (defun swift-helpful--insert-manuals (sym)
521 | "Insert Swift manual information for the symbol SYM in the current buffer."
522 | (insert
523 | (swift-helpful--section-title "Swift Language Documentation")
524 | "\n")
525 | (let ((point-before-snippet (point)))
526 | (insert (swift-helpful--generate-doc-snippet sym))
527 | (when swift-helpful--overlay-found
528 | (let ((new-overlay-start (+ point-before-snippet
529 | swift-helpful--overlay-start-local))
530 | (new-overlay-end (+ point-before-snippet
531 | swift-helpful--overlay-end-local)))
532 | (overlay-put (make-overlay new-overlay-start new-overlay-end)
533 | 'face info-lookup-highlight-face))))
534 | ;; Insert a "Read more in manual" button in case the user is
535 | ;; curious about this topic and wants to learn more.
536 | (insert
537 | "\n\n"
538 | (swift-helpful--make-manual-button sym)
539 | "\n\n"))
540 |
541 | (defun swift-helpful--insert-library-source-code (lsp-snippet)
542 | "Insert Swift standard library information for LSP-SNIPPET.
543 | Inserting source code from the standard library only requires
544 | that the `swift-helpful-stdlib-path' variable correctly points to
545 | a checkout of the Swift standard library and that the
546 | `swift-helpful-ripgrep-executable' variable points to a recent
547 | version of the rg command line
548 | tool (https://github.com/BurntSushi/ripgrep)."
549 | (let ((swift-helpful--stdlib-grep (substring-no-properties
550 | (swift-helpful--type-signature-to-grep
551 | lsp-snippet))))
552 | (unless (string-blank-p swift-helpful--stdlib-grep)
553 | (insert
554 | (swift-helpful--section-title "Source Code")
555 | "\n"
556 | swift-helpful--stdlib-grep))))
557 |
558 | (defun swift-helpful--update (sym source-buffer lsp-snippet)
559 | "Update the *swift-helpful* buffer to document SYM from SOURCE-BUFFER.
560 | This function creates several sections with all the documentation
561 | that could be found about the Swift symbol SYM. LSP-SNIPPET
562 | contains information from Language Server Protocol about that
563 | symbol."
564 | (let ((inhibit-read-only t)
565 | (standard-library-p
566 | (swift-helpful--standard-library-identifier-p source-buffer)))
567 | (if standard-library-p
568 | (swift-helpful--log "Symbol %s probably comes from the Swift standard library" sym)
569 | (swift-helpful--log "Symbol %s probably does not come from the Swift standard library" sym))
570 | (erase-buffer)
571 | (remove-overlays)
572 | ;; Header.
573 | (swift-helpful--insert-header sym)
574 | ;; LSP.
575 | (when (swift-helpful--lsp-snippet-p lsp-snippet)
576 | (swift-helpful--insert-lsp sym source-buffer lsp-snippet))
577 | ;; Manuals.
578 | (when (swift-helpful--in-manual-p sym)
579 | (swift-helpful--insert-manuals sym))
580 | ;; Standard library source code.
581 | (when (and (and swift-helpful-stdlib-path
582 | (file-exists-p swift-helpful-stdlib-path))
583 | (executable-find swift-helpful-ripgrep-executable)
584 | standard-library-p
585 | (swift-helpful--lsp-snippet-p lsp-snippet))
586 | (swift-helpful--insert-library-source-code lsp-snippet))
587 | ;; Position the point at the beginning of the buffer when
588 | ;; everything is in place.
589 | (goto-char (point-min))))
590 |
591 | (defun swift-helpful--symbol-at-point ()
592 | "Return the Swift symbol at point."
593 | (save-excursion
594 | (let* ((bounds (bounds-of-thing-at-point 'symbol))
595 | (start (car bounds))
596 | (end (cdr bounds)))
597 | (goto-char end)
598 | ;; Check if '?' and '!' follows, so we correctly distinguish
599 | ;; between 'try', 'try!', and 'try?'.
600 | (cond ((or (eq ?? (char-after))
601 | (eq ?! (char-after)))
602 | (buffer-substring-no-properties start (1+ end)))
603 | (t (buffer-substring-no-properties start end))))))
604 |
605 | (defun swift-helpful--log (msg &rest args)
606 | "Log MSG with ARGS to the Messages buffer if `swift-helpful-debug-log' is t."
607 | (when swift-helpful-debug-log
608 | (message msg args)))
609 |
610 | (defun swift-helpful-maybe-configure-manuals ()
611 | "Configure `info-look' so that Swift reference indices can be queried."
612 | (info-lookup-maybe-add-help
613 | :mode 'swift-mode
614 | :regexp "&\\(+\\|-\\|*\\)=\\|[#@_a-zA-Z][_a-zA-Z0-9\\?!]*"
615 | :doc-spec '(("(swift)Index" nil "['`‘]" "['’]")
616 | ("(swift-reference)Index" nil "['`‘]" "['’]"))))
617 |
618 | ;;;###autoload
619 | (defun swift-helpful ()
620 | "Open a panel with information about a Swift token at point.
621 | Information comes from different configurable sources: Language
622 | Server Protocol (LSP), the Swift reference manuals, or the
623 | standard library source code (if locally available and
624 | accessible)."
625 | (interactive)
626 | (let* ((sym (swift-helpful--symbol-at-point))
627 | (source-buffer (current-buffer))
628 | (lsp-snippet
629 | (swift-helpful--generate-lsp-snippet source-buffer)))
630 | (swift-helpful--log "Symbol under point %s" sym)
631 | (swift-helpful-maybe-configure-manuals)
632 | (unless sym
633 | (user-error "There isn't a Swift symbol under point"))
634 | (unless (or (swift-helpful--lsp-snippet-p lsp-snippet)
635 | (swift-helpful--in-manual-p sym))
636 | (user-error "%s: Not documented as a symbol" sym))
637 | (funcall swift-helpful-switch-buffer-function (swift-helpful--buffer sym))
638 | (swift-helpful--update sym source-buffer lsp-snippet)))
639 |
640 | (defvar swift-helpful-mode-map
641 | (let* ((map (make-sparse-keymap)))
642 | (define-key map (kbd "TAB") #'forward-button)
643 | (define-key map (kbd "") #'backward-button)
644 | map)
645 | "Keymap for `swift-helpful-mode'.")
646 |
647 | (define-derived-mode swift-helpful-mode special-mode "Swift-Helpful"
648 | "Major mode for *swift-helpful* buffers.")
649 |
650 | (provide 'swift-helpful)
651 |
652 | ;;; swift-helpful.el ends here
653 |
--------------------------------------------------------------------------------
/swift-info/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Attribution 4.0 International Public License
2 |
3 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
4 |
5 | Section 1 – Definitions.
6 |
7 | Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
8 | Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
9 | Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
10 | Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
11 | Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
12 | Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
13 | Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
14 | Licensor means the individual(s) or entity(ies) granting rights under this Public License.
15 | Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
16 | Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
17 | You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
18 | Section 2 – Scope.
19 |
20 | License grant.
21 | Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
22 | reproduce and Share the Licensed Material, in whole or in part; and
23 | produce, reproduce, and Share Adapted Material.
24 | Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
25 | Term. The term of this Public License is specified in Section 6(a).
26 | Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
27 | Downstream recipients.
28 | Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
29 | No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
30 | No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
31 | Other rights.
32 |
33 | Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
34 | Patent and trademark rights are not licensed under this Public License.
35 | To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
36 | Section 3 – License Conditions.
37 |
38 | Your exercise of the Licensed Rights is expressly made subject to the following conditions.
39 |
40 | Attribution.
41 |
42 | If You Share the Licensed Material (including in modified form), You must:
43 |
44 | retain the following if it is supplied by the Licensor with the Licensed Material:
45 | identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
46 | a copyright notice;
47 | a notice that refers to this Public License;
48 | a notice that refers to the disclaimer of warranties;
49 | a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
50 | indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
51 | indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
52 | You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
53 | If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
54 | If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
55 | Section 4 – Sui Generis Database Rights.
56 |
57 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
58 |
59 | for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
60 | if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
61 | You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
62 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
63 | Section 5 – Disclaimer of Warranties and Limitation of Liability.
64 |
65 | Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
66 | To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
67 | The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
68 | Section 6 – Term and Termination.
69 |
70 | This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
71 | Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
72 |
73 | automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
74 | upon express reinstatement by the Licensor.
75 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
76 | For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
77 | Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
78 | Section 7 – Other Terms and Conditions.
79 |
80 | The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
81 | Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
82 | Section 8 – Interpretation.
83 |
84 | For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
85 | To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
86 | No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
87 | Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
88 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
89 |
90 | Creative Commons may be contacted at creativecommons.org.
--------------------------------------------------------------------------------
/swift-info/Makefile:
--------------------------------------------------------------------------------
1 | all: swift.info swift.html swift-reference.info swift-reference.html
2 | html: swift.html swift-reference.html
3 |
4 | # Swift manual
5 |
6 | swift.texi: swift.org
7 | emacs -batch -l helper.el --eval "(org-to-texi \"swift.org\")"
8 |
9 | swift.info: swift.texi
10 | makeinfo --no-split $^
11 |
12 | swift.html: swift.texi
13 | makeinfo --no-split --html --css-ref=https://gnu.org/software/emacs/manual.css $^
14 |
15 | # Swift reference manual
16 |
17 | swift-reference.texi: swift-reference.org
18 | emacs -batch -l helper.el --eval "(org-to-texi \"swift-reference.org\")"
19 |
20 | swift-reference.info: swift-reference.texi
21 | makeinfo --no-split $^
22 |
23 | swift-reference.html: swift-reference.texi
24 | makeinfo --no-split --html --css-ref=https://gnu.org/software/emacs/manual.css $^
25 |
26 | .PHONY: all
27 |
--------------------------------------------------------------------------------
/swift-info/README.md:
--------------------------------------------------------------------------------
1 | # swift-info
2 |
3 | 
4 |
5 | (Work in progress.)
6 |
7 | Curated Swift 5.3 documentation and reference in GNU Info format, with cross-references and indices for concepts and keywords.
8 |
9 | If you use macOS, I recommend you install a newer version of GNU texinfo:
10 |
11 | ```sh
12 | brew install texinfo
13 | ```
14 |
15 | You can export the documentation by making the `all` target:
16 |
17 | ```sh
18 | make all
19 | ```
20 |
21 | This will generate up to date `.info`, `.texi` and `.html` files from `swift.org` and `swift-reference.org`.
22 |
23 | You can also export the documentation to HTML (the CSS used is the same one used by the Emacs manuals):
24 |
25 | ```sh
26 | make html
27 | ```
28 |
29 | ## Emacs
30 |
31 | Note that if you are using `swift-info` as part of the `swift-helpful` Emacs package you don't need to follow these instructions because everything is
32 | configured automatically as part of the package installation and load.
33 |
34 | You can add this Info manual to the list of existing manuals:
35 |
36 | ```elisp
37 | (add-to-list 'Info-directory-list "")
38 | ```
39 |
40 | If you want to use `info-lookup-symbol` in `swift-mode`, add the following code to your configuration file:
41 |
42 | ```elisp
43 | (require 'info-look)
44 | (info-lookup-maybe-add-help
45 | :mode 'swift-mode
46 | :regexp "[#@_a-zA-Z][_a-zA-Z0-9\\?!]*"
47 | :doc-spec '(("(swift)Index" nil "['`‘]" "['’]")
48 | ("(swift-reference)Index" nil "['`‘]" "['’]")))
49 | ```
50 |
51 | Visit a Swift file in `swift-mode`, place the point on a keyword and hit `C-h S` to see definitive discussion about that Swift keyword or concept.
52 |
--------------------------------------------------------------------------------
/swift-info/dir:
--------------------------------------------------------------------------------
1 | This is the file .../info/dir, which contains the
2 | topmost node of the Info hierarchy, called (dir)Top.
3 | The first time you invoke Info you start off looking at this node.
4 |
5 | File: dir, Node: Top This is the top of the INFO tree
6 |
7 | This (the Directory node) gives a menu of major topics.
8 | Typing "q" exits, "H" lists all Info commands, "d" returns here,
9 | "h" gives a primer for first-timers,
10 | "mEmacs" visits the Emacs manual, etc.
11 |
12 | In Emacs, you can click mouse button 2 on a menu item or cross reference
13 | to select it.
14 |
15 | * Menu:
16 |
17 | Emacs
18 | * Swift: (swift). The Swift programming language.
19 | * Swift Reference: (swift-reference).
20 | The Swift programming language reference.
21 |
--------------------------------------------------------------------------------
/swift-info/helper.el:
--------------------------------------------------------------------------------
1 | (setq org-confirm-babel-evaluate nil)
2 | (defun org-to-texi (fname)
3 | (find-file fname)
4 | (org-texinfo-export-to-texinfo))
5 |
--------------------------------------------------------------------------------
/swift-info/images/CollectionTypes_intro_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/CollectionTypes_intro_2x.png
--------------------------------------------------------------------------------
/swift-info/images/UTF16_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/UTF16_2x.png
--------------------------------------------------------------------------------
/swift-info/images/UTF8_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/UTF8_2x.png
--------------------------------------------------------------------------------
/swift-info/images/UnicodeScalar_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/UnicodeScalar_2x.png
--------------------------------------------------------------------------------
/swift-info/images/barcode_QR_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/barcode_QR_2x.png
--------------------------------------------------------------------------------
/swift-info/images/barcode_UPC_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/barcode_UPC_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftSignedAddition_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftSignedAddition_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftSignedFour_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftSignedFour_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftSignedMinusFourValue_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftSignedMinusFourValue_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftSignedMinusFour_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftSignedMinusFour_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftSigned_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftSigned_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitshiftUnsigned_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitshiftUnsigned_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitwiseAND_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitwiseAND_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitwiseNOT_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitwiseNOT_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitwiseOR_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitwiseOR_2x.png
--------------------------------------------------------------------------------
/swift-info/images/bitwiseXOR_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/bitwiseXOR_2x.png
--------------------------------------------------------------------------------
/swift-info/images/chessBoard_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/chessBoard_2x.png
--------------------------------------------------------------------------------
/swift-info/images/closureReferenceCycle01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/closureReferenceCycle01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/closureReferenceCycle02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/closureReferenceCycle02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/computedProperties_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/computedProperties_2x.png
--------------------------------------------------------------------------------
/swift-info/images/coordinateGraphComplex_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/coordinateGraphComplex_2x.png
--------------------------------------------------------------------------------
/swift-info/images/coordinateGraphMedium_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/coordinateGraphMedium_2x.png
--------------------------------------------------------------------------------
/swift-info/images/coordinateGraphSimple_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/coordinateGraphSimple_2x.png
--------------------------------------------------------------------------------
/swift-info/images/initializerDelegation01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/initializerDelegation01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/initializerDelegation02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/initializerDelegation02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/initializersExample01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/initializersExample01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/initializersExample02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/initializersExample02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/initializersExample03_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/initializersExample03_2x.png
--------------------------------------------------------------------------------
/swift-info/images/memory_increment_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/memory_increment_2x.png
--------------------------------------------------------------------------------
/swift-info/images/memory_share_health_maria_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/memory_share_health_maria_2x.png
--------------------------------------------------------------------------------
/swift-info/images/memory_share_health_oscar_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/memory_share_health_oscar_2x.png
--------------------------------------------------------------------------------
/swift-info/images/memory_shopping_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/memory_shopping_2x.png
--------------------------------------------------------------------------------
/swift-info/images/multilineStringWhitespace_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/multilineStringWhitespace_2x.png
--------------------------------------------------------------------------------
/swift-info/images/overflowAddition_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/overflowAddition_2x.png
--------------------------------------------------------------------------------
/swift-info/images/overflowSignedSubtraction_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/overflowSignedSubtraction_2x.png
--------------------------------------------------------------------------------
/swift-info/images/overflowUnsignedSubtraction_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/overflowUnsignedSubtraction_2x.png
--------------------------------------------------------------------------------
/swift-info/images/referenceCycle01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/referenceCycle01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/referenceCycle02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/referenceCycle02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/referenceCycle03_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/referenceCycle03_2x.png
--------------------------------------------------------------------------------
/swift-info/images/remainderInteger_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/remainderInteger_2x.png
--------------------------------------------------------------------------------
/swift-info/images/setEulerDiagram_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/setEulerDiagram_2x.png
--------------------------------------------------------------------------------
/swift-info/images/setVennDiagram_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/setVennDiagram_2x.png
--------------------------------------------------------------------------------
/swift-info/images/sharedStateClass_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/sharedStateClass_2x.png
--------------------------------------------------------------------------------
/swift-info/images/sharedStateStruct_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/sharedStateStruct_2x.png
--------------------------------------------------------------------------------
/swift-info/images/snakesAndLadders_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/snakesAndLadders_2x.png
--------------------------------------------------------------------------------
/swift-info/images/stackPoppedOneString_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/stackPoppedOneString_2x.png
--------------------------------------------------------------------------------
/swift-info/images/stackPushPop_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/stackPushPop_2x.png
--------------------------------------------------------------------------------
/swift-info/images/stackPushedFourStrings_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/stackPushedFourStrings_2x.png
--------------------------------------------------------------------------------
/swift-info/images/staticPropertiesVUMeter_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/staticPropertiesVUMeter_2x.png
--------------------------------------------------------------------------------
/swift-info/images/stringSubstring_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/stringSubstring_2x.png
--------------------------------------------------------------------------------
/swift-info/images/subscriptMatrix01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/subscriptMatrix01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/subscriptMatrix02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/subscriptMatrix02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/twoPhaseInitialization01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/twoPhaseInitialization01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/twoPhaseInitialization02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/twoPhaseInitialization02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/unownedOptionalReference_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/unownedOptionalReference_2x.png
--------------------------------------------------------------------------------
/swift-info/images/unownedReference01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/unownedReference01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/unownedReference02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/unownedReference02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/vectorAddition_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/vectorAddition_2x.png
--------------------------------------------------------------------------------
/swift-info/images/weakReference01_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/weakReference01_2x.png
--------------------------------------------------------------------------------
/swift-info/images/weakReference02_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/weakReference02_2x.png
--------------------------------------------------------------------------------
/swift-info/images/weakReference03_2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/images/weakReference03_2x.png
--------------------------------------------------------------------------------
/swift-info/screenshots/info-lookup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielmartin/swift-helpful/b46c580e4b8f55761431ec677866de3fc66592e9/swift-info/screenshots/info-lookup.png
--------------------------------------------------------------------------------
/targets/checkdoc.el:
--------------------------------------------------------------------------------
1 | (checkdoc-file "swift-helpful.el")
2 | (checkdoc-file "swift-helpful-regex.el")
3 |
--------------------------------------------------------------------------------
/test/swift-helpful-info-loader.el:
--------------------------------------------------------------------------------
1 | ;;; swift-helpful-info-loader.el --- Configures `swift-info' for running tests -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; This program is free software; you can redistribute it and/or modify
6 | ;; it under the terms of the GNU General Public License as published by
7 | ;; the Free Software Foundation, either version 3 of the License, or
8 | ;; (at your option) any later version.
9 |
10 | ;; This program is distributed in the hope that it will be useful,
11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;; GNU General Public License for more details.
14 |
15 | ;; You should have received a copy of the GNU General Public License
16 | ;; along with this program. If not, see .
17 |
18 | (require 'info-look)
19 | (require 'swift-helpful)
20 |
21 | (add-to-list 'Info-directory-list (format "%s/swift-info" swift-helpful-default-directory))
22 |
23 | (swift-helpful-maybe-configure-manuals)
24 |
--------------------------------------------------------------------------------
/test/swift-helpful-regex-test.el:
--------------------------------------------------------------------------------
1 | ;;; swift-helpful-regex-test.el --- Tests for `swift-helpful-regex' -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; This program is free software; you can redistribute it and/or modify
6 | ;; it under the terms of the GNU General Public License as published by
7 | ;; the Free Software Foundation, either version 3 of the License, or
8 | ;; (at your option) any later version.
9 |
10 | ;; This program is distributed in the hope that it will be useful,
11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;; GNU General Public License for more details.
14 |
15 | ;; You should have received a copy of the GNU General Public License
16 | ;; along with this program. If not, see .
17 |
18 | (require 'ert)
19 | (require 'swift-helpful-regex)
20 |
21 | (ert-deftest swift-helpful-regex--remove-non-interesting-syntax ()
22 | (should (equal (swift-helpful--remove-non-interesting-syntax "@inlinable public var first: Element? { get }")
23 | "@inlinable public var first: Element?"))
24 | (should (equal (swift-helpful--remove-non-interesting-syntax "func decode(_ type: String.Type, forKey key: KeyedDecodingContainer.Key) throws -> String")
25 | "func decode(_ type: String.Type, forKey key: Key) throws -> String")))
26 |
27 | (ert-deftest swift-helpful-regex--adapt-generics-test ()
28 | (should (equal (swift-helpful--adapt-for-generics "public func contains(_ other: T) -> Bool where T : StringProtocol")
29 | "public func contains(_ other: T) -> Bool")))
30 |
31 | (ert-deftest swift-helpful-regex--prepare-signature-to-grep-test ()
32 | (should (equal (swift-helpful--prepare-type-signature-for-grep
33 | "func contains(_ other: T) -> Bool where T : StringProtocol")
34 | "public func contains(_ other: T) -> Bool"))
35 | (should (equal (swift-helpful--prepare-type-signature-for-grep
36 | "@inlinable __consuming func filter(_ isIncluded: (String) throws -> Bool) rethrows -> [String]")
37 | "@inlinable public __consuming func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]"))
38 | (should (equal (swift-helpful--prepare-type-signature-for-grep
39 | "@inlinable func map(_ transform: (Wrapped) throws -> U) rethrows -> U?")
40 | "@inlinable public func map(_ transform: (Wrapped) throws -> U) rethrows -> U?"))
41 | (should (equal (swift-helpful--prepare-type-signature-for-grep
42 | "@inlinable func map(_ transform: (Self.Element) throws -> T) rethrows -> [T]")
43 | "@inlinable public func map(_ transform: (Element) throws -> T) rethrows -> [T]"))
44 | (should (equal (swift-helpful--prepare-type-signature-for-grep
45 | "@inlinable mutating func append(contentsOf newElements: __owned S) where Element == S.Element, S : Sequence")
46 | "@inlinable public mutating func append(contentsOf newElements: __owned S) where Element == S.Element")))
47 |
--------------------------------------------------------------------------------
/test/swift-helpful-test.el:
--------------------------------------------------------------------------------
1 | ;;; swift-helpful-test.el --- Tests for `swift-helpful' -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; This program is free software; you can redistribute it and/or modify
6 | ;; it under the terms of the GNU General Public License as published by
7 | ;; the Free Software Foundation, either version 3 of the License, or
8 | ;; (at your option) any later version.
9 |
10 | ;; This program is distributed in the hope that it will be useful,
11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;; GNU General Public License for more details.
14 |
15 | ;; You should have received a copy of the GNU General Public License
16 | ;; along with this program. If not, see .
17 |
18 | (require 'ert)
19 | (require 'swift-helpful)
20 |
21 | ;; Doc snippet generation tests
22 | (ert-deftest swift-helpful--generate-doc-snippet-blank-keyword-test ()
23 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
24 | (should-error (swift-helpful--generate-doc-snippet ""))))
25 |
26 | (ert-deftest swift-helpful--generate-doc-snippet-unknown-keyword-test ()
27 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
28 | (should-error (swift-helpful--generate-doc-snippet "abc"))))
29 |
30 | (ert-deftest swift-helpful--generate-doc-snippet-test ()
31 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
32 | (should (equal (swift-helpful--generate-doc-snippet "func")
33 | "
34 | All of this information is rolled up into the function’s
35 | _definition_, which is prefixed with the ‘func’ keyword. You indicate
36 | the function’s return type with the _return arrow_ ‘->’ (a hyphen
37 | followed by a right angle bracket), which is followed by the name of the
38 | [...]")))
39 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
40 | (should (equal (swift-helpful--generate-doc-snippet "init")
41 | "_Initializers_ are called to create a new instance of a particular type.
42 | In its simplest form, an initializer is like an instance method with no
43 | parameters, written using the ‘init’ keyword:
44 |
45 | init() {
46 | [...]")))
47 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
48 | (should (equal (swift-helpful--generate-doc-snippet "@autoclosure")
49 | "‘serve(customer:)’ below performs the same operation but, instead of
50 | taking an explicit closure, it takes an autoclosure by marking its
51 | parameter’s type with the ‘@autoclosure’ attribute. Now you can call
52 | the function as if it took a ‘String’ argument instead of a closure.
53 | The argument is automatically converted to a closure, because the
54 | [...]")))
55 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
56 | (should (equal (swift-helpful--generate-doc-snippet "@dynamicCallable")
57 | "
58 | 8.1.3 dynamicCallable
59 | ---------------------
60 |
61 | Apply this attribute to a class, structure, enumeration, or protocol to
62 | treat instances of the type as callable functions. The type must
63 | [...]")))
64 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
65 | (should (equal (swift-helpful--generate-doc-snippet "if")
66 | "---------
67 |
68 | In its simplest form, the ‘if’ statement has a single ‘if’ condition.
69 | It executes a set of statements only if that condition is ‘true’.
70 |
71 | [...]"))))
72 |
73 | (ert-deftest swift-helpful--generate-doc-snippet-num-lines-context-test ()
74 | (let ((swift-helpful-doc-snippet-number-of-lines-context 2))
75 | (cl-letf (((symbol-function #'display-color-p) #'swift-helpful-display-color-p))
76 | (should (equal (swift-helpful--generate-doc-snippet "if")
77 | "
78 | In its simplest form, the ‘if’ statement has a single ‘if’ condition.
79 | [...]")))))
80 |
81 | (ert-deftest swift-helpful--standard-library-grep ()
82 | (let ((swift-helpful-stdlib-path "/Users/fixture/swift-source/swift/stdlib/public/")
83 | (default-directory swift-helpful-default-directory))
84 | (cl-letf (((symbol-function #'shell-command-to-string) #'swift-helpful-shell-command-to-string))
85 | (should (equal (swift-helpful--stdlib-grep (swift-helpful-test-contents
86 | "filter-type-signature.txt"))
87 | (swift-helpful-test-contents "filter-definition.txt")))
88 | (should (equal (swift-helpful--stdlib-grep (swift-helpful-test-contents
89 | "contains-type-signature.txt"))
90 | (swift-helpful-test-contents "contains-definition.txt"))))))
91 |
92 | (ert-deftest swift-helpful--update-no-information-from-stdlib ()
93 | "No Swift standard library info means no Source Code section."
94 | (with-temp-buffer
95 | (cl-letf (((symbol-function #'swift-helpful--type-signature-to-grep)
96 | #'swift-helpful--type-signature-to-grep-mock)
97 | ((symbol-function #'swift-helpful--standard-library-identifier-p)
98 | #'swift-helpful--standard-library-identifier-mock-p))
99 | (swift-helpful--update "Int" (current-buffer) "Sample LSP Snippet")
100 | (should (equal (buffer-substring-no-properties (point-min) (point-max))
101 | "Int
102 |
103 | Signature Information (from LSP)
104 |
105 | Sample LSP Snippet
106 |
107 | Cross-references (from LSP)
108 |
109 | Search references Go to definition
110 |
111 | ")))))
112 |
--------------------------------------------------------------------------------
/test/test-data/contains-definition.txt:
--------------------------------------------------------------------------------
1 | From test/test-data/stdlib-mocks/NSStringAPI.swift
2 | public func contains(_ other: T) -> Bool {
3 | let r = self.range(of: other) != nil
4 | if #available(macOS 10.10, iOS 8.0, *) {
5 | assert(r == _ns.contains(other._ephemeralString))
6 | }
7 | return r
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/test/test-data/contains-rg-command.txt:
--------------------------------------------------------------------------------
1 | rg -U --line-number p\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*b\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*f\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*a\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*s\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\<\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*T\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\:\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*S\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*g\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*P\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\>\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\(\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*_\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*h\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\:\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*T\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\)\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*-\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\>\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*B\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l /Users/fixture/swift-source/swift/stdlib/public/
--------------------------------------------------------------------------------
/test/test-data/contains-rg-results.txt:
--------------------------------------------------------------------------------
1 | test/test-data/stdlib-mocks/NSStringAPI.swift:1675: public func contains(_ other: T) -> Bool {
2 |
--------------------------------------------------------------------------------
/test/test-data/contains-type-signature.txt:
--------------------------------------------------------------------------------
1 | func contains(_ other: T) -> Bool where T : StringProtocol
2 |
--------------------------------------------------------------------------------
/test/test-data/filter-definition.txt:
--------------------------------------------------------------------------------
1 | From test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb
2 | @inlinable
3 | public __consuming func filter(
4 | _ isIncluded: (Element) throws -> Bool
5 | ) rethrows -> [Element] {
6 | return try _box._filter(isIncluded)
7 | }
8 |
9 | From test/test-data/stdlib-mocks/Sequence.swift
10 | @inlinable
11 | public __consuming func filter(
12 | _ isIncluded: (Element) throws -> Bool
13 | ) rethrows -> [Element] {
14 | return try _filter(isIncluded)
15 | }
16 |
17 |
--------------------------------------------------------------------------------
/test/test-data/filter-rg-command.txt:
--------------------------------------------------------------------------------
1 | rg -U --line-number \@\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*a\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*b\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*p\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*b\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*_\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*_\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*s\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*m\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*g\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*f\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*f\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\(\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*_\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*i\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*s\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*I\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*c\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*u\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*d\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*d\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\:\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\(\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*E\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*m\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\)\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*h\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*w\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*s\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*-\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\>\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*B\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\)\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*h\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*r\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*o\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*w\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*s\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*-\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\>\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\ \[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\[\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*E\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*l\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*m\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*e\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*n\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*t\[\\n\ \\\(__owned\\\|\@inline\(__always\)\\\|\@discardableResult\\\|__consuming\\\)\]\*\\\] /Users/fixture/swift-source/swift/stdlib/public/
--------------------------------------------------------------------------------
/test/test-data/filter-rg-results.txt:
--------------------------------------------------------------------------------
1 | test/test-data/stdlib-mocks/ArrayType.swift:69: @inlinable
2 | test/test-data/stdlib-mocks/ArrayType.swift:70: public __consuming func filter(
3 | test/test-data/stdlib-mocks/ArrayType.swift:71: _ isIncluded: (Element) throws -> Bool
4 | test/test-data/stdlib-mocks/ArrayType.swift:72: ) rethrows -> [Element] {
5 | test/test-data/stdlib-mocks/Sequence.swift:638: @inlinable
6 | test/test-data/stdlib-mocks/Sequence.swift:639: public __consuming func filter(
7 | test/test-data/stdlib-mocks/Sequence.swift:640: _ isIncluded: (Element) throws -> Bool
8 | test/test-data/stdlib-mocks/Sequence.swift:641: ) rethrows -> [Element] {
9 | test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb:788: @inlinable
10 | test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb:789: public __consuming func filter(
11 | test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb:790: _ isIncluded: (Element) throws -> Bool
12 | test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb:791: ) rethrows -> [Element] {
13 |
--------------------------------------------------------------------------------
/test/test-data/filter-type-signature.txt:
--------------------------------------------------------------------------------
1 | @inlinable __consuming func filter(_ isIncluded: (String) throws -> Bool) rethrows -> [String]
2 |
--------------------------------------------------------------------------------
/test/test-data/stdlib-mocks/ArrayType.swift:
--------------------------------------------------------------------------------
1 | //===--- ArrayType.swift - Protocol for Array-like types ------------------===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | @usableFromInline
14 | internal protocol _ArrayProtocol
15 | : RangeReplaceableCollection, ExpressibleByArrayLiteral
16 | where Indices == Range {
17 | /// The number of elements the Array can store without reallocation.
18 | var capacity: Int { get }
19 |
20 | /// An object that guarantees the lifetime of this array's elements.
21 | var _owner: AnyObject? { get }
22 |
23 | /// If the elements are stored contiguously, a pointer to the first
24 | /// element. Otherwise, `nil`.
25 | var _baseAddressIfContiguous: UnsafeMutablePointer? { get }
26 |
27 | //===--- basic mutations ------------------------------------------------===//
28 |
29 | /// Reserve enough space to store minimumCapacity elements.
30 | ///
31 | /// - Postcondition: `capacity >= minimumCapacity` and the array has
32 | /// mutable contiguous storage.
33 | ///
34 | /// - Complexity: O(`self.count`).
35 | override mutating func reserveCapacity(_ minimumCapacity: Int)
36 |
37 | /// Insert `newElement` at index `i`.
38 | ///
39 | /// Invalidates all indices with respect to `self`.
40 | ///
41 | /// - Complexity: O(`self.count`).
42 | ///
43 | /// - Precondition: `startIndex <= i`, `i <= endIndex`.
44 | override mutating func insert(_ newElement: __owned Element, at i: Int)
45 |
46 | /// Remove and return the element at the given index.
47 | ///
48 | /// - returns: The removed element.
49 | ///
50 | /// - Complexity: Worst case O(*n*).
51 | ///
52 | /// - Precondition: `count > index`.
53 | @discardableResult
54 | override mutating func remove(at index: Int) -> Element
55 |
56 | //===--- implementation detail -----------------------------------------===//
57 |
58 | associatedtype _Buffer: _ArrayBufferProtocol where _Buffer.Element == Element
59 | init(_ buffer: _Buffer)
60 |
61 | // For testing.
62 | var _buffer: _Buffer { get }
63 | }
64 |
65 | extension _ArrayProtocol {
66 | // Since RangeReplaceableCollection now has a version of filter that is less
67 | // efficient, we should make the default implementation coming from Sequence
68 | // preferred.
69 | @inlinable
70 | public __consuming func filter(
71 | _ isIncluded: (Element) throws -> Bool
72 | ) rethrows -> [Element] {
73 | return try _filter(isIncluded)
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/test/test-data/stdlib-mocks/ExistentialCollection.swift.gyb:
--------------------------------------------------------------------------------
1 | //===--- ExistentialCollection.swift.gyb ----------------------*- swift -*-===//
2 | //
3 | // This source file is part of the Swift.org open source project
4 | //
5 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6 | // Licensed under Apache License v2.0 with Runtime Library Exception
7 | //
8 | // See https://swift.org/LICENSE.txt for license information
9 | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 | //
11 | //===----------------------------------------------------------------------===//
12 |
13 | %{
14 |
15 | from gyb_stdlib_support import (
16 | TRAVERSALS,
17 | collectionForTraversal
18 | )
19 |
20 | }%
21 |
22 | // TODO: swift-3-indexing-model: perform type erasure on the associated
23 | // `Indices` type.
24 |
25 | import SwiftShims
26 |
27 | @inline(never)
28 | @usableFromInline
29 | internal func _abstract(
30 | file: StaticString = #file,
31 | line: UInt = #line
32 | ) -> Never {
33 | fatalError("Method must be overridden", file: file, line: line)
34 | }
35 |
36 | //===--- Iterator ---------------------------------------------------------===//
37 | //===----------------------------------------------------------------------===//
38 |
39 | /// A type-erased iterator of `Element`.
40 | ///
41 | /// This iterator forwards its `next()` method to an arbitrary underlying
42 | /// iterator having the same `Element` type, hiding the specifics of the
43 | /// underlying `IteratorProtocol`.
44 | @frozen
45 | public struct AnyIterator {
46 | @usableFromInline
47 | internal let _box: _AnyIteratorBoxBase
48 |
49 | /// Creates an iterator that wraps a base iterator but whose type depends
50 | /// only on the base iterator's element type.
51 | ///
52 | /// You can use `AnyIterator` to hide the type signature of a more complex
53 | /// iterator. For example, the `digits()` function in the following example
54 | /// creates an iterator over a collection that lazily maps the elements of a
55 | /// `Range` instance to strings. Instead of returning an
56 | /// iterator with a type that encapsulates the implementation of the
57 | /// collection, the `digits()` function first wraps the iterator in an
58 | /// `AnyIterator` instance.
59 | ///
60 | /// func digits() -> AnyIterator {
61 | /// let lazyStrings = (0..<10).lazy.map { String($0) }
62 | /// let iterator:
63 | /// LazyMapIterator>, String>
64 | /// = lazyStrings.makeIterator()
65 | ///
66 | /// return AnyIterator(iterator)
67 | /// }
68 | ///
69 | /// - Parameter base: An iterator to type-erase.
70 | @inlinable
71 | public init(_ base: I) where I.Element == Element {
72 | self._box = _IteratorBox(base)
73 | }
74 |
75 | /// Creates an iterator that wraps the given closure in its `next()` method.
76 | ///
77 | /// The following example creates an iterator that counts up from the initial
78 | /// value of an integer `x` to 15:
79 | ///
80 | /// var x = 7
81 | /// let iterator: AnyIterator = AnyIterator {
82 | /// defer { x += 1 }
83 | /// return x < 15 ? x : nil
84 | /// }
85 | /// let a = Array(iterator)
86 | /// // a == [7, 8, 9, 10, 11, 12, 13, 14]
87 | ///
88 | /// - Parameter body: A closure that returns an optional element. `body` is
89 | /// executed each time the `next()` method is called on the resulting
90 | /// iterator.
91 | @inlinable
92 | public init(_ body: @escaping () -> Element?) {
93 | self._box = _IteratorBox(_ClosureBasedIterator(body))
94 | }
95 |
96 | @inlinable
97 | internal init(_box: _AnyIteratorBoxBase) {
98 | self._box = _box
99 | }
100 | }
101 |
102 | extension AnyIterator: IteratorProtocol {
103 | /// Advances to the next element and returns it, or `nil` if no next element
104 | /// exists.
105 | ///
106 | /// Once `nil` has been returned, all subsequent calls return `nil`.
107 | @inlinable
108 | public func next() -> Element? {
109 | return _box.next()
110 | }
111 | }
112 |
113 | /// Every `IteratorProtocol` can also be a `Sequence`. Note that
114 | /// traversing the sequence consumes the iterator.
115 | extension AnyIterator: Sequence { }
116 |
117 | @usableFromInline
118 | @frozen
119 | internal struct _ClosureBasedIterator: IteratorProtocol {
120 | @inlinable
121 | internal init(_ body: @escaping () -> Element?) {
122 | self._body = body
123 | }
124 | @inlinable
125 | internal func next() -> Element? { return _body() }
126 | @usableFromInline
127 | internal let _body: () -> Element?
128 | }
129 |
130 | @_fixed_layout
131 | @usableFromInline
132 | internal class _AnyIteratorBoxBase: IteratorProtocol {
133 | @inlinable // FIXME(sil-serialize-all)
134 | internal init() {}
135 |
136 | @inlinable // FIXME(sil-serialize-all)
137 | deinit {}
138 | /// Advances to the next element and returns it, or `nil` if no next element
139 | /// exists.
140 | ///
141 | /// Once `nil` has been returned, all subsequent calls return `nil`.
142 | ///
143 | /// - Note: Subclasses must override this method.
144 | @inlinable // FIXME(sil-serialize-all)
145 | internal func next() -> Element? { _abstract() }
146 | }
147 |
148 | @_fixed_layout
149 | @usableFromInline
150 | internal final class _IteratorBox<
151 | Base: IteratorProtocol
152 | >: _AnyIteratorBoxBase {
153 | @inlinable
154 | internal init(_ base: Base) { self._base = base }
155 | @inlinable // FIXME(sil-serialize-all)
156 | deinit {}
157 | @inlinable
158 | internal override func next() -> Base.Element? { return _base.next() }
159 | @usableFromInline
160 | internal var _base: Base
161 | }
162 |
163 | //===--- Sequence ---------------------------------------------------------===//
164 | //===----------------------------------------------------------------------===//
165 |
166 | % for Kind in ['Sequence', 'Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
167 |
168 | @_fixed_layout
169 | @usableFromInline
170 | % if Kind == 'Sequence':
171 | internal class _AnySequenceBox
172 | % elif Kind == 'Collection':
173 | internal class _AnyCollectionBox: _AnySequenceBox
174 | % elif Kind == 'BidirectionalCollection':
175 | internal class _AnyBidirectionalCollectionBox
176 | : _AnyCollectionBox
177 | % elif Kind == 'RandomAccessCollection':
178 | internal class _AnyRandomAccessCollectionBox
179 | : _AnyBidirectionalCollectionBox
180 | % else:
181 | % assert False, 'Unknown kind'
182 | % end
183 | {
184 |
185 | % if Kind == 'Sequence':
186 | @inlinable // FIXME(sil-serialize-all)
187 | internal init() { }
188 |
189 | @inlinable
190 | internal func _makeIterator() -> AnyIterator { _abstract() }
191 |
192 | @inlinable
193 | internal var _underestimatedCount: Int { _abstract() }
194 |
195 | @inlinable
196 | internal func _map(
197 | _ transform: (Element) throws -> T
198 | ) rethrows -> [T] {
199 | _abstract()
200 | }
201 |
202 | @inlinable
203 | internal func _filter(
204 | _ isIncluded: (Element) throws -> Bool
205 | ) rethrows -> [Element] {
206 | _abstract()
207 | }
208 |
209 | @inlinable
210 | internal func _forEach(
211 | _ body: (Element) throws -> Void
212 | ) rethrows {
213 | _abstract()
214 | }
215 |
216 | @inlinable
217 | internal func __customContainsEquatableElement(
218 | _ element: Element
219 | ) -> Bool? {
220 | _abstract()
221 | }
222 |
223 | @inlinable
224 | internal func __copyToContiguousArray() -> ContiguousArray {
225 | _abstract()
226 | }
227 |
228 | @inlinable
229 | internal func __copyContents(initializing buf: UnsafeMutableBufferPointer)
230 | -> (AnyIterator,UnsafeMutableBufferPointer.Index) {
231 | _abstract()
232 | }
233 |
234 | % end
235 |
236 | % # This deinit has to be present on all the types
237 | @inlinable // FIXME(sil-serialize-all)
238 | deinit {}
239 |
240 | % if Kind == 'Sequence':
241 | @inlinable
242 | internal func _drop(
243 | while predicate: (Element) throws -> Bool
244 | ) rethrows -> _AnySequenceBox {
245 | _abstract()
246 | }
247 |
248 | @inlinable
249 | internal func _dropFirst(_ n: Int) -> _AnySequenceBox {
250 | _abstract()
251 | }
252 |
253 | @inlinable
254 | internal func _dropLast(_ n: Int) -> [Element] {
255 | _abstract()
256 | }
257 |
258 | @inlinable
259 | internal func _prefix(_ maxLength: Int) -> _AnySequenceBox {
260 | _abstract()
261 | }
262 |
263 | @inlinable
264 | internal func _prefix(
265 | while predicate: (Element) throws -> Bool
266 | ) rethrows -> [Element] {
267 | _abstract()
268 | }
269 |
270 | @inlinable
271 | internal func _suffix(_ maxLength: Int) -> [Element] {
272 | _abstract()
273 | }
274 | % else:
275 | % override = 'override' if Kind != 'Collection' else ''
276 | @inlinable
277 | internal override func _drop(
278 | while predicate: (Element) throws -> Bool
279 | ) rethrows -> _Any${Kind}Box {
280 | _abstract()
281 | }
282 |
283 | @inlinable
284 | internal override func _dropFirst(_ n: Int) -> _Any${Kind}Box {
285 | _abstract()
286 | }
287 |
288 | @inlinable
289 | internal ${override} func _dropLast(_ n: Int) -> _Any${Kind}Box {
290 | _abstract()
291 | }
292 |
293 | @inlinable
294 | internal override func _prefix(_ maxLength: Int) -> _Any${Kind}Box {
295 | _abstract()
296 | }
297 |
298 | @inlinable
299 | internal ${override} func _prefix(
300 | while predicate: (Element) throws -> Bool
301 | ) rethrows -> _Any${Kind}Box {
302 | _abstract()
303 | }
304 |
305 | @inlinable
306 | internal ${override} func _suffix(_ maxLength: Int) -> _Any${Kind}Box {
307 | _abstract()
308 | }
309 | % end
310 |
311 | % if Kind == 'Collection':
312 | @inlinable
313 | internal subscript(i: _AnyIndexBox) -> Element { _abstract() }
314 |
315 | @inlinable
316 | internal func _index(after i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }
317 |
318 | @inlinable
319 | internal func _formIndex(after i: _AnyIndexBox) { _abstract() }
320 |
321 | @inlinable
322 | internal func _index(
323 | _ i: _AnyIndexBox, offsetBy n: Int
324 | ) -> _AnyIndexBox {
325 | _abstract()
326 | }
327 |
328 | @inlinable
329 | internal func _index(
330 | _ i: _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox
331 | ) -> _AnyIndexBox? {
332 | _abstract()
333 | }
334 |
335 | @inlinable
336 | internal func _formIndex(_ i: inout _AnyIndexBox, offsetBy n: Int) {
337 | _abstract()
338 | }
339 |
340 | @inlinable
341 | internal func _formIndex(
342 | _ i: inout _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox
343 | ) -> Bool {
344 | _abstract()
345 | }
346 |
347 | @inlinable
348 | internal func _distance(
349 | from start: _AnyIndexBox, to end: _AnyIndexBox
350 | ) -> Int {
351 | _abstract()
352 | }
353 |
354 | // TODO: swift-3-indexing-model: forward the following methods.
355 | /*
356 | var _indices: Indices
357 |
358 | __consuming func prefix(upTo end: Index) -> SubSequence
359 |
360 | __consuming func suffix(from start: Index) -> SubSequence
361 |
362 | func prefix(through position: Index) -> SubSequence
363 |
364 | var isEmpty: Bool { get }
365 | */
366 |
367 | @inlinable // FIXME(sil-serialize-all)
368 | internal var _count: Int { _abstract() }
369 |
370 | // TODO: swift-3-indexing-model: forward the following methods.
371 | /*
372 | func _customIndexOfEquatableElement(element: Element) -> Index??
373 | func _customLastIndexOfEquatableElement(element: Element) -> Index??
374 | */
375 |
376 | @inlinable
377 | internal init(
378 | _startIndex: _AnyIndexBox,
379 | endIndex: _AnyIndexBox
380 | ) {
381 | self._startIndex = _startIndex
382 | self._endIndex = endIndex
383 | }
384 |
385 | @usableFromInline
386 | internal let _startIndex: _AnyIndexBox
387 |
388 | @usableFromInline
389 | internal let _endIndex: _AnyIndexBox
390 | % end
391 |
392 | % if Kind in ['Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
393 | % override = 'override' if Kind != 'Collection' else ''
394 | @inlinable
395 | internal ${override} subscript(
396 | start start: _AnyIndexBox,
397 | end end: _AnyIndexBox
398 | ) -> _Any${Kind}Box { _abstract() }
399 | % end
400 |
401 | % if Kind == 'BidirectionalCollection':
402 | @inlinable
403 | internal func _index(before i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }
404 | @inlinable
405 | internal func _formIndex(before i: _AnyIndexBox) { _abstract() }
406 | % end
407 | }
408 |
409 | % end
410 |
411 | % for Kind in ['Sequence', 'Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
412 | % if Kind == 'Sequence':
413 | % EqualAndWeakerKinds = ['Sequence']
414 | % elif Kind == 'Collection':
415 | % EqualAndWeakerKinds = ['Sequence', 'Collection']
416 | % elif Kind == 'BidirectionalCollection':
417 | % EqualAndWeakerKinds = ['Sequence', 'Collection', 'BidirectionalCollection']
418 | % elif Kind == 'RandomAccessCollection':
419 | % EqualAndWeakerKinds = ['Sequence', 'Collection', 'BidirectionalCollection', 'RandomAccessCollection']
420 | % else:
421 | % assert False, 'Unknown kind'
422 | % end
423 |
424 |
425 |
426 | @_fixed_layout
427 | @usableFromInline
428 | internal final class _${Kind}Box: _Any${Kind}Box
429 | {
430 | @usableFromInline
431 | internal typealias Element = S.Element
432 |
433 | @inline(__always)
434 | @inlinable
435 | internal override func _makeIterator() -> AnyIterator {
436 | return AnyIterator(_base.makeIterator())
437 | }
438 | @inlinable
439 | internal override var _underestimatedCount: Int {
440 | return _base.underestimatedCount
441 | }
442 | @inlinable
443 | internal override func _map(
444 | _ transform: (Element) throws -> T
445 | ) rethrows -> [T] {
446 | return try _base.map(transform)
447 | }
448 | @inlinable
449 | internal override func _filter(
450 | _ isIncluded: (Element) throws -> Bool
451 | ) rethrows -> [Element] {
452 | return try _base.filter(isIncluded)
453 | }
454 | @inlinable
455 | internal override func _forEach(
456 | _ body: (Element) throws -> Void
457 | ) rethrows {
458 | return try _base.forEach(body)
459 | }
460 | @inlinable
461 | internal override func __customContainsEquatableElement(
462 | _ element: Element
463 | ) -> Bool? {
464 | return _base._customContainsEquatableElement(element)
465 | }
466 | @inlinable
467 | internal override func __copyToContiguousArray() -> ContiguousArray {
468 | return _base._copyToContiguousArray()
469 | }
470 | @inlinable
471 | internal override func __copyContents(initializing buf: UnsafeMutableBufferPointer)
472 | -> (AnyIterator,UnsafeMutableBufferPointer.Index) {
473 | let (it,idx) = _base._copyContents(initializing: buf)
474 | return (AnyIterator(it),idx)
475 | }
476 | % if Kind == 'Sequence':
477 | @inlinable
478 | internal override func _dropFirst(_ n: Int) -> _AnySequenceBox {
479 | return _SequenceBox>(_base: _base.dropFirst(n))
480 | }
481 | @inlinable
482 | internal override func _drop(
483 | while predicate: (Element) throws -> Bool
484 | ) rethrows -> _Any${Kind}Box {
485 | return try _SequenceBox>(_base: _base.drop(while: predicate))
486 | }
487 | @inlinable
488 | internal override func _dropLast(_ n: Int) -> [Element] {
489 | return _base.dropLast(n)
490 | }
491 | @inlinable
492 | internal override func _prefix(_ n: Int) -> _AnySequenceBox {
493 | return _SequenceBox>(_base: _base.prefix(n))
494 | }
495 | @inlinable
496 | internal override func _prefix(
497 | while predicate: (Element) throws -> Bool
498 | ) rethrows -> [Element] {
499 | return try _base.prefix(while: predicate)
500 | }
501 | @inlinable
502 | internal override func _suffix(_ maxLength: Int) -> [Element] {
503 | return _base.suffix(maxLength)
504 | }
505 | % else:
506 | @inline(__always)
507 | @inlinable
508 | internal override func _drop(
509 | while predicate: (Element) throws -> Bool
510 | ) rethrows -> _Any${Kind}Box {
511 | return try _${Kind}Box(_base: _base.drop(while: predicate))
512 | }
513 | @inline(__always)
514 | @inlinable
515 | internal override func _dropFirst(_ n: Int) -> _Any${Kind}Box {
516 | return _${Kind}Box(_base: _base.dropFirst(n))
517 | }
518 | @inline(__always)
519 | @inlinable
520 | internal override func _dropLast(_ n: Int) -> _Any${Kind}Box {
521 | return _${Kind}Box(_base: _base.dropLast(n))
522 | }
523 | @inline(__always)
524 | @inlinable
525 | internal override func _prefix(
526 | while predicate: (Element) throws -> Bool
527 | ) rethrows -> _Any${Kind}Box {
528 | return try _${Kind}Box(_base: _base.prefix(while: predicate))
529 | }
530 | @inline(__always)
531 | @inlinable
532 | internal override func _prefix(_ maxLength: Int) -> _Any${Kind}Box {
533 | return _${Kind}Box(_base: _base.prefix(maxLength))
534 | }
535 | @inline(__always)
536 | @inlinable
537 | internal override func _suffix(_ maxLength: Int) -> _Any${Kind}Box {
538 | return _${Kind}Box(_base: _base.suffix(maxLength))
539 | }
540 | % end
541 |
542 | @inlinable // FIXME(sil-serialize-all)
543 | deinit {}
544 |
545 | % if Kind == 'Sequence':
546 | @inlinable
547 | internal init(_base: S) {
548 | self._base = _base
549 | }
550 | % else:
551 | @inlinable
552 | internal init(_base: S) {
553 | self._base = _base
554 | super.init(
555 | _startIndex: _IndexBox(_base: _base.startIndex),
556 | endIndex: _IndexBox(_base: _base.endIndex))
557 | }
558 |
559 | @inlinable
560 | internal func _unbox(
561 | _ position: _AnyIndexBox, file: StaticString = #file, line: UInt = #line
562 | ) -> S.Index {
563 | if let i = position._unbox() as S.Index? {
564 | return i
565 | }
566 | fatalError("Index type mismatch!", file: file, line: line)
567 | }
568 |
569 | @inlinable
570 | internal override subscript(position: _AnyIndexBox) -> Element {
571 | return _base[_unbox(position)]
572 | }
573 |
574 | @inlinable
575 | internal override subscript(start start: _AnyIndexBox, end end: _AnyIndexBox)
576 | -> _Any${Kind}Box
577 | {
578 | return _${Kind}Box(_base:
579 | _base[_unbox(start)..<_unbox(end)]
580 | )
581 | }
582 |
583 | @inlinable
584 | internal override func _index(after position: _AnyIndexBox) -> _AnyIndexBox {
585 | return _IndexBox(_base: _base.index(after: _unbox(position)))
586 | }
587 |
588 | @inlinable
589 | internal override func _formIndex(after position: _AnyIndexBox) {
590 | if let p = position as? _IndexBox {
591 | return _base.formIndex(after: &p._base)
592 | }
593 | fatalError("Index type mismatch!")
594 | }
595 |
596 | @inlinable
597 | internal override func _index(
598 | _ i: _AnyIndexBox, offsetBy n: Int
599 | ) -> _AnyIndexBox {
600 | return _IndexBox(_base: _base.index(_unbox(i), offsetBy: numericCast(n)))
601 | }
602 |
603 | @inlinable
604 | internal override func _index(
605 | _ i: _AnyIndexBox,
606 | offsetBy n: Int,
607 | limitedBy limit: _AnyIndexBox
608 | ) -> _AnyIndexBox? {
609 | return _base.index(
610 | _unbox(i),
611 | offsetBy: numericCast(n),
612 | limitedBy: _unbox(limit))
613 | .map { _IndexBox(_base: $0) }
614 | }
615 |
616 | @inlinable
617 | internal override func _formIndex(
618 | _ i: inout _AnyIndexBox, offsetBy n: Int
619 | ) {
620 | if let box = i as? _IndexBox {
621 | return _base.formIndex(&box._base, offsetBy: numericCast(n))
622 | }
623 | fatalError("Index type mismatch!")
624 | }
625 |
626 | @inlinable
627 | internal override func _formIndex(
628 | _ i: inout _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox
629 | ) -> Bool {
630 | if let box = i as? _IndexBox {
631 | return _base.formIndex(
632 | &box._base,
633 | offsetBy: numericCast(n),
634 | limitedBy: _unbox(limit))
635 | }
636 | fatalError("Index type mismatch!")
637 | }
638 |
639 | @inlinable
640 | internal override func _distance(
641 | from start: _AnyIndexBox,
642 | to end: _AnyIndexBox
643 | ) -> Int {
644 | return numericCast(_base.distance(from: _unbox(start), to: _unbox(end)))
645 | }
646 |
647 | @inlinable
648 | internal override var _count: Int {
649 | return numericCast(_base.count)
650 | }
651 |
652 | % if Kind in ['BidirectionalCollection', 'RandomAccessCollection']:
653 | @inlinable
654 | internal override func _index(before position: _AnyIndexBox) -> _AnyIndexBox {
655 | return _IndexBox(_base: _base.index(before: _unbox(position)))
656 | }
657 |
658 | @inlinable
659 | internal override func _formIndex(before position: _AnyIndexBox) {
660 | if let p = position as? _IndexBox {
661 | return _base.formIndex(before: &p._base)
662 | }
663 | fatalError("Index type mismatch!")
664 | }
665 |
666 | % end
667 |
668 | % end
669 | @usableFromInline
670 | internal var _base: S
671 | }
672 | % end
673 |
674 | @usableFromInline
675 | @frozen
676 | internal struct _ClosureBasedSequence {
677 | @usableFromInline
678 | internal var _makeUnderlyingIterator: () -> Iterator
679 |
680 | @inlinable
681 | internal init(_ makeUnderlyingIterator: @escaping () -> Iterator) {
682 | self._makeUnderlyingIterator = makeUnderlyingIterator
683 | }
684 | }
685 |
686 | extension _ClosureBasedSequence: Sequence {
687 | @inlinable
688 | internal func makeIterator() -> Iterator {
689 | return _makeUnderlyingIterator()
690 | }
691 | }
692 |
693 | /// A type-erased sequence.
694 | ///
695 | /// An instance of `AnySequence` forwards its operations to an underlying base
696 | /// sequence having the same `Element` type, hiding the specifics of the
697 | /// underlying sequence.
698 | @frozen
699 | public struct AnySequence {
700 | @usableFromInline
701 | internal let _box: _AnySequenceBox
702 |
703 | /// Creates a sequence whose `makeIterator()` method forwards to
704 | /// `makeUnderlyingIterator`.
705 | @inlinable
706 | public init(
707 | _ makeUnderlyingIterator: @escaping () -> I
708 | ) where I.Element == Element {
709 | self.init(_ClosureBasedSequence(makeUnderlyingIterator))
710 | }
711 |
712 | @inlinable
713 | internal init(_box: _AnySequenceBox) {
714 | self._box = _box
715 | }
716 | }
717 |
718 | extension AnySequence: Sequence {
719 | public typealias Iterator = AnyIterator
720 |
721 | /// Creates a new sequence that wraps and forwards operations to `base`.
722 | @inlinable
723 | public init(_ base: S)
724 | where
725 | S.Element == Element {
726 | self._box = _SequenceBox(_base: base)
727 | }
728 | }
729 |
730 | % for Kind in ['Sequence', 'Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
731 | extension Any${Kind} {
732 | % if Kind == 'Sequence':
733 | /// Returns an iterator over the elements of this sequence.
734 | @inline(__always)
735 | @inlinable
736 | public __consuming func makeIterator() -> Iterator {
737 | return _box._makeIterator()
738 | }
739 | @inlinable
740 | public __consuming func dropLast(_ n: Int = 1) -> [Element] {
741 | return _box._dropLast(n)
742 | }
743 | @inlinable
744 | public __consuming func prefix(
745 | while predicate: (Element) throws -> Bool
746 | ) rethrows -> [Element] {
747 | return try _box._prefix(while: predicate)
748 | }
749 | @inlinable
750 | public __consuming func suffix(_ maxLength: Int) -> [Element] {
751 | return _box._suffix(maxLength)
752 | }
753 | % else:
754 | /// Returns an iterator over the elements of this collection.
755 | @inline(__always)
756 | @inlinable
757 | public __consuming func makeIterator() -> Iterator {
758 | return _box._makeIterator()
759 | }
760 | @inlinable
761 | public __consuming func dropLast(_ n: Int = 1) -> Any${Kind} {
762 | return Any${Kind}(_box: _box._dropLast(n))
763 | }
764 | @inlinable
765 | public __consuming func prefix(
766 | while predicate: (Element) throws -> Bool
767 | ) rethrows -> Any${Kind} {
768 | return try Any${Kind}(_box: _box._prefix(while: predicate))
769 | }
770 | @inlinable
771 | public __consuming func suffix(_ maxLength: Int) -> Any${Kind} {
772 | return Any${Kind}(_box: _box._suffix(maxLength))
773 | }
774 | % end
775 |
776 | @inlinable
777 | public var underestimatedCount: Int {
778 | return _box._underestimatedCount
779 | }
780 |
781 | @inlinable
782 | public func map(
783 | _ transform: (Element) throws -> T
784 | ) rethrows -> [T] {
785 | return try _box._map(transform)
786 | }
787 |
788 | @inlinable
789 | public __consuming func filter(
790 | _ isIncluded: (Element) throws -> Bool
791 | ) rethrows -> [Element] {
792 | return try _box._filter(isIncluded)
793 | }
794 |
795 | @inlinable
796 | public __consuming func forEach(
797 | _ body: (Element) throws -> Void
798 | ) rethrows {
799 | return try _box._forEach(body)
800 | }
801 |
802 | @inlinable
803 | public __consuming func drop(
804 | while predicate: (Element) throws -> Bool
805 | ) rethrows -> Any${Kind} {
806 | return try Any${Kind}(_box: _box._drop(while: predicate))
807 | }
808 |
809 | @inlinable
810 | public __consuming func dropFirst(_ n: Int = 1) -> Any${Kind} {
811 | return Any${Kind}(_box: _box._dropFirst(n))
812 | }
813 |
814 | @inlinable
815 | public __consuming func prefix(_ maxLength: Int = 1) -> Any${Kind} {
816 | return Any${Kind}(_box: _box._prefix(maxLength))
817 | }
818 |
819 | @inlinable
820 | public func _customContainsEquatableElement(
821 | _ element: Element
822 | ) -> Bool? {
823 | return _box.__customContainsEquatableElement(element)
824 | }
825 |
826 | @inlinable
827 | public __consuming func _copyToContiguousArray() -> ContiguousArray {
828 | return self._box.__copyToContiguousArray()
829 | }
830 |
831 | @inlinable
832 | public __consuming func _copyContents(initializing buf: UnsafeMutableBufferPointer)
833 | -> (AnyIterator,UnsafeMutableBufferPointer.Index) {
834 | let (it,idx) = _box.__copyContents(initializing: buf)
835 | return (AnyIterator(it),idx)
836 | }
837 | }
838 | % end
839 |
840 | //===--- Index ------------------------------------------------------------===//
841 | //===----------------------------------------------------------------------===//
842 |
843 | @usableFromInline
844 | internal protocol _AnyIndexBox: class {
845 | var _typeID: ObjectIdentifier { get }
846 |
847 | func _unbox() -> T?
848 |
849 | func _isEqual(to rhs: _AnyIndexBox) -> Bool
850 |
851 | func _isLess(than rhs: _AnyIndexBox) -> Bool
852 | }
853 |
854 | @_fixed_layout
855 | @usableFromInline
856 | internal final class _IndexBox: _AnyIndexBox {
857 | @usableFromInline
858 | internal var _base: BaseIndex
859 |
860 | @inlinable
861 | internal init(_base: BaseIndex) {
862 | self._base = _base
863 | }
864 |
865 | @inlinable
866 | internal func _unsafeUnbox(_ other: _AnyIndexBox) -> BaseIndex {
867 | return unsafeDowncast(other, to: _IndexBox.self)._base
868 | }
869 |
870 | @inlinable
871 | internal var _typeID: ObjectIdentifier {
872 | return ObjectIdentifier(type(of: self))
873 | }
874 |
875 | @inlinable
876 | internal func _unbox() -> T? {
877 | return (self as _AnyIndexBox as? _IndexBox)?._base
878 | }
879 |
880 | @inlinable
881 | internal func _isEqual(to rhs: _AnyIndexBox) -> Bool {
882 | return _base == _unsafeUnbox(rhs)
883 | }
884 |
885 | @inlinable
886 | internal func _isLess(than rhs: _AnyIndexBox) -> Bool {
887 | return _base < _unsafeUnbox(rhs)
888 | }
889 | }
890 |
891 | /// A wrapper over an underlying index that hides the specific underlying type.
892 | @frozen
893 | public struct AnyIndex {
894 | @usableFromInline
895 | internal var _box: _AnyIndexBox
896 |
897 | /// Creates a new index wrapping `base`.
898 | @inlinable
899 | public init(_ base: BaseIndex) {
900 | self._box = _IndexBox(_base: base)
901 | }
902 |
903 | @inlinable
904 | internal init(_box: _AnyIndexBox) {
905 | self._box = _box
906 | }
907 |
908 | @inlinable
909 | internal var _typeID: ObjectIdentifier {
910 | return _box._typeID
911 | }
912 | }
913 |
914 | extension AnyIndex: Comparable {
915 | /// Returns a Boolean value indicating whether two indices wrap equal
916 | /// underlying indices.
917 | ///
918 | /// The types of the two underlying indices must be identical.
919 | ///
920 | /// - Parameters:
921 | /// - lhs: An index to compare.
922 | /// - rhs: Another index to compare.
923 | @inlinable
924 | public static func == (lhs: AnyIndex, rhs: AnyIndex) -> Bool {
925 | _precondition(lhs._typeID == rhs._typeID, "Base index types differ")
926 | return lhs._box._isEqual(to: rhs._box)
927 | }
928 |
929 | /// Returns a Boolean value indicating whether the first argument represents a
930 | /// position before the second argument.
931 | ///
932 | /// The types of the two underlying indices must be identical.
933 | ///
934 | /// - Parameters:
935 | /// - lhs: An index to compare.
936 | /// - rhs: Another index to compare.
937 | @inlinable
938 | public static func < (lhs: AnyIndex, rhs: AnyIndex) -> Bool {
939 | _precondition(lhs._typeID == rhs._typeID, "Base index types differ")
940 | return lhs._box._isLess(than: rhs._box)
941 | }
942 | }
943 |
944 | //===--- Collections ------------------------------------------------------===//
945 | //===----------------------------------------------------------------------===//
946 |
947 | public // @testable
948 | protocol _AnyCollectionProtocol: Collection {
949 | /// Identifies the underlying collection stored by `self`. Instances
950 | /// copied or upgraded/downgraded from one another have the same `_boxID`.
951 | var _boxID: ObjectIdentifier { get }
952 | }
953 |
954 | % for (ti, Traversal) in enumerate(TRAVERSALS):
955 | % SelfProtocol = collectionForTraversal(Traversal)
956 | % Self = 'Any' + SelfProtocol
957 | /// A type-erased wrapper over any collection with indices that
958 | /// support ${Traversal.lower().replace('omacc', 'om acc')} traversal.
959 | ///
960 | /// An `${Self}` instance forwards its operations to a base collection having the
961 | /// same `Element` type, hiding the specifics of the underlying
962 | /// collection.
963 | @frozen
964 | public struct ${Self} {
965 | @usableFromInline
966 | internal let _box: _${Self}Box
967 |
968 | @inlinable
969 | internal init(_box: _${Self}Box) {
970 | self._box = _box
971 | }
972 | }
973 |
974 | extension ${Self}: ${SelfProtocol} {
975 | public typealias Indices = DefaultIndices<${Self}>
976 | public typealias Iterator = AnyIterator
977 | public typealias Index = AnyIndex
978 | public typealias SubSequence = ${Self}
979 |
980 | % for SubTraversal in TRAVERSALS[ti:]:
981 | % SubProtocol = collectionForTraversal(SubTraversal)
982 | /// Creates a type-erased collection that wraps the given collection.
983 | ///
984 | /// - Parameter base: The collection to wrap.
985 | ///
986 | /// - Complexity: O(1).
987 | @inline(__always)
988 | @inlinable
989 | public init(_ base: C) where C.Element == Element {
990 | // Traversal: ${Traversal}
991 | // SubTraversal: ${SubTraversal}
992 | self._box = _${SubProtocol}Box(
993 | _base: base)
994 | }
995 |
996 | /// Creates an `${Self}` having the same underlying collection as `other`.
997 | ///
998 | /// - Complexity: O(1)
999 | @inlinable
1000 | public init(_ other: Any${SubProtocol}) {
1001 | self._box = other._box
1002 | }
1003 | % end
1004 |
1005 | % for SuperTraversal in TRAVERSALS[:ti]:
1006 | /// Creates an `${Self}` having the same underlying collection as `other`.
1007 | ///
1008 | /// If the underlying collection stored by `other` does not satisfy
1009 | /// `${SelfProtocol}`, the result is `nil`.
1010 | ///
1011 | /// - Complexity: O(1)
1012 | @inlinable
1013 | public init?(_ other: Any${collectionForTraversal(SuperTraversal)}) {
1014 | guard let box =
1015 | other._box as? _${Self}Box else {
1016 | return nil
1017 | }
1018 | self._box = box
1019 | }
1020 | % end
1021 |
1022 | /// The position of the first element in a non-empty collection.
1023 | ///
1024 | /// In an empty collection, `startIndex == endIndex`.
1025 | @inlinable
1026 | public var startIndex: Index {
1027 | return AnyIndex(_box: _box._startIndex)
1028 | }
1029 |
1030 | /// The collection's "past the end" position---that is, the position one
1031 | /// greater than the last valid subscript argument.
1032 | ///
1033 | /// `endIndex` is always reachable from `startIndex` by zero or more
1034 | /// applications of `index(after:)`.
1035 | @inlinable
1036 | public var endIndex: Index {
1037 | return AnyIndex(_box: _box._endIndex)
1038 | }
1039 |
1040 | /// Accesses the element indicated by `position`.
1041 | ///
1042 | /// - Precondition: `position` indicates a valid position in `self` and
1043 | /// `position != endIndex`.
1044 | @inlinable
1045 | public subscript(position: Index) -> Element {
1046 | return _box[position._box]
1047 | }
1048 |
1049 | @inlinable
1050 | public subscript(bounds: Range) -> SubSequence {
1051 | return ${Self}(_box:
1052 | _box[start: bounds.lowerBound._box, end: bounds.upperBound._box])
1053 | }
1054 |
1055 | @inlinable
1056 | public func _failEarlyRangeCheck(_ index: Index, bounds: Range) {
1057 | // Do nothing. Doing a range check would involve unboxing indices,
1058 | // performing dynamic dispatch etc. This seems to be too costly for a fast
1059 | // range check for QoI purposes.
1060 | }
1061 |
1062 | @inlinable
1063 | public func _failEarlyRangeCheck(_ range: Range, bounds: Range) {
1064 | // Do nothing. Doing a range check would involve unboxing indices,
1065 | // performing dynamic dispatch etc. This seems to be too costly for a fast
1066 | // range check for QoI purposes.
1067 | }
1068 |
1069 | @inlinable
1070 | public func index(after i: Index) -> Index {
1071 | return AnyIndex(_box: _box._index(after: i._box))
1072 | }
1073 |
1074 | @inlinable
1075 | public func formIndex(after i: inout Index) {
1076 | if _isUnique(&i._box) {
1077 | _box._formIndex(after: i._box)
1078 | }
1079 | else {
1080 | i = index(after: i)
1081 | }
1082 | }
1083 |
1084 | @inlinable
1085 | public func index(_ i: Index, offsetBy n: Int) -> Index {
1086 | return AnyIndex(_box: _box._index(i._box, offsetBy: n))
1087 | }
1088 |
1089 | @inlinable
1090 | public func index(
1091 | _ i: Index, offsetBy n: Int, limitedBy limit: Index
1092 | ) -> Index? {
1093 | return _box._index(i._box, offsetBy: n, limitedBy: limit._box)
1094 | .map { AnyIndex(_box:$0) }
1095 | }
1096 |
1097 | @inlinable
1098 | public func formIndex(_ i: inout Index, offsetBy n: Int) {
1099 | if _isUnique(&i._box) {
1100 | return _box._formIndex(&i._box, offsetBy: n)
1101 | } else {
1102 | i = index(i, offsetBy: n)
1103 | }
1104 | }
1105 |
1106 | @inlinable
1107 | public func formIndex(
1108 | _ i: inout Index,
1109 | offsetBy n: Int,
1110 | limitedBy limit: Index
1111 | ) -> Bool {
1112 | if _isUnique(&i._box) {
1113 | return _box._formIndex(&i._box, offsetBy: n, limitedBy: limit._box)
1114 | }
1115 | if let advanced = index(i, offsetBy: n, limitedBy: limit) {
1116 | i = advanced
1117 | return true
1118 | }
1119 | i = limit
1120 | return false
1121 | }
1122 |
1123 | @inlinable
1124 | public func distance(from start: Index, to end: Index) -> Int {
1125 | return _box._distance(from: start._box, to: end._box)
1126 | }
1127 |
1128 | /// The number of elements.
1129 | ///
1130 | % if Traversal != 'RandomAccess':
1131 | /// To check whether a collection is empty, use its `isEmpty` property
1132 | /// instead of comparing `count` to zero. Calculating `count` can be an O(*n*)
1133 | /// operation.
1134 | ///
1135 | % end
1136 | /// - Complexity: ${'O(1)' if Traversal == 'RandomAccess' else 'O(*n*)'}
1137 | @inlinable
1138 | public var count: Int {
1139 | return _box._count
1140 | }
1141 |
1142 | % if Traversal == 'Bidirectional' or Traversal == 'RandomAccess':
1143 | @inlinable
1144 | public func index(before i: Index) -> Index {
1145 | return AnyIndex(_box: _box._index(before: i._box))
1146 | }
1147 |
1148 | @inlinable
1149 | public func formIndex(before i: inout Index) {
1150 | if _isUnique(&i._box) {
1151 | _box._formIndex(before: i._box)
1152 | }
1153 | else {
1154 | i = index(before: i)
1155 | }
1156 | }
1157 | % end
1158 | }
1159 |
1160 | extension ${Self}: _AnyCollectionProtocol {
1161 | /// Uniquely identifies the stored underlying collection.
1162 | @inlinable
1163 | public // Due to language limitations only
1164 | var _boxID: ObjectIdentifier {
1165 | return ObjectIdentifier(_box)
1166 | }
1167 | }
1168 | % end
1169 |
1170 | // ${'Local Variables'}:
1171 | // eval: (read-only-mode 1)
1172 | // End:
1173 |
--------------------------------------------------------------------------------
/test/test-helper.el:
--------------------------------------------------------------------------------
1 | ;;; test-helper.el --- Helper for tests -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2019 Daniel Martín
4 |
5 | ;; This program is free software; you can redistribute it and/or modify
6 | ;; it under the terms of the GNU General Public License as published by
7 | ;; the Free Software Foundation, either version 3 of the License, or
8 | ;; (at your option) any later version.
9 |
10 | ;; This program is distributed in the hope that it will be useful,
11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;; GNU General Public License for more details.
14 |
15 | ;; You should have received a copy of the GNU General Public License
16 | ;; along with this program. If not, see .
17 |
18 | (require 'f)
19 |
20 | (defvar swift-helpful-default-directory
21 | (f-parent (f-dirname (f-this-file)))
22 | "Return the root directory of the `swift-helpful' project.")
23 |
24 | (defun swift-helpful-test-contents (file)
25 | "Return FILE contents as string."
26 | (with-temp-buffer
27 | (insert-file-contents
28 | (format "%s/test/test-data/%s"
29 | swift-helpful-default-directory
30 | file))
31 | (buffer-string)))
32 |
33 | (defun swift-helpful-shell-command-to-string (command)
34 | "Mock `shell-command-to-string' to not access the system shell."
35 | (cond
36 | ((string-equal command (swift-helpful-test-contents
37 | "filter-rg-command.txt"))
38 | (swift-helpful-test-contents "filter-rg-results.txt"))
39 | ((string-equal command (swift-helpful-test-contents
40 | "contains-rg-command.txt"))
41 | (swift-helpful-test-contents "contains-rg-results.txt"))
42 | (t (error "Couldn't mock shell command %s" command))))
43 |
44 | (defun swift-helpful-display-color-p (&optional display)
45 | "Mock `display-color-p' to assume the DISPLAY always support color.
46 | We need to mock this function because we rely on overlays created
47 | by `info-look' to provide a better context for the documentation
48 | snippet. Per `info-look' implementation, overlays are only
49 | created when the display supports color, and this is not the case
50 | when Emacs runs in batch mode."
51 | t)
52 |
53 | (defun swift-helpful--type-signature-to-grep-mock (signature)
54 | "Mock `swift-helpful--type-signature-to-grep' to simulate a no results
55 | status for a stdlib search for SIGNATURE."
56 | "")
57 |
58 | (defun swift-helpful--standard-library-identifier-mock-p (source-buffer)
59 | "Mock `swift-helpful--standard-library-identifier-p' to
60 | simulate that the symbol at point at SOURCE-BUFFER comes from
61 | the Swift standard library."
62 | t)
63 |
64 | ;;; test-helper.el ends here
65 |
--------------------------------------------------------------------------------