├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
├── src
├── main
│ ├── antlr4
│ │ └── pyjava
│ │ │ └── parser
│ │ │ ├── PyJavaLexer.g4
│ │ │ └── PyJavaParser.g4
│ └── java
│ │ └── pyjava
│ │ ├── PyJava.java
│ │ ├── PyJavaOptions.java
│ │ ├── parser
│ │ ├── PyJavaLexerBase.java
│ │ └── PyJavaParserBase.java
│ │ └── tree
│ │ ├── GetGroupAtom.java
│ │ ├── GetGroupAtomContents.java
│ │ ├── GetPrimary.java
│ │ ├── IndentationAwareAppender.java
│ │ ├── LazyAppendable.java
│ │ └── Transpiler.java
└── test
│ └── java
│ └── pyjava
│ ├── BasicTests.java
│ ├── TestComments.java
│ ├── TestCompoundExpressions.java
│ ├── TestDecorators.java
│ └── TestForceParens.java
└── tool-tests
├── 1
├── expected
│ ├── main.py
│ └── utils
│ │ └── points.py
└── input
│ ├── main.pyj
│ └── utils
│ └── points.pyj
└── runtests.sh
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Python
2 | .pyc
3 | __pycache__/
4 |
5 | # VS Code
6 | .vscode/
7 | .code-workspace
8 |
9 | # Java
10 | *.class
11 |
12 | # Eclipse
13 | .settings/
14 | bin/
15 | tmp/
16 | .metadata
17 | .classpath
18 | .project
19 | *.tmp
20 | *.bak
21 | *.swp
22 | *~.nib
23 | local.properties
24 | .loadpath
25 | .factorypath
26 |
27 | # Maven
28 | target/
29 | pom.xml.tag
30 | pom.xml.releaseBackup
31 | pom.xml.versionsBackup
32 | pom.xml.next
33 | pom.xml.bak
34 | dependency-reduced-pom.xml
35 |
36 | # Antlr
37 | .antlr/
38 |
39 | # OS X
40 | .DS_Store
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PyJava
2 | ### Description
3 | This project is the inverse of my [JavaPy project](https://github.com/raptor4694/JavaPy). It allows you to write Python code using semicolons and braces instead of indentation, like Java.
4 |
5 | ### Usage
6 | Call the program with `java -jar pyjava.jar ` and it will output a file
7 | called the same thing except with a `.py` extension.
8 | You can use pyjavaconfig.json to configure parsing options.
9 | The program tries to format the file to be human-readable but may not be quite right in places. Use your own formatter as necessary.
10 | The parser does not *always* check for semantically invalid syntax, such as duplicate/missing variable names, duplicate functions, etc.
11 |
12 | ### Config File
13 | The configuration file, if present, has the format
14 | ```typescript
15 | {
16 | "requireSemicolons"?: boolean = false,
17 | "allowColonSimpleBlocks"?: boolean = true,
18 | "allowNoColonSimpleBlocks"?: boolean = true,
19 | "forceParensInStatements"?: boolean = false,
20 | "forceParensInReturnYieldRaise"?: boolean = false,
21 | "files"?: {
22 | "include"?: string[] = ["**.pyj"],
23 | "exclude"?: string[] = []
24 | }
25 | }
26 | ```
27 |
28 | #### requireSemicolons
29 | Simply put, if this is `true` then semicolons will be required at the end of statements, as opposed to the default method which is similar to JavaScript's semicolon auto-insertion.
30 |
31 | Defaults to `false`.
32 |
33 | ##### Example:
34 | Input:
35 | ```python
36 | if (condition)
37 | return
38 | getValue();
39 | ```
40 |
41 | Output when `requireSemicolons` is false:
42 | ```python
43 | if (condition):
44 | return
45 | getValue()
46 | ```
47 |
48 | Output when `requireSemicolons` is true:
49 | ```python
50 | if (condition):
51 | return getValue()
52 | ```
53 |
54 | #### allowColonSimpleBlocks
55 | This allows you to have blocks consisting of a colon followed by a single statement, such as
56 | ```python
57 | if condition: return True
58 | ```
59 |
60 | Defaults to `true`.
61 |
62 | #### allowNoColonSimpleBlocks
63 | This allows you to have blocks consisting of a single statement, such as
64 | ```python
65 | if condition
66 | return True
67 | ```
68 |
69 | Defaults to `true`.
70 |
71 | #### forceParensInStatements
72 | This option, when `true`, requires conditions in `if`, `while`, `for` and other statements to be surrounded by parenthesis.
73 | ```python
74 | if (condition) { ... }
75 |
76 | while (condition) { ... }
77 |
78 | for (elem in values) { ... }
79 | ```
80 |
81 | Defaults to `false`.
82 |
83 | #### forceParensInReturnYieldRaise
84 | This option, when `true`, requires the values of `return`, `yield`, `assert`, `raise`, and basically any other statement which accepts an expression immediately following its keyword, to be enclosed by parenthesis.
85 | ```python
86 | return (value)
87 | raise (Exception)
88 | yield (element)
89 | assert (condition, "message")
90 | del (x.y, z[0])
91 | ```
92 |
93 | Defaults to `false`.
94 |
95 | #### files
96 | This object allows you to specify a list of files/folder globs to include and exclude from compilation.
97 |
98 | `include` defaults to `["**.pyj"]`.
99 | `exclude` defaults to `[]`.
100 |
101 | ### Differences from Normal Python
102 | #### Simple Statements
103 | Non-compound statements must now end with a semicolon *unless* the `--optional-semicolons` flag is provided.
104 |
105 | #### Code Blocks (aka Suites)
106 | A block of code is now enclosed in curly brackets `{` `}`.
107 | You can also do a colon `:` followed by a single statement.
108 |
109 | **Examples**:
110 |
111 | Normal Python:
112 | ```python
113 | class Example:
114 | def __init__(self, x, y):
115 | self.x = x
116 | self.y = y
117 | ```
118 | PyJava:
119 | ```python
120 | class Example {
121 | def __init__(self, x, y) {
122 | self.x = x;
123 | self.y = y;
124 | }
125 | }
126 | ```
127 |
129 |
130 | #### Lambdas
131 | A nice pro of not caring about whitespace is that you can now make mutli-line lambdas (anonymous functions).
132 |
133 | **Example**:
134 | ```python
135 | filter(lambda x {
136 | if not isinstance(x, str):
137 | return False;
138 | if x.isspace():
139 | return False;
140 | return True;
141 | }, args)
142 | ```
143 |
144 | You can also add type annotations to lambdas. Adding type annotations to the parameters requires enclosing the parameters in parenthesis. Adding a return type annotation is as simple as following the parameter list with a `->` and the annotation expression.
145 |
146 | **Example**:
147 | ```python
148 | lambda (x: int, y: int) -> int {
149 | if x + y < 10 {
150 | return 3;
151 | } else {
152 | return x - y;
153 | }
154 | }
155 | ```
156 |
157 | #### Classes
158 | You can now do anonymous classes.
159 | The syntax is this:
160 |
161 | class [superclass arguments]
162 |
163 | If superclass arguments are provided, the hidden name of the class will try to be similar to the first superclass defined. Otherwise, it will be similar to 'object'.
164 |
165 | **Example**:
166 | ```ruby
167 | class Animal(ABC) {
168 | @abstractmethod
169 | def speak(self) {}
170 | }
171 |
172 | dog = class(Animal)() {
173 | def speak(self) {
174 | print("woof!");
175 | }
176 | };
177 | ```
178 |
179 | ### Notes
180 | 1. The walrus operator `:=`, new in Python 3.8, is supported.
181 | 2. The positional parameter syntax `/`, new in Python 3.8, is supported.
182 | 3. The match statement, new in Python 3.10, is supported.
183 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | com.raptor
4 | pyjava
5 | 2.0
6 | jar
7 | PyJava
8 |
9 |
10 | 16
11 | 16
12 | --enable-preview
13 | UTF-8
14 | 5.6.0
15 | 4.8
16 |
17 |
18 |
19 |
20 | org.antlr
21 | antlr4
22 | ${antlr.version}
23 |
24 |
25 | org.antlr
26 | antlr4-runtime
27 | ${antlr.version}
28 |
29 |
30 |
31 | org.junit.jupiter
32 | junit-jupiter
33 | ${junit.version}
34 | test
35 |
36 |
37 | com.googlecode.json-simple
38 | json-simple
39 | 1.1.1
40 |
41 |
42 |
43 |
44 |
45 |
46 | maven-compiler-plugin
47 | 3.8.1
48 |
49 | 16
50 |
51 |
52 |
53 |
54 | org.antlr
55 | antlr4-maven-plugin
56 | ${antlr.version}
57 |
58 |
59 | antlr
60 |
61 | antlr4
62 |
63 |
64 |
65 |
66 | true
67 | true
68 |
69 |
70 |
71 | org.codehaus.mojo
72 | build-helper-maven-plugin
73 | 3.2.0
74 |
75 |
76 | add-source
77 | generate-sources
78 |
79 | add-source
80 |
81 |
82 |
83 | target/generated-sources/antlr4
84 |
85 |
86 |
87 |
88 |
89 |
90 | org.apache.maven.plugins
91 | maven-jar-plugin
92 | 3.2.0
93 |
94 |
95 |
96 | true
97 | pyjava.PyJava
98 |
99 |
100 |
101 |
102 |
103 | org.apache.maven.plugins
104 | maven-shade-plugin
105 | 3.2.4
106 |
107 |
108 | package
109 |
110 | shade
111 |
112 |
113 |
114 |
117 |
118 | org.antlr:antlr4-runtime
119 | com.googlecode.json-simple:json-simple
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
--------------------------------------------------------------------------------
/src/main/antlr4/pyjava/parser/PyJavaLexer.g4:
--------------------------------------------------------------------------------
1 | lexer grammar PyJavaLexer;
2 |
3 | channels { ERROR }
4 |
5 | // tokens { FSTRING_START_EXPR, FSTRING_ATOM }
6 |
7 | options {
8 | superClass=PyJavaLexerBase;
9 | }
10 |
11 | BLOCK_COMMENT
12 | : /* {!isInTemplateString()}? */ '#{' .*? '#}' -> channel(HIDDEN)
13 | ;
14 |
15 | LINE_COMMENT
16 | : /* {!isInTemplateString()}? */ '#' (~[{\r\n\f] (~[\r\n\f])*)? -> channel(HIDDEN)
17 | ;
18 |
19 | NUMBER
20 | : INTEGER
21 | | FLOAT_NUMBER
22 | | IMAG_NUMBER
23 | ;
24 |
25 | fragment INTEGER
26 | : DECIMAL_INTEGER
27 | | OCT_INTEGER
28 | | HEX_INTEGER
29 | | BIN_INTEGER
30 | ;
31 |
32 | DEF: 'def';
33 | RETURN: 'return';
34 | RAISE: 'raise';
35 | FROM: 'from';
36 | IMPORT: 'import';
37 | AS: 'as';
38 | GLOBAL: 'global';
39 | NONLOCAL: 'nonlocal';
40 | ASSERT: 'assert';
41 | IF: 'if';
42 | ELIF: 'elif';
43 | ELSE: 'else';
44 | WHILE: 'while';
45 | FOR: 'for';
46 | IN: 'in';
47 | TRY: 'try';
48 | FINALLY: 'finally';
49 | WITH: 'with';
50 | EXCEPT: 'except';
51 | LAMBDA: 'lambda';
52 | OR: 'or';
53 | AND: 'and';
54 | NOT: 'not';
55 | IS: 'is';
56 | NONE: 'None';
57 | TRUE: 'True';
58 | FALSE: 'False';
59 | CLASS: 'class';
60 | YIELD: 'yield';
61 | DEL: 'del';
62 | PASS: 'pass';
63 | CONTINUE: 'continue';
64 | BREAK: 'break';
65 | ASYNC: 'async';
66 | AWAIT: 'await';
67 | MATCH: 'match';
68 | CASE: 'case';
69 |
70 | NAME
71 | : ID_START ID_CONTINUE*
72 | ;
73 |
74 | STRING_LITERAL
75 | : ( [rR] | [uU] | FSTRING_BEGIN )? (SHORT_STRING | LONG_STRING)
76 | ;
77 |
78 | // SINGLE_SHORT_FSTRING_QUOTE
79 | // : FSTRING_BEGIN '\'' {increaseTemplateDepth();} -> pushMode(SINGLE_SHORT_FSTRING_TEMPLATE)
80 | // ;
81 |
82 | // DOUBLE_SHORT_FSTRING_QUOTE
83 | // : FSTRING_BEGIN '"' {increaseTemplateDepth();} -> pushMode(DOUBLE_SHORT_FSTRING_TEMPLATE)
84 | // ;
85 |
86 | // SINGLE_LONG_FSTRING_QUOTE
87 | // : FSTRING_BEGIN '\'\'\'' {increaseTemplateDepth();} -> pushMode(SINGLE_LONG_FSTRING_TEMPLATE)
88 | // ;
89 |
90 | // DOUBLE_LONG_FSTRING_QUOTE
91 | // : FSTRING_BEGIN '"""' {increaseTemplateDepth();} -> pushMode(DOUBLE_LONG_FSTRING_TEMPLATE)
92 | // ;
93 |
94 | fragment FSTRING_BEGIN
95 | : [fF] | ( [fF] [rR] ) | ( [rR] [fF] )
96 | ;
97 |
98 | BYTES_LITERAL
99 | : ( [bB] | ( [bB] [rR] ) | ( [rR] [bB] ) ) (SHORT_BYTES | LONG_BYTES)
100 | ;
101 |
102 | fragment DECIMAL_INTEGER
103 | : NON_ZERO_DIGIT ('_'* DIGITS)?
104 | | '0'+ ('_'+ '0'+)*
105 | ;
106 |
107 | fragment OCT_INTEGER
108 | : '0' [oO] OCT_DIGITS
109 | ;
110 |
111 | fragment HEX_INTEGER
112 | : '0' [xX] HEX_DIGITS
113 | ;
114 |
115 | fragment BIN_INTEGER
116 | : '0' [bB] BIN_DIGITS
117 | ;
118 |
119 | fragment FLOAT_NUMBER
120 | : POINT_FLOAT
121 | | EXPONENT_FLOAT
122 | ;
123 |
124 | fragment IMAG_NUMBER
125 | : (FLOAT_NUMBER | DIGITS) [jJ]
126 | ;
127 |
128 | DOT: '.';
129 | ELLIPSIS: '...';
130 | STAR: '*';
131 | LPAREN: '(' {enterBracket('(');};
132 | RPAREN: ')' {exitBracket(')');};
133 | COMMA: ',';
134 | COLON: ':';
135 | SEMI: ';';
136 | STARSTAR: '**';
137 | EQ: '=';
138 | LBRACK: '[' {enterBracket('[');};
139 | RBRACK: ']' {exitBracket(']');};
140 | BAR: '|';
141 | CARET: '^';
142 | AMP: '&';
143 | LTLT: '<<';
144 | GTGT: '>>';
145 | PLUS: '+';
146 | MINUS: '-';
147 | SLASH: '/';
148 | PER: '%';
149 | TILDE: '~';
150 | SLASHSLASH: '//';
151 | LBRACE: '{' {enterBracket('{');};
152 | // TEMPLATE_RBRACE: {isInTemplateString()}? '}' -> popMode;
153 | RBRACE: '}' {exitBracket('}');};
154 | LT: '<';
155 | GT: '>';
156 | EQEQ: '==';
157 | GTEQ: '>=';
158 | LTEQ: '<=';
159 | LTGT: '<>';
160 | BANGEQ: '!=';
161 | AT: '@';
162 | ARROW: '->';
163 | PLUSEQ: '+=';
164 | MINUSEQ: '-=';
165 | STAREQ: '*=';
166 | SLASHEQ: '/=';
167 | PEREQ: '%=';
168 | ATEQ: '@=';
169 | BAREQ: '|=';
170 | CARETEQ: '^=';
171 | AMPEQ: '&=';
172 | LTLTEQ: '<<=';
173 | GTGTEQ: '>>=';
174 | STARSTAREQ: '**=';
175 | SLASHSLASHEQ: '//=';
176 | COLONEQ: ':=';
177 |
178 | SPACES: [ \t\f]+ -> skip;
179 | NEWLINE: '\r'? '\n' {
180 | if (inCurlyBracketsOrNone()) {
181 | setChannel(HIDDEN);
182 | } else {
183 | skip();
184 | }
185 | };
186 |
187 | UNKNOWN: .;
188 |
189 | // mode SINGLE_SHORT_FSTRING_TEMPLATE;
190 |
191 | // SINGLE_SHORT_QUOTE_INSIDE
192 | // : '\'' {decreaseTemplateDepth();} -> type(SINGLE_SHORT_FSTRING_QUOTE), popMode
193 | // ;
194 |
195 | // SINGLE_SHORT_FSTRING_START_EXPR
196 | // : '{' -> type(FSTRING_START_EXPR), pushMode(DEFAULT_MODE)
197 | // ;
198 |
199 | // SINGLE_SHORT_FSTRING_ATOM
200 | // : (~['{\r\n])+ -> type(FSTRING_ATOM)
201 | // ;
202 |
203 | // mode DOUBLE_SHORT_FSTRING_TEMPLATE;
204 |
205 | // DOUBLE_SHORT_QUOTE_INSIDE
206 | // : '"' {decreaseTemplateDepth();} -> type(DOUBLE_SHORT_FSTRING_QUOTE), popMode
207 | // ;
208 |
209 | // DOUBLE_SHORT_FSTRING_START_EXPR
210 | // : '{' -> type(FSTRING_START_EXPR), pushMode(DEFAULT_MODE)
211 | // ;
212 |
213 | // DOUBLE_SHORT_FSTRING_ATOM
214 | // : (~["{\r\n])+ -> type(FSTRING_ATOM)
215 | // ;
216 |
217 | // mode SINGLE_LONG_FSTRING_TEMPLATE;
218 |
219 | // SINGLE_LONG_QUOTE_INSIDE
220 | // : '\'\'\'' {decreaseTemplateDepth();} -> type(SINGLE_LONG_FSTRING_QUOTE), popMode
221 | // ;
222 |
223 | // SINGLE_LONG_FSTRING_START_EXPR
224 | // : '{' -> type(FSTRING_START_EXPR), pushMode(DEFAULT_MODE)
225 | // ;
226 |
227 | // SINGLE_LONG_FSTRING_ATOM
228 | // : ( '\'\'' ~['{]
229 | // | '\'' ~['{]
230 | // | ~['{])+ -> type(FSTRING_ATOM)
231 | // ;
232 |
233 | // mode DOUBLE_LONG_FSTRING_TEMPLATE;
234 |
235 | // DOUBLE_LONG_QUOTE_INSIDE
236 | // : '"""' {decreaseTemplateDepth();} -> type(DOUBLE_LONG_FSTRING_QUOTE), popMode
237 | // ;
238 |
239 | // DOUBLE_LONG_FSTRING_START_EXPR
240 | // : '{' -> type(FSTRING_START_EXPR), pushMode(DEFAULT_MODE)
241 | // ;
242 |
243 | // DOUBLE_LONG_FSTRING_ATOM
244 | // : ( '""' ~["{]
245 | // | '"' ~["{]
246 | // | ~["{])+ -> type(FSTRING_ATOM)
247 | // ;
248 |
249 |
250 | // Fragment rules
251 |
252 | fragment SHORT_STRING
253 | : '\'' (STRING_ESCAPE_SEQ | ~[\\\r\n\f'])* '\''
254 | | '"' (STRING_ESCAPE_SEQ | ~[\\\r\n\f"])* '"'
255 | ;
256 |
257 | fragment LONG_STRING
258 | : '\'\'\'' (/* {!isInTemplateString()}? */ STRING_ESCAPE_SEQ | ~'\\')*? '\'\'\''
259 | | '"""' (/* {!isInTemplateString()}? */ STRING_ESCAPE_SEQ | ~'\\')*? '"""'
260 | ;
261 |
262 | fragment STRING_ESCAPE_SEQ
263 | : '\\' .
264 | | '\\' NEWLINE
265 | ;
266 |
267 | fragment SHORT_BYTES
268 | : '\'' (SHORT_BYTES_CHAR_NO_SINGLE_QUOTE | BYTES_ESCAPE_SEQ)* '\''
269 | | '"' (SHORT_BYTES_CHAR_NO_DOUBLE_QUOTE | BYTES_ESCAPE_SEQ)* '"'
270 | ;
271 |
272 | fragment LONG_BYTES
273 | : '\'\'\'' (LONG_BYTES_CHAR | BYTES_ESCAPE_SEQ)*? '\'\'\''
274 | | '"""' (LONG_BYTES_CHAR | BYTES_ESCAPE_SEQ)*? '"""'
275 | ;
276 |
277 | fragment SHORT_BYTES_CHAR_NO_SINGLE_QUOTE
278 | : [\u0000-\u0009]
279 | | [\u000B-\u000C]
280 | | [\u000E-\u0026]
281 | | [\u0028-\u005B]
282 | | [\u005D-\u007F]
283 | ;
284 |
285 | fragment SHORT_BYTES_CHAR_NO_DOUBLE_QUOTE
286 | : [\u0000-\u0009]
287 | | [\u000B-\u000C]
288 | | [\u000E-\u0021]
289 | | [\u0023-\u005B]
290 | | [\u005D-\u007F]
291 | ;
292 |
293 | fragment LONG_BYTES_CHAR
294 | : [\u0000-\u005B]
295 | | [\u005D-\u007F]
296 | ;
297 |
298 | fragment BYTES_ESCAPE_SEQ
299 | : '\\' [\u0000-\u007F]
300 | ;
301 |
302 | fragment NON_ZERO_DIGIT
303 | : [1-9]
304 | ;
305 |
306 | fragment DIGIT
307 | : [0-9]
308 | ;
309 |
310 | fragment OCT_DIGIT
311 | : [0-7]
312 | ;
313 |
314 | fragment HEX_DIGIT
315 | : [a-fA-F0-9]
316 | ;
317 |
318 | fragment BIN_DIGIT
319 | : [01]
320 | ;
321 |
322 | fragment DIGITS
323 | : DIGIT+ ('_'+ DIGIT+)*
324 | ;
325 |
326 | fragment OCT_DIGITS
327 | : OCT_DIGIT+ ('_'+ OCT_DIGIT+)*
328 | ;
329 |
330 | fragment HEX_DIGITS
331 | : HEX_DIGIT+ ('_'+ HEX_DIGIT+)*
332 | ;
333 |
334 | fragment BIN_DIGITS
335 | : BIN_DIGIT+ ('_'+ BIN_DIGIT+)*
336 | ;
337 |
338 | fragment POINT_FLOAT
339 | : DIGITS '.' DIGITS?
340 | | '.' DIGITS
341 | ;
342 |
343 | fragment EXPONENT_FLOAT
344 | : (DIGITS | POINT_FLOAT) EXPONENT
345 | ;
346 |
347 | fragment EXPONENT
348 | : [eE] [+-]? DIGITS
349 | ;
350 |
351 | fragment UNICODE_OIDS
352 | : '\u1885'..'\u1886'
353 | | '\u2118'
354 | | '\u212e'
355 | | '\u309b'..'\u309c'
356 | ;
357 |
358 | fragment UNICODE_OIDC
359 | : '\u00b7'
360 | | '\u0387'
361 | | '\u1369'..'\u1371'
362 | | '\u19da'
363 | ;
364 |
365 | fragment ID_START
366 | : '_'
367 | | [\p{L}]
368 | | [\p{Nl}]
369 | // | [\p{Other_ID_Start}]
370 | | UNICODE_OIDS
371 | ;
372 |
373 | fragment ID_CONTINUE
374 | : ID_START
375 | | [\p{Mn}]
376 | | [\p{Mc}]
377 | | [\p{Nd}]
378 | | [\p{Pc}]
379 | // | [\p{Other_ID_Continue}]
380 | | UNICODE_OIDC
381 | ;
--------------------------------------------------------------------------------
/src/main/antlr4/pyjava/parser/PyJavaParser.g4:
--------------------------------------------------------------------------------
1 | parser grammar PyJavaParser;
2 |
3 | options {
4 | tokenVocab=PyJavaLexer;
5 | superClass=PyJavaParserBase;
6 | }
7 |
8 | @header {
9 | import java.util.List;
10 | import java.util.ArrayList;
11 |
12 | import pyjava.PyJavaOptions;
13 | }
14 |
15 | @members {
16 | public PyJavaParser(TokenStream input, PyJavaOptions optionsIn) {
17 | this(input);
18 | options = optionsIn;
19 | }
20 | }
21 |
22 | file
23 | : statement* comments EOF
24 | ;
25 |
26 |
27 | statement
28 | returns [List commentTokens]
29 | @init {
30 | $commentTokens = getPrecedingLineComments();
31 | }
32 | : ';' comment # EmptyStatement
33 | | assignment eos # AssignmentStatement
34 | | starExpressions eos # ExpressionStatement
35 | | 'return' retVal? eos # ReturnStatement
36 | | yieldExpression eos # YieldStatement
37 | | {!options.forceParensInReturnYieldRaise()}?
38 | 'raise' {notLineTerminator()}? expression {notLineTerminator()}? 'from' expression eos # RaiseFromStatement
39 | | {options.forceParensInReturnYieldRaise()}?
40 | 'raise' {notLineTerminator()}? namedExpressionCond {notLineTerminator()}? 'from' namedExpressionCond eos # RaiseFromStatement
41 | | 'raise' retVal? eos # RaiseStatement
42 | | 'import' dottedAsNames eos # ImportStatement
43 | | 'from' importFromName 'import' importFromTargets eos # FromImportStatement
44 | | 'pass' eos # EmptyStatement
45 | | 'del' delTargets eos # DelStatement
46 | | {!options.forceParensInReturnYieldRaise()}?
47 | 'assert' expression (',' expression)? eos # AssertStatement
48 | | {options.forceParensInReturnYieldRaise()}?
49 | 'assert' '(' namedExpression (',' namedExpression)? ','? ')' eos # AssertStatement
50 | | 'break' eos # BreakStatement
51 | | 'continue' eos # ContinueStatement
52 | | 'global' identifier (',' identifier)* eos # GlobalStatement
53 | | 'nonlocal' identifier (',' identifier)* eos # NonLocalStatement
54 | | decorators? funcHeader retType? comment comments STRING_LITERAL? funcBody # FunctionDef
55 | | decorators? classHeader comment comments STRING_LITERAL? classBody # ClassDef
56 | | 'if' namedExpressionCond block elif* elseBlock? # IfStatement
57 | | 'while' namedExpressionCond block elseBlock? # WhileLoop
58 | | 'async'? 'for' forLoopHeader block elseBlock? # ForLoop
59 | | 'async'? 'with' withItems block # WithStatement
60 | | 'try' block finallyBlock # TryFinallyStatement
61 | | 'try' block exceptBlock+ elseBlock? finallyBlock? # TryExceptStatement
62 | | 'match' {notLineTerminator()}? subjectExprCond comment '{' ({lineTerminatorAhead()}? comment)? caseBlock+ '}' # MatchStatement
63 | ;
64 |
65 | retVal
66 | : {options.forceParensInReturnYieldRaise()}? {notLineTerminator()}? '(' starExpressions? ')'
67 | | {!options.forceParensInReturnYieldRaise()}? {notLineTerminator()}? starExpressions
68 | ;
69 |
70 | assignment
71 | : identifier annotation ('=' annotatedRhs)? # VarDeclAssignment
72 | | '(' singleTarget ')' annotation ('=' annotatedRhs)? # AnnotatedAssignment
73 | | singleSubscriptAttributeTarget annotation ('=' annotatedRhs)? # AnnotatedAssignment
74 | | (starTargets '=')+ annotatedRhs # MultipleAssignment
75 | | singleTarget augAssign annotatedRhs # AugAssignment
76 | ;
77 |
78 | augAssign
79 | : '+='
80 | | '-='
81 | | '*='
82 | | '@='
83 | | '/='
84 | | '%='
85 | | '//='
86 | | '&='
87 | | '^='
88 | | '|='
89 | | '<<='
90 | | '>>='
91 | | '**='
92 | ;
93 |
94 | singleTarget
95 | : singleSubscriptAttributeTarget
96 | | identifier
97 | | '(' singleTarget ')'
98 | ;
99 |
100 | singleSubscriptAttributeTarget
101 | : tPrimary '.' identifier
102 | | tPrimary {notLineTerminator()}? '[' slices ']'
103 | ;
104 |
105 | block
106 | : comment '{' ({lineTerminatorAhead()}? comment)? statement* comments '}'
107 | | {options.allowColonSimpleBlocks()}? ':' ({lineTerminatorAhead()}? comment)? {!next(SEMI)}? statement
108 | | {options.allowNoColonSimpleBlocks()}? ({lineTerminatorAhead()}? comment)? statement
109 | ;
110 |
111 | elif
112 | returns [List commentTokens]
113 | @init {
114 | $commentTokens = getPrecedingLineComments();
115 | }
116 | : 'elif' namedExpressionCond block
117 | ;
118 |
119 | elseBlock
120 | returns [List commentTokens]
121 | @init {
122 | $commentTokens = getPrecedingLineComments();
123 | }
124 | : 'else' block
125 | ;
126 |
127 | forLoopHeader
128 | : '(' starTargets 'in' starExpressions ')'
129 | | {!options.forceParensInStatements()}? starTargets 'in' starExpressions
130 | ;
131 |
132 | withItems
133 | : '(' withItem (',' withItem)* ','? ')'
134 | | {!options.forceParensInStatements()}? withItem (',' withItem)*
135 | ;
136 |
137 | withItem
138 | : expression ('as' starTarget)?
139 | ;
140 |
141 | exceptBlock
142 | : 'except' (exceptItem | '(' ')')? block
143 | ;
144 |
145 | exceptItem
146 | : '(' expression ('as' identifier)? ')'
147 | | {!options.forceParensInStatements()}? expression ('as' identifier)?
148 | ;
149 |
150 | finallyBlock
151 | : 'finally' block
152 | ;
153 |
154 | subjectExprCond
155 | : {options.forceParensInStatements()}? namedExpressionCond
156 | | {!options.forceParensInStatements()}? subjectExpr
157 | ;
158 |
159 | subjectExpr
160 | : starNamedExpression ',' starNamedExpressions?
161 | | namedExpression
162 | ;
163 |
164 | caseBlock
165 | returns [List commentTokens]
166 | @init {
167 | $commentTokens = getPrecedingLineComments();
168 | }
169 | : {options.forceParensInReturnYieldRaise()}? 'case' '(' patterns? ')' guard? block
170 | | {!options.forceParensInReturnYieldRaise()}? 'case' patterns guard? block
171 | ;
172 |
173 | guard
174 | : 'if' namedExpressionCond
175 | ;
176 |
177 |
178 | importFromName
179 | : dots? dottedName
180 | | dots
181 | ;
182 |
183 | dots
184 | : ('.' | '...')+
185 | ;
186 |
187 | importFromTargets
188 | : '(' importFromAsNames ','? ')'
189 | | importFromAsNames
190 | | '*'
191 | ;
192 |
193 | importFromAsNames
194 | : importFromAsName (',' importFromAsName)*
195 | ;
196 |
197 | importFromAsName
198 | : name=identifier ('as' alias=identifier)?
199 | ;
200 |
201 | dottedAsNames
202 | : dottedAsName (',' dottedAsName)*
203 | ;
204 |
205 | dottedAsName
206 | : name=dottedName ('as' alias=identifier)?
207 | ;
208 |
209 | dottedName
210 | : identifier ('.' identifier)*
211 | ;
212 |
213 |
214 | delTargets
215 | : {!options.forceParensInReturnYieldRaise()}? delTarget (',' delTarget)*
216 | | '(' (delTarget (',' delTarget)* ','?)? ')'
217 | ;
218 |
219 | delTarget
220 | : tPrimary '.' identifier # PropertyDelTarget
221 | | tPrimary {notLineTerminator()}? '[' slices ']' # SliceDelTarget
222 | | identifier # NameDelTarget
223 | | '(' delTarget ')' # DelTargetParens
224 | | '(' (delTarget ((',' delTarget)+ ','? | ','))? ')' # DelTargetList
225 | | '[' (delTarget (',' delTarget)* ','?)? ']' # DelTargetList
226 | ;
227 |
228 |
229 | tPrimary
230 | : tPrimary '.' identifier # PropertyTPrimary
231 | | tPrimary {notLineTerminator()}? '[' slices ']' # SliceTPrimary
232 | | tPrimary {notLineTerminator()}? genExp # CallWithGenExpTPrimary
233 | | tPrimary {notLineTerminator()}? '(' arguments? ')' # CallTPrimary
234 | | atom # AtomTPrimary
235 | ;
236 |
237 |
238 | classHeader
239 | : 'class' identifier ('(' arguments? ')')?
240 | ;
241 |
242 |
243 | funcHeader
244 | : 'async'? 'def' identifier '(' parameters? ')'
245 | ;
246 |
247 | retType
248 | : '->' expression
249 | ;
250 |
251 | funcBody
252 | : '{' statement* comments '}'
253 | ;
254 |
255 | classBody
256 | : '{' statement* comments '}'
257 | ;
258 |
259 | parameters
260 | : slashNoDefault (',' paramsNoDefault)? (',' paramsWithDefault)? (
261 | ',' starEtc
262 | )? ','?
263 | | slashWithDefault (',' paramsWithDefault) (',' starEtc)? ','?
264 | | paramsNoDefault (',' paramsWithDefault)? (',' starEtc)? ','?
265 | | paramsWithDefault (',' starEtc)? ','?
266 | | starEtc ','?
267 | ;
268 |
269 | slashNoDefault
270 | : paramsNoDefault ',' '/'
271 | ;
272 |
273 | slashWithDefault
274 | : paramNoDefault (',' paramNoDefault)* (',' paramWithDefault)+ ',' '/'
275 | | paramWithDefault (',' paramWithDefault)* ',' '/'
276 | ;
277 |
278 | paramsNoDefault
279 | : paramNoDefault (',' paramNoDefault)*
280 | ;
281 |
282 | paramNoDefault
283 | : identifier annotation?
284 | ;
285 |
286 | paramsWithDefault
287 | : paramWithDefault (',' paramWithDefault)*
288 | ;
289 |
290 | paramWithDefault
291 | : identifier annotation? defaultVal
292 | ;
293 |
294 | paramMaybeDefault
295 | : identifier annotation? defaultVal?
296 | ;
297 |
298 | starEtc
299 | : '*' paramNoDefault (',' paramMaybeDefault)* (',' kwds)?
300 | | '*' (',' paramMaybeDefault)+ (',' kwds)?
301 | | kwds
302 | ;
303 |
304 | kwds
305 | : '**' paramNoDefault
306 | ;
307 |
308 |
309 | decorators
310 | @init {
311 | boolean temp_inDecorator = inDecorator;
312 | inDecorator = true;
313 | }
314 | : decorator+
315 | ;
316 | finally {
317 | inDecorator = temp_inDecorator;
318 | }
319 |
320 | decorator
321 | : '@' namedExpression comment comments
322 | ;
323 |
324 |
325 | patterns
326 | : openSequencePattern
327 | | pattern
328 | ;
329 |
330 | pattern
331 | : asPattern
332 | | orPattern
333 | ;
334 |
335 | asPattern
336 | : orPattern 'as' patternCaptureTarget
337 | ;
338 |
339 | orPattern
340 | : closedPattern ('|' closedPattern)*
341 | ;
342 |
343 | closedPattern
344 | : literalExpr # LiteralPattern
345 | | patternCaptureTarget # CapturePattern
346 | | {next("_")}? NAME # WildcardPattern
347 | | attr # ValuePattern
348 | | '(' pattern ')' # GroupPattern
349 | | '[' maybeSequencePattern? ']' # ListSequencePattern
350 | | '(' openSequencePattern? ')' # TupleSequencePattern
351 | | '{' '}' # MappingPattern
352 | | '{' doubleStarPattern ','? '}' # MappingPattern
353 | | '{' itemsPattern ',' doubleStarPattern ','? '}' # MappingPattern
354 | | '{' itemsPattern ','? '}' # MappingPattern
355 | | nameOrAttr '(' ')' # ClassPattern
356 | | nameOrAttr '(' positionalPatterns ','? ')' # ClassPattern
357 | | nameOrAttr '(' keywordPatterns ','? ')' # ClassPattern
358 | | nameOrAttr '(' positionalPatterns ',' keywordPatterns ','? ')' # ClassPattern
359 | ;
360 |
361 | nameOrAttr
362 | : attr
363 | | identifier
364 | ;
365 |
366 | complexNumber
367 | : signedRealNumber sign imaginaryNumber
368 | ;
369 |
370 | sign
371 | : '+'
372 | | '-'
373 | ;
374 |
375 | signedNumber
376 | : '-'? NUMBER
377 | ;
378 |
379 | signedRealNumber
380 | : '-'? realNumber
381 | ;
382 |
383 | realNumber
384 | : {nextIsRealNumber()}? NUMBER
385 | ;
386 |
387 | imaginaryNumber
388 | : {nextIsImagNumber()}? NUMBER
389 | ;
390 |
391 | attr
392 | : dottedName '.' identifier
393 | ;
394 |
395 | openSequencePattern
396 | : maybeStarPattern ',' maybeSequencePattern?
397 | ;
398 |
399 | maybeSequencePattern
400 | : maybeStarPattern (',' maybeStarPattern)* ','?
401 | ;
402 |
403 | maybeStarPattern
404 | : starPattern
405 | | pattern
406 | ;
407 |
408 | starPattern
409 | : '*' {next("_")}? NAME
410 | | '*' patternCaptureTarget
411 | ;
412 |
413 | itemsPattern
414 | : keyValuePattern (',' keyValuePattern)*
415 | ;
416 |
417 | keyValuePattern
418 | : literalExpr ':' pattern
419 | | attr ':' pattern
420 | ;
421 |
422 | doubleStarPattern
423 | : '**' patternCaptureTarget
424 | ;
425 |
426 | literalExpr
427 | : complexNumber # ComplexLiteralPattern
428 | | signedNumber # NumberLiteralPattern
429 | | strings # StringLiteralPattern
430 | | 'None' # NoneLiteralPattern
431 | | 'True' # TrueLiteralPattern
432 | | 'False' # FalseLiteralPattern
433 | ;
434 |
435 | patternCaptureTarget
436 | : {!next("_")}? identifier {!(next(EQ) || next(DOT) || next(LPAREN))}?
437 | ;
438 |
439 | positionalPatterns
440 | : pattern (',' pattern)*
441 | ;
442 |
443 | keywordPatterns
444 | : keywordPattern (',' keywordPattern)*
445 | ;
446 |
447 | keywordPattern
448 | : identifier '=' pattern
449 | ;
450 |
451 |
452 | starExpressions
453 | : starExpression (',' starExpression)* ','?
454 | ;
455 |
456 | starExpression
457 | : '*' bitwiseOr
458 | | expression
459 | ;
460 |
461 | starNamedExpressions
462 | : starNamedExpression (',' starNamedExpression)* ','?
463 | ;
464 |
465 | starNamedExpression
466 | : '*' bitwiseOr
467 | | namedExpression
468 | ;
469 |
470 |
471 | assignmentExpression
472 | : identifier ':=' expression
473 | ;
474 |
475 | namedExpressionCond
476 | : {options.forceParensInStatements()}? 'not'?
477 | {next(LPAREN)}? atom
478 | | {!options.forceParensInStatements()}? namedExpression
479 | ;
480 |
481 | namedExpression
482 | : assignmentExpression
483 | | expression {!next(COLONEQ)}?
484 | ;
485 |
486 | annotatedRhs
487 | : yieldExpression
488 | | starExpressions
489 | ;
490 |
491 | expressions
492 | : expression (',' expression)* ','?
493 | ;
494 |
495 | expression
496 | : disjunction 'if'
497 | {
498 | boolean temp_inDecorator = inDecorator;
499 | inDecorator = false;
500 | }
501 | disjunction
502 | {
503 | inDecorator = temp_inDecorator;
504 | }
505 | 'else' expression # IfExpression
506 | | disjunction # DisjunctionExpression
507 | | lambdaHeader ':' expression # LambdaExpression
508 | ;
509 |
510 | lambdaHeader
511 | @init {
512 | boolean temp_inDecorator = inDecorator;
513 | inDecorator = false;
514 | }
515 | : 'async'? 'lambda' (lambdaParameters | '(' lambdaParameters ')' | '(' parameters? ')')? retType?
516 | ;
517 | finally {
518 | inDecorator = temp_inDecorator;
519 | }
520 |
521 | lambdaParameters
522 | : lambdaSlashNoDefault (',' lambdaParamsNoDefault)? (
523 | ',' lambdaParamsWithDefault
524 | )? (',' lambdaStarEtc)? ','?
525 | | lambdaSlashWithDefault (',' lambdaParamsWithDefault) (
526 | ',' lambdaStarEtc
527 | )? ','?
528 | | lambdaParamsNoDefault (',' lambdaParamsWithDefault)? (
529 | ',' lambdaStarEtc
530 | )? ','?
531 | | lambdaParamsWithDefault (',' lambdaStarEtc)? ','?
532 | | lambdaStarEtc
533 | ;
534 |
535 | lambdaSlashNoDefault
536 | : lambdaParamsNoDefault ',' '/'
537 | ;
538 |
539 | lambdaSlashWithDefault
540 | : lambdaParamNoDefault (',' lambdaParamNoDefault)* (
541 | ',' lambdaParamWithDefault
542 | )+
543 | | lambdaParamWithDefault (',' lambdaParamWithDefault)*
544 | ;
545 |
546 | lambdaParamsNoDefault
547 | : lambdaParamNoDefault (',' lambdaParamNoDefault)*
548 | ;
549 |
550 | lambdaParamNoDefault
551 | : identifier
552 | ;
553 |
554 | lambdaParamsWithDefault
555 | : lambdaParamWithDefault (',' lambdaParamWithDefault)*
556 | ;
557 |
558 | lambdaParamWithDefault
559 | : identifier defaultVal
560 | ;
561 |
562 | lambdaParamMaybeDefault
563 | : identifier defaultVal?
564 | ;
565 |
566 | lambdaStarEtc
567 | : '*' lambdaParamNoDefault (',' lambdaParamMaybeDefault)* (
568 | ',' lambdaKwds
569 | )?
570 | | '*' (',' lambdaParamMaybeDefault)+ (',' lambdaKwds)?
571 | | lambdaKwds
572 | ;
573 |
574 | lambdaKwds
575 | : '**' lambdaParamNoDefault
576 | ;
577 |
578 |
579 | disjunction
580 | : conjunction ('or' conjunction)*
581 | ;
582 |
583 | conjunction
584 | : inversion ('and' inversion)*
585 | ;
586 |
587 | inversion
588 | : 'not' inversion
589 | | comparison
590 | ;
591 |
592 | comparison
593 | : bitwiseOr compareOpBitwiseOrPair+
594 | | bitwiseOr
595 | ;
596 |
597 | compareOpBitwiseOrPair
598 | : compareOp bitwiseOr
599 | ;
600 |
601 | compareOp
602 | : '=='
603 | | '!='
604 | | '<='
605 | | '<'
606 | | '>='
607 | | '>'
608 | | 'not' 'in'
609 | | 'in'
610 | | 'is' 'not'
611 | | 'is'
612 | ;
613 |
614 | bitwiseOr
615 | : bitwiseOr '|' bitwiseXor
616 | | bitwiseXor
617 | ;
618 |
619 | bitwiseXor
620 | : bitwiseXor '^' bitwiseAnd
621 | | bitwiseAnd
622 | ;
623 |
624 | bitwiseAnd
625 | : bitwiseAnd '&' shiftExpr
626 | | shiftExpr
627 | ;
628 |
629 | shiftExpr
630 | : shiftExpr shiftOp sum
631 | | sum
632 | ;
633 |
634 | shiftOp
635 | : '<<'
636 | | '>>'
637 | ;
638 |
639 | sum
640 | : sum sumOp term
641 | | term
642 | ;
643 |
644 | sumOp
645 | : '+'
646 | | '-'
647 | ;
648 |
649 | term
650 | : term termOp factor
651 | | factor
652 | ;
653 |
654 | termOp
655 | : '*'
656 | | '/'
657 | | '//'
658 | | '%'
659 | | {!inDecorator}? '@'
660 | ;
661 |
662 | factor
663 | : prefixOp factor
664 | | power
665 | ;
666 |
667 | prefixOp
668 | : '+'
669 | | '-'
670 | | '~'
671 | ;
672 |
673 | power
674 | : awaitPrimary '**' factor
675 | | awaitPrimary
676 | ;
677 |
678 | awaitPrimary
679 | : 'await' primary
680 | | primary
681 | ;
682 |
683 | primary
684 | : primary '.' identifier # PropertyPrimary
685 | | primary {notLineTerminator()}? genExp # CallWithGenExpPrimary
686 | | primary {notLineTerminator()}? '(' arguments? ')' # CallPrimary
687 | | primary {notLineTerminator()}? '[' slices ']' # SlicePrimary
688 | | atom # AtomPrimary
689 | ;
690 |
691 | slices
692 | @init {
693 | boolean temp_inDecorator = inDecorator;
694 | inDecorator = false;
695 | }
696 | : slice (',' slice)* ','?
697 | ;
698 | finally {
699 | inDecorator = temp_inDecorator;
700 | }
701 |
702 | slice
703 | : begin=expression? ':' end=expression? (
704 | ':' step=expression?
705 | )?
706 | | namedExpression
707 | ;
708 |
709 | atom
710 | @init {
711 | boolean temp_inDecorator = inDecorator;
712 | inDecorator = false;
713 | }
714 | : identifier # NamedAtom
715 | | 'True' # TrueAtom
716 | | 'False' # FalseAtom
717 | | 'None' # NoneAtom
718 | | strings # StringsAtom
719 | | NUMBER # NumberAtom
720 | | '(' yieldExpression ')' # GroupAtom
721 | | '(' namedExpression ')' # GroupAtom
722 | | '(' (starNamedExpressions {((TupleAtomContext)$ctx).starNamedExpressions().COMMA(0) != null}?)? ')' # TupleAtom
723 | | genExp # GenExpAtom
724 | | '[' starNamedExpressions? ']' # ListAtom
725 | | '[' namedExpression forIfClauses ']' # ListCompAtom
726 | | '{' doubleStarredKVPairs? '}' # DictAtom
727 | | '{' kVPair forIfClauses '}' # DictCompAtom
728 | | '...' # EllipsisAtom
729 | | 'class' ('(' superClassArgs=arguments? ')')? (genExp | '(' constructorArgs=arguments? ')') classBody # AnonymousClassExpression
730 | | lambdaHeader funcBody # MultiLineLambdaExpression
731 | ;
732 | finally {
733 | inDecorator = temp_inDecorator;
734 | }
735 |
736 | doubleStarredKVPairs
737 | : doubleStarredKVPair (',' doubleStarredKVPair)* ','?
738 | ;
739 |
740 | doubleStarredKVPair
741 | : '**' bitwiseOr
742 | | kVPair
743 | ;
744 |
745 | kVPair
746 | : key=expression ':' value=expression
747 | ;
748 |
749 | forIfClauses
750 | : forIfClause+
751 | ;
752 |
753 | forIfClause
754 | : 'async'? 'for' starTargets 'in' disjunction filter*
755 | ;
756 |
757 | filter
758 | : 'if' disjunction
759 | ;
760 |
761 | genExp
762 | @init {
763 | boolean temp_inDecorator = inDecorator;
764 | inDecorator = false;
765 | }
766 | : '(' assignmentExpression forIfClauses ')'
767 | | '(' expression forIfClauses ')'
768 | ;
769 | finally {
770 | inDecorator = temp_inDecorator;
771 | }
772 |
773 | yieldExpression
774 | : 'yield' {notLineTerminator()}? 'from'
775 | ( {!options.forceParensInReturnYieldRaise()}?
776 | expression
777 | | {options.forceParensInReturnYieldRaise()}?
778 | {next(LPAREN)}? atom
779 | )
780 | | 'yield' retVal?
781 | ;
782 |
783 |
784 | arguments
785 | @init {
786 | boolean temp_inDecorator = inDecorator;
787 | inDecorator = false;
788 | }
789 | : argument (',' argument)* (',' kwargs)? ','?
790 | | kwargs ','?
791 | ;
792 | finally {
793 | inDecorator = temp_inDecorator;
794 | }
795 |
796 | argument
797 | : starredExpression
798 | | assignmentExpression
799 | | expression
800 | ;
801 |
802 | starredExpression
803 | : '*' expression
804 | ;
805 |
806 | kwargs
807 | : kwargOrStarred (',' kwargOrStarred)* (
808 | ',' kwargOrDoubleStarred
809 | )*
810 | | kwargOrDoubleStarred (',' kwargOrDoubleStarred)*
811 | ;
812 |
813 | kwargOrStarred
814 | : identifier '=' expression
815 | | starredExpression
816 | ;
817 |
818 |
819 | kwargOrDoubleStarred
820 | : identifier '=' expression
821 | | '**' expression
822 | ;
823 |
824 |
825 | starTargets
826 | : starTarget (',' starTarget)* ','?
827 | ;
828 |
829 | starTarget
830 | : '*' targetWithStarAtom
831 | | targetWithStarAtom
832 | ;
833 |
834 | targetWithStarAtom
835 | : tPrimary '.' identifier # PropertyTargetWithStarAtom
836 | | tPrimary {notLineTerminator()}? '[' slices ']' # SliceTargetWithStarAtom
837 | | starAtom # TargetStarAtom
838 | ;
839 |
840 | starAtom
841 | : identifier # NamedStarAtom
842 | | '(' targetWithStarAtom ')' # StarAtomGroup
843 | | '(' (starTargets {((TupleStarAtomContext)$ctx).starTargets().COMMA(0) != null}?)? ')' # TupleStarAtom
844 | | '[' starTargets? ']' # ListStarAtom
845 | ;
846 |
847 |
848 | strings
849 | : (STRING_LITERAL | BYTES_LITERAL)+
850 | ;
851 |
852 |
853 | annotation
854 | : ':' expression
855 | ;
856 |
857 | defaultVal
858 | : '=' expression
859 | ;
860 |
861 | identifier
862 | : NAME
863 | | 'match'
864 | | 'case'
865 | ;
866 |
867 | comment
868 | returns [Token commentToken]
869 | : {$commentToken = getFirstPrecedingComment();}
870 | ;
871 |
872 | comments
873 | returns [List commentTokens]
874 | : {$commentTokens = getPrecedingLineComments();}
875 | ;
876 |
877 | eos
878 | : ';' comment
879 | | {!options.requireSemicolons()}?
880 | comment
881 | ( EOF
882 | | {lineTerminatorAhead()}?
883 | | {closeBrace()}?
884 | // | {options.forceParensInReturnYieldRaise()}?
885 | //| {if(true) throw new FailedPredicateException(this, "false", "expected semicolon or end of statement");}
886 | )
887 | | {options.requireSemicolons()}? {if(true) throw new FailedPredicateException(this, "false", "expected semicolon");} /*{false}?*/
888 | ;
--------------------------------------------------------------------------------
/src/main/java/pyjava/PyJava.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import java.io.IOException;
4 | import java.nio.charset.StandardCharsets;
5 | import java.nio.file.*;
6 | import java.nio.file.attribute.BasicFileAttributes;
7 | import java.util.ArrayList;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.regex.Pattern;
11 |
12 | import org.antlr.v4.runtime.BailErrorStrategy;
13 | import org.antlr.v4.runtime.CharStreams;
14 | import org.antlr.v4.runtime.CommonTokenStream;
15 | import org.json.simple.parser.JSONParser;
16 |
17 | import pyjava.parser.PyJavaLexer;
18 | import pyjava.parser.PyJavaParser;
19 | import pyjava.tree.LazyAppendable.AppendFunction;
20 | import pyjava.tree.Transpiler;
21 |
22 | public class PyJava {
23 | private static final Pattern ESCAPE_CHARS_REGEX = Pattern.compile("\\[|\\]|\\\\");
24 | private static final Pattern SPECIAL_CHARS_REGEX = Pattern.compile("[*?]");
25 |
26 | public static void main(String[] args) throws Exception {
27 | final var fs = FileSystems.getDefault();
28 |
29 | Path configFile = null;
30 | Path outputDir = null;
31 | var optionsBuilder = PyJavaOptions.builder();
32 | var inputs = new ArrayList();
33 | var include = new ArrayList();
34 | var exclude = new ArrayList();
35 |
36 | parseArgs: {
37 | for (int i = 0; i < args.length; i++) {
38 | String arg = args[i];
39 | matchArg:
40 | switch (arg) {
41 | case "--config", "-c" -> {
42 | if (configFile != null) {
43 | error("Error: duplicate argument --config");
44 | return;
45 | }
46 | i++;
47 | if (i == args.length) {
48 | error("Error: missing path after " + arg);
49 | return;
50 | }
51 | configFile = fs.getPath(args[i]);
52 | }
53 | case "--output", "-o" -> {
54 | if (outputDir != null) {
55 | error("Error: duplicate argument --output");
56 | return;
57 | }
58 | i++;
59 | if (i == args.length) {
60 | error("Error: missing path after " + arg);
61 | return;
62 | }
63 | outputDir = fs.getPath(args[i]);
64 | }
65 | case "--help", "-help", "-h", "--?", "-?", "/?" -> {
66 | printHelp();
67 | return;
68 | }
69 | case "--" -> {
70 | break parseArgs;
71 | }
72 | default -> {
73 | for (var option : new String[] {"--config=", "-c"}) {
74 | if (arg.startsWith(option)) {
75 | if (configFile != null) {
76 | error("Error: duplicate argument --config");
77 | return;
78 | }
79 | configFile = fs.getPath(arg.substring(option.length()));
80 | break matchArg;
81 | }
82 | }
83 | for (var option : new String[] {"--output=", "-o"}) {
84 | if (arg.startsWith(option)) {
85 | if (outputDir != null) {
86 | error("Error: duplicate argument --output");
87 | return;
88 | }
89 | outputDir = fs.getPath(arg.substring(option.length()));
90 | break matchArg;
91 | }
92 | }
93 | if (arg.startsWith("-")) {
94 | error("Error: unknown option "+arg);
95 | return;
96 | }
97 | if (SPECIAL_CHARS_REGEX.matcher(arg).find()) {
98 | include.add(fs.getPathMatcher(getGlob(arg)));
99 | } else {
100 | var path = fs.getPath(arg).normalize();
101 | if (!Files.exists(path)) {
102 | error("Error: the system cannot find the path specified: "+arg);
103 | return;
104 | }
105 | boolean duplicate = false;
106 | for (var oldInput : inputs) {
107 | if (Files.isSameFile(oldInput, path)) {
108 | duplicate = true;
109 | }
110 | }
111 | if (!duplicate) {
112 | inputs.add(path);
113 | }
114 | }
115 | }
116 | }
117 | }
118 | } /* parseArgs */
119 |
120 | if (outputDir != null) {
121 | if (!Files.exists(outputDir)) {
122 | Files.createDirectories(outputDir);
123 | } else if (!Files.isDirectory(outputDir)) {
124 | error("Error: not a directory: "+outputDir);
125 | return;
126 | }
127 | } else {
128 | outputDir = fs.getPath("./");
129 | }
130 |
131 | if (configFile == null) {
132 | configFile = fs.getPath("pyjavaconfig.json");
133 | if (!Files.exists(configFile)) {
134 | configFile = null;
135 | } else if (!Files.isRegularFile(configFile)) {
136 | error("Error: not a file: "+configFile);
137 | return;
138 | }
139 | } else {
140 | if (!Files.exists(configFile)) {
141 | error("Error: the system cannot find the path specified: "+configFile);
142 | return;
143 | }
144 | if (!Files.isRegularFile(configFile)) {
145 | error("Error: not a file: "+configFile);
146 | return;
147 | }
148 | }
149 | if (configFile != null) {
150 | var parser = new JSONParser();
151 | Object parsedJSON;
152 | try (var reader = Files.newBufferedReader(configFile)) {
153 | parsedJSON = parser.parse(reader);
154 | }
155 | if (parsedJSON instanceof Map,?> map) {
156 | @SuppressWarnings("unchecked")
157 | var jsonObj = (Map)map;
158 | if (jsonObj.containsKey("requireSemicolons")) {
159 | optionsBuilder.requireSemicolons(getBoolean(jsonObj, "requireSemicolons"));
160 | }
161 | if (jsonObj.containsKey("allowColonSimpleBlocks")) {
162 | optionsBuilder.allowColonSimpleBlocks(getBoolean(jsonObj, "allowColonSimpleBlocks"));
163 | }
164 | if (jsonObj.containsKey("allowNoColonSimpleBlocks")) {
165 | optionsBuilder.allowNoColonSimpleBlocks(getBoolean(jsonObj, "allowNoColonSimpleBlocks"));
166 | }
167 | if (jsonObj.containsKey("forceParensInStatements")) {
168 | optionsBuilder.forceParensInStatements(getBoolean(jsonObj, "forceParensInStatements"));
169 | }
170 | if (jsonObj.containsKey("forceParensInReturnYieldRaise")) {
171 | optionsBuilder.forceParensInReturnYieldRaise(getBoolean(jsonObj, "forceParensInReturnYieldRaise"));
172 | }
173 | if (jsonObj.containsKey("files")) {
174 | var files = getObject(jsonObj, "files");
175 | if (files.containsKey("include")) {
176 | for (var glob : getStringArray(files, "include")) {
177 | include.add(fs.getPathMatcher(getGlob(glob)));
178 | }
179 | }
180 | if (files.containsKey("exclude")) {
181 | for (var glob : getStringArray(files, "exclude")) {
182 | exclude.add(fs.getPathMatcher(getGlob(glob)));
183 | }
184 | }
185 | }
186 | } else {
187 | error("Error: invalid config file: expected top-level JSON to be an object");
188 | return;
189 | }
190 | } else if (inputs.isEmpty() && include.isEmpty() && exclude.isEmpty()) {
191 | printHelp();
192 | return;
193 | }
194 |
195 | if (inputs.isEmpty()) {
196 | inputs.add(fs.getPath("./"));
197 | }
198 | if (include.isEmpty()) {
199 | include.add(fs.getPathMatcher("glob:**.pyj"));
200 | }
201 |
202 | final var options = optionsBuilder.build();
203 |
204 | class Visitor extends SimpleFileVisitor {
205 | private final Path outputDir;
206 | private final Path parentDir;
207 |
208 | public Visitor(Path outputDir, Path parentDir) {
209 | this.outputDir = outputDir;
210 | this.parentDir = parentDir.toAbsolutePath();
211 | }
212 |
213 | @Override
214 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
215 | for (var excludeMatcher : exclude) {
216 | if (excludeMatcher.matches(dir)) {
217 | return FileVisitResult.SKIP_SUBTREE;
218 | }
219 | }
220 | return FileVisitResult.CONTINUE;
221 | }
222 |
223 | @Override
224 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
225 | for (var includeMatcher : include) {
226 | if (includeMatcher.matches(file)) {
227 | for (var excludeMatcher : exclude) {
228 | if (excludeMatcher.matches(file)) {
229 | return FileVisitResult.CONTINUE;
230 | }
231 | }
232 | String name = file.getFileName().toString();
233 | int i = name.indexOf('.');
234 | if (i == -1) {
235 | name += ".py";
236 | } else {
237 | name = name.substring(0, i) + ".py";
238 | }
239 | Path outputFile = outputDir.resolve(parentDir.relativize(file.toAbsolutePath()).resolveSibling(name));
240 | processFile(file, outputFile, options);
241 | return FileVisitResult.CONTINUE;
242 | }
243 | }
244 | return FileVisitResult.CONTINUE;
245 | }
246 |
247 | @Override
248 | public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
249 | return FileVisitResult.CONTINUE;
250 | }
251 | };
252 | final var noParentDirVisitor = new Visitor(outputDir, fs.getPath(""));
253 |
254 | for (var input : inputs) {
255 | if (Files.isDirectory(input)) {
256 | Files.walkFileTree(input, new Visitor(outputDir, input.normalize()));
257 | } else {
258 | noParentDirVisitor.visitFile(input, null);
259 | }
260 | }
261 | }
262 |
263 | private static void processFile(Path input, Path output, PyJavaOptions options) {
264 | PyJavaParser.FileContext file;
265 | try {
266 | var source = CharStreams.fromPath(input);
267 | var lexer = new PyJavaLexer(source);
268 | var tokens = new CommonTokenStream(lexer);
269 | var parser = new PyJavaParser(tokens, options);
270 | parser.setErrorHandler(new BailErrorStrategy());
271 | file = parser.file();
272 | } catch (Exception e) {
273 | System.err.println("Failed to process file "+input+':');
274 | e.printStackTrace(System.err);
275 | return;
276 | }
277 | var transpiler = new Transpiler();
278 | try {
279 | file.accept(transpiler);
280 | } catch (Exception e) {
281 | System.err.println("Failed to transpile file "+input+':');
282 | e.printStackTrace(System.out);
283 | return;
284 | }
285 | try {
286 | Files.createDirectories(output.getParent());
287 | try (var writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) {
288 | transpiler.appendTo(AppendFunction.wrap(writer));
289 | }
290 | } catch (Exception e) {
291 | System.err.println("Failed to write to file "+output+':');
292 | e.printStackTrace(System.err);
293 | return;
294 | }
295 | }
296 |
297 | private static void error(String msg) {
298 | System.err.println(msg);
299 | System.exit(1);
300 | }
301 |
302 | private static void printHelp() {
303 | System.out.print("""
304 | java -jar PyJava.jar [OPTIONS AND INPUTS...] [--] INPUTS...
305 |
306 | OPTIONS:
307 | --config FILE, -c FILE The config file to use. Default is "pyjavaconfig.json".
308 | --output DIR, -o DIR Output directory to use. Folder structure is kept intact. Default is ".".
309 | -- Everything after this will be treated as an input.
310 |
311 | INPUTS A list of files/glob patterns to run over. Default is "**.pyj".
312 | """);
313 | System.exit(0);
314 | }
315 |
316 | private static String getGlob(String arg) {
317 | return ESCAPE_CHARS_REGEX.matcher(arg).replaceAll("\\\\$0");
318 | }
319 |
320 | private static boolean getBoolean(Map jsonObj, String key) {
321 | var obj = jsonObj.get(key);
322 | if (obj instanceof Boolean b) {
323 | return b;
324 | }
325 | error("Error: invalid config file: expected key "+key+" to be a boolean");
326 | return false;
327 | }
328 |
329 | @SuppressWarnings("unchecked")
330 | private static Map getObject(Map jsonObj, String key) {
331 | var obj = jsonObj.get(key);
332 | if (obj instanceof Map,?>) {
333 | return (Map)obj;
334 | }
335 | error("Error: invalid config file: expected key "+key+" to be an object");
336 | return null;
337 | }
338 |
339 | @SuppressWarnings("unchecked")
340 | private static List getStringArray(Map jsonObj, String key) {
341 | var obj = jsonObj.get(key);
342 | if (obj instanceof List> arr) {
343 | if (arr.stream().allMatch(String.class::isInstance)) {
344 | return (List)arr;
345 | }
346 | }
347 | error("Error: invalid config file: expected key "+key+" to be a string array");
348 | return null;
349 | }
350 | }
351 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/PyJavaOptions.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | public record PyJavaOptions(
4 | boolean requireSemicolons,
5 | boolean allowColonSimpleBlocks,
6 | boolean allowNoColonSimpleBlocks,
7 | boolean forceParensInStatements,
8 | boolean forceParensInReturnYieldRaise
9 | ) {
10 | public static final boolean DEFAULT_REQUIRE_SEMICOLONS = false;
11 | public static final boolean DEFAULT_ALLOW_COLON_SIMPLE_BLOCKS = true;
12 | public static final boolean DEFAULT_ALLOW_NO_COLON_SIMPLE_BLOCKS = true;
13 | public static final boolean DEFAULT_FORCE_PARENS_IN_STATEMENTS = false;
14 | public static final boolean DEFAULT_FORCE_PARENS_IN_RETURN_YIELD_RAISE = false;
15 |
16 | public PyJavaOptions() {
17 | this(
18 | DEFAULT_REQUIRE_SEMICOLONS,
19 | DEFAULT_ALLOW_COLON_SIMPLE_BLOCKS,
20 | DEFAULT_ALLOW_NO_COLON_SIMPLE_BLOCKS,
21 | DEFAULT_FORCE_PARENS_IN_STATEMENTS,
22 | DEFAULT_FORCE_PARENS_IN_RETURN_YIELD_RAISE
23 | );
24 | }
25 |
26 | public Builder toBuilder() {
27 | var b = new Builder();
28 | b.requireSemicolons = requireSemicolons;
29 | b.allowColonSimpleBlocks = allowColonSimpleBlocks;
30 | b.allowNoColonSimpleBlocks = allowNoColonSimpleBlocks;
31 | b.forceParensInStatements = forceParensInStatements;
32 | b.forceParensInReturnYieldRaise = forceParensInReturnYieldRaise;
33 | return b;
34 | }
35 |
36 | public static Builder builder() {
37 | return new Builder();
38 | }
39 |
40 | public static class Builder {
41 | private boolean requireSemicolons = DEFAULT_REQUIRE_SEMICOLONS;
42 | private boolean allowColonSimpleBlocks = DEFAULT_ALLOW_COLON_SIMPLE_BLOCKS;
43 | private boolean allowNoColonSimpleBlocks = DEFAULT_ALLOW_NO_COLON_SIMPLE_BLOCKS;
44 | private boolean forceParensInStatements = DEFAULT_FORCE_PARENS_IN_STATEMENTS;
45 | private boolean forceParensInReturnYieldRaise = DEFAULT_FORCE_PARENS_IN_RETURN_YIELD_RAISE;
46 |
47 | public Builder requireSemicolons(boolean requireSemicolons) {
48 | this.requireSemicolons = requireSemicolons;
49 | return this;
50 | }
51 |
52 | public Builder allowColonSimpleBlocks(boolean allowColonSimpleBlocks) {
53 | this.allowColonSimpleBlocks = allowColonSimpleBlocks;
54 | return this;
55 | }
56 |
57 | public Builder allowNoColonSimpleBlocks(boolean allowNoColonSimpleBlocks) {
58 | this.allowNoColonSimpleBlocks = allowNoColonSimpleBlocks;
59 | return this;
60 | }
61 |
62 | public Builder forceParensInStatements(boolean forceParensInStatements) {
63 | this.forceParensInStatements = forceParensInStatements;
64 | return this;
65 | }
66 |
67 | public Builder forceParensInReturnYieldRaise(boolean forceParensInReturnYieldRaise) {
68 | this.forceParensInReturnYieldRaise = forceParensInReturnYieldRaise;
69 | return this;
70 | }
71 |
72 | public PyJavaOptions build() {
73 | return new PyJavaOptions(
74 | requireSemicolons,
75 | allowColonSimpleBlocks,
76 | allowNoColonSimpleBlocks,
77 | forceParensInStatements,
78 | forceParensInReturnYieldRaise
79 | );
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/parser/PyJavaLexerBase.java:
--------------------------------------------------------------------------------
1 | package pyjava.parser;
2 |
3 | import java.util.ArrayDeque;
4 |
5 | import org.antlr.v4.runtime.CharStream;
6 | import org.antlr.v4.runtime.Lexer;
7 | import org.antlr.v4.runtime.Token;
8 |
9 | public abstract class PyJavaLexerBase extends Lexer {
10 | public PyJavaLexerBase() {}
11 |
12 | public PyJavaLexerBase(CharStream input) {
13 | super(input);
14 | }
15 |
16 | private Token lastToken;
17 |
18 | // private int templateDepth = 0;
19 |
20 | protected boolean isStartOfFile() {
21 | return lastToken == null;
22 | }
23 |
24 | // protected boolean isInTemplateString() {
25 | // return templateDepth > 0;
26 | // }
27 |
28 | @Override
29 | public Token nextToken() {
30 | Token next = super.nextToken();
31 |
32 | if (next.getChannel() == Token.DEFAULT_CHANNEL) {
33 | // Keep track of the last token on the default channel.
34 | lastToken = next;
35 | }
36 |
37 | return next;
38 | }
39 |
40 | // protected void increaseTemplateDepth() {
41 | // templateDepth++;
42 | // }
43 |
44 | // protected void decreaseTemplateDepth() {
45 | // templateDepth--;
46 | // }
47 |
48 | protected static enum BracketType {
49 | PAREN('(', ')'), SQUARE('[', ']'), CURLY('{', '}'), ANGLE('<', '>');
50 |
51 | public final char openChar, closeChar;
52 |
53 | private BracketType(char openChar, char closeChar) {
54 | this.openChar = openChar;
55 | this.closeChar = closeChar;
56 | }
57 |
58 | public static BracketType fromOpenChar(char openChar) {
59 | return switch (openChar) {
60 | case '(' -> PAREN;
61 | case '[' -> SQUARE;
62 | case '{' -> CURLY;
63 | case '<' -> ANGLE;
64 | default -> throw new IllegalArgumentException("Unknown bracket open char: '"+openChar+"'");
65 | };
66 | }
67 |
68 | public static BracketType fromCloseChar(char closeChar) {
69 | return switch (closeChar) {
70 | case ')' -> PAREN;
71 | case ']' -> SQUARE;
72 | case '}' -> CURLY;
73 | case '>' -> ANGLE;
74 | default -> throw new IllegalArgumentException("Unknown bracket close char: '"+closeChar+"'");
75 | };
76 | }
77 | }
78 |
79 | protected final ArrayDeque brackets = new ArrayDeque<>();
80 |
81 | protected boolean inBrackets() {
82 | return !brackets.isEmpty();
83 | }
84 |
85 | protected boolean inBrackets(BracketType type) {
86 | return !brackets.isEmpty() && brackets.peek() == type;
87 | }
88 |
89 | protected boolean inParens() {
90 | return inBrackets(BracketType.PAREN);
91 | }
92 |
93 | protected boolean inSquareBrackets() {
94 | return inBrackets(BracketType.SQUARE);
95 | }
96 |
97 | protected boolean inCurlyBrackets() {
98 | return inBrackets(BracketType.CURLY);
99 | }
100 |
101 | protected boolean inAngleBrackets() {
102 | return inBrackets(BracketType.ANGLE);
103 | }
104 |
105 | protected boolean inParensOrSquareBrackets() {
106 | return !brackets.isEmpty() && switch (brackets.peek()) { case SQUARE, PAREN -> true; default -> false; };
107 | }
108 |
109 | protected boolean inCurlyBracketsOrNone() {
110 | return inCurlyBrackets() || brackets.isEmpty();
111 | }
112 |
113 | protected void enterBracket(char openChar) {
114 | brackets.push(BracketType.fromOpenChar(openChar));
115 | }
116 |
117 | protected void exitBracket(char closeChar) {
118 | var bracket = BracketType.fromCloseChar(closeChar);
119 | if (!brackets.isEmpty() && brackets.peek() == bracket) {
120 | brackets.pop();
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/parser/PyJavaParserBase.java:
--------------------------------------------------------------------------------
1 | package pyjava.parser;
2 |
3 | import static pyjava.parser.PyJavaLexer.*;
4 |
5 | import java.util.ArrayDeque;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 | import java.util.Objects;
9 |
10 | import org.antlr.v4.runtime.Lexer;
11 | import org.antlr.v4.runtime.Parser;
12 | import org.antlr.v4.runtime.Token;
13 | import org.antlr.v4.runtime.TokenStream;
14 |
15 | import pyjava.PyJavaOptions;
16 |
17 | public abstract class PyJavaParserBase extends Parser {
18 | protected PyJavaOptions options;
19 | protected boolean inDecorator;
20 |
21 | public PyJavaParserBase(TokenStream input) {
22 | super(input);
23 | options = new PyJavaOptions();
24 | }
25 |
26 | public PyJavaParserBase(TokenStream input, PyJavaOptions optionsIn) {
27 | super(input);
28 | options = Objects.requireNonNullElseGet(optionsIn, PyJavaOptions::new);
29 | }
30 |
31 | public void setOptions(PyJavaOptions options) {
32 | this.options = Objects.requireNonNull(options);
33 | }
34 |
35 | protected boolean prev(String str) {
36 | return _input.LT(-1).getText().equals(str);
37 | }
38 |
39 | protected boolean prev(final int type) {
40 | return _input.LA(-1) == type;
41 | }
42 |
43 | protected boolean next(String str) {
44 | return _input.LT(1).getText().equals(str);
45 | }
46 |
47 | protected boolean next(final int type) {
48 | return _input.LA(1) == type;
49 | }
50 |
51 | protected boolean notLineTerminator() {
52 | return options.requireSemicolons() || !here(NEWLINE);
53 | }
54 |
55 | protected boolean closeBrace() {
56 | return _input.LT(1).getType() == RBRACE;
57 | }
58 |
59 | protected boolean nextIsRealNumber() {
60 | Token tok = _input.LT(1);
61 | if (tok.getType() == NUMBER) {
62 | String text = tok.getText();
63 | return switch (text.charAt(text.length() - 1)) {
64 | case 'j', 'J' -> false;
65 | default -> true;
66 | };
67 | }
68 | return false;
69 | }
70 |
71 | protected boolean nextIsImagNumber() {
72 | Token tok = _input.LT(1);
73 | if (tok.getType() == NUMBER) {
74 | String text = tok.getText();
75 | return switch (text.charAt(text.length() - 1)) {
76 | case 'j', 'J' -> true;
77 | default -> false;
78 | };
79 | }
80 | return false;
81 | }
82 |
83 | public boolean isCommentToken(Token token) {
84 | if (token.getChannel() == Lexer.HIDDEN) {
85 | switch (token.getType()) {
86 | case BLOCK_COMMENT, LINE_COMMENT:
87 | return true;
88 | }
89 | }
90 | return false;
91 | }
92 |
93 | /**
94 | * Gets the comment token at the current index of the parser's
95 | * token stream if there is one, otherwise returns {@code null}.
96 | * @return the hidden comment token or {@code null}.
97 | */
98 | protected Token getFirstPrecedingComment() {
99 | // Get the token ahead of the current index.
100 | int possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 1;
101 | if (possibleIndexEosToken < 0) return null;
102 | Token ahead = _input.get(possibleIndexEosToken);
103 |
104 | Token lastCommentToken = null;
105 | loop: while (ahead.getChannel() == Lexer.HIDDEN) {
106 | switch (ahead.getType()) {
107 | case BLOCK_COMMENT, LINE_COMMENT -> {
108 | lastCommentToken = ahead;
109 | }
110 | case NEWLINE -> {
111 | lastCommentToken = null;
112 | }
113 | default -> {
114 | break loop;
115 | }
116 | }
117 | if (--possibleIndexEosToken < 0) break;
118 | ahead = _input.get(possibleIndexEosToken);
119 | }
120 |
121 | return lastCommentToken;
122 | }
123 |
124 | /**
125 | * Gets all comment tokens starting at the current index of the parser's
126 | * token stream.
127 | * @return a list of the comment tokens or an empty list if there were none.
128 | */
129 | protected List getPrecedingLineComments() {
130 | // Get the token ahead of the current index.
131 | int possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 1;
132 | if (possibleIndexEosToken < 0) return List.of();
133 | Token ahead = _input.get(possibleIndexEosToken);
134 |
135 | var commentTokens = new LinkedList();
136 | boolean addedCommentLast = false;
137 | loop: while (ahead.getChannel() == Lexer.HIDDEN) {
138 | switch (ahead.getType()) {
139 | case BLOCK_COMMENT, LINE_COMMENT -> {
140 | commentTokens.addFirst(ahead);
141 | addedCommentLast = true;
142 | }
143 | case NEWLINE -> {
144 | addedCommentLast = false;
145 | }
146 | default -> {
147 | break loop;
148 | }
149 | }
150 | if (--possibleIndexEosToken < 0) {
151 | addedCommentLast = false;
152 | break;
153 | }
154 | ahead = _input.get(possibleIndexEosToken);
155 | }
156 | if (addedCommentLast) {
157 | commentTokens.removeFirst();
158 | }
159 |
160 | return commentTokens;
161 | }
162 |
163 | /**
164 | * Returns {@code true} if on the current index of the parser's
165 | * token stream a token of the given {@code type} exists on the
166 | * {@code HIDDEN} channel.
167 | *
168 | * @param type
169 | * the type of the token on the {@code HIDDEN} channel
170 | * to check.
171 | *
172 | * @return {@code true} if there's a hidden token here.
173 | */
174 | private boolean here(final int type) {
175 | // Get the token ahead of the current index.
176 | int possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 1;
177 | if (possibleIndexEosToken < 0) return false;
178 | Token ahead = _input.get(possibleIndexEosToken);
179 |
180 | // Check if the token resides on the HIDDEN channel and if it's of the
181 | // provided type.
182 | return ahead.getChannel() == Lexer.HIDDEN && ahead.getType() == type;
183 | }
184 |
185 | /**
186 | * Returns {@code true} iff on the current index of the parser's
187 | * token stream a token exists on the {@code HIDDEN} channel which
188 | * either is a line terminator, or is a multi line comment that
189 | * contains a line terminator.
190 | *
191 | * @return {@code true} iff on the current index of the parser's
192 | * token stream a token exists on the {@code HIDDEN} channel which
193 | * either is a line terminator, or is a multi line comment that
194 | * contains a line terminator.
195 | */
196 | protected boolean lineTerminatorAhead() {
197 | // Get the token ahead of the current index.
198 | int possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 1;
199 | if (possibleIndexEosToken < 0) return false;
200 | Token ahead = _input.get(possibleIndexEosToken);
201 |
202 | if (ahead.getChannel() != Lexer.HIDDEN) {
203 | // We're only interested in tokens on the HIDDEN channel.
204 | return false;
205 | }
206 |
207 | if (ahead.getType() == NEWLINE) {
208 | // There is definitely a line terminator ahead.
209 | return true;
210 | }
211 |
212 | if (ahead.getType() == SPACES) {
213 | // Get the token ahead of the current whitespaces.
214 | possibleIndexEosToken = this.getCurrentToken().getTokenIndex() - 2;
215 | ahead = _input.get(possibleIndexEosToken);
216 | }
217 |
218 | // Get the token's text and type.
219 | String text = ahead.getText();
220 | int type = ahead.getType();
221 |
222 | // Check if the token is, or contains a line terminator.
223 | return type == BLOCK_COMMENT && (text.contains("\r") || text.contains("\n"))
224 | || type == NEWLINE;
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/tree/GetGroupAtom.java:
--------------------------------------------------------------------------------
1 | package pyjava.tree;
2 |
3 | import org.antlr.v4.runtime.tree.ParseTree;
4 | import org.antlr.v4.runtime.tree.RuleNode;
5 |
6 | import pyjava.parser.PyJavaParserBaseVisitor;
7 | import pyjava.parser.PyJavaParser.*;
8 |
9 | public class GetGroupAtom extends PyJavaParserBaseVisitor {
10 | protected ParseTree defaultVal;
11 |
12 | public GetGroupAtom(ParseTree defaultVal) {
13 | this.defaultVal = defaultVal;
14 | }
15 |
16 | @Override
17 | protected ParseTree defaultResult() {
18 | return defaultVal;
19 | }
20 |
21 | @Override
22 | @Deprecated
23 | public ParseTree visitChildren(RuleNode node) {
24 | return defaultVal;
25 | }
26 |
27 | @Override
28 | public ParseTree visitPatterns(PatternsContext ctx) {
29 | var pattern = ctx.pattern();
30 | if (pattern == null) return defaultVal;
31 | return pattern.accept(this);
32 | }
33 |
34 | @Override
35 | public ParseTree visitPattern(PatternContext ctx) {
36 | return ctx.getChild(0).accept(this);
37 | }
38 |
39 | @Override
40 | public ParseTree visitOrPattern(OrPatternContext ctx) {
41 | if (ctx.BAR(0) != null) return defaultVal;
42 | return ctx.closedPattern(0);
43 | }
44 |
45 | @Override
46 | public ParseTree visitArgument(ArgumentContext ctx) {
47 | return ctx.getChild(0).accept(this);
48 | }
49 |
50 | @Override
51 | public ParseTree visitStarTargets(StarTargetsContext ctx) {
52 | var iter = ctx.starTarget().iterator();
53 | var starTarget = iter.next();
54 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
55 | return starTarget.accept(this);
56 | }
57 |
58 | @Override
59 | public ParseTree visitStarTarget(StarTargetContext ctx) {
60 | if (ctx.STAR() != null) return defaultVal;
61 | return ctx.targetWithStarAtom().accept(this);
62 | }
63 |
64 | @Override
65 | public ParseTree visitTargetStarAtom(TargetStarAtomContext ctx) {
66 | return ctx.starAtom();
67 | }
68 |
69 | @Override
70 | public ParseTree visitSubjectExpr(SubjectExprContext ctx) {
71 | var namedExpression = ctx.namedExpression();
72 | if (namedExpression == null) return defaultVal;
73 | return namedExpression.accept(this);
74 | }
75 |
76 | @Override
77 | public ParseTree visitStarExpressions(StarExpressionsContext ctx) {
78 | var iter = ctx.starExpression().iterator();
79 | var starExpression = iter.next();
80 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
81 | return starExpression.accept(this);
82 | }
83 |
84 | @Override
85 | public ParseTree visitStarExpression(StarExpressionContext ctx) {
86 | var expression = ctx.expression();
87 | if (expression == null) return defaultVal;
88 | return expression.accept(this);
89 | }
90 |
91 | @Override
92 | public ParseTree visitStarNamedExpressions(StarNamedExpressionsContext ctx) {
93 | var iter = ctx.starNamedExpression().iterator();
94 | var starNamedExpression = iter.next();
95 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
96 | return starNamedExpression.accept(this);
97 | }
98 |
99 | @Override
100 | public ParseTree visitStarNamedExpression(StarNamedExpressionContext ctx) {
101 | var namedExpression = ctx.namedExpression();
102 | if (namedExpression == null) return defaultVal;
103 | return namedExpression.accept(this);
104 | }
105 |
106 | @Override
107 | public ParseTree visitAtomTPrimary(AtomTPrimaryContext ctx) {
108 | return ctx.atom();
109 | }
110 |
111 | @Override
112 | public ParseTree visitNamedExpression(NamedExpressionContext ctx) {
113 | var expression = ctx.expression();
114 | if (expression == null) return defaultVal;
115 | return expression.accept(this);
116 | }
117 |
118 | @Override
119 | public ParseTree visitDisjunctionExpression(DisjunctionExpressionContext ctx) {
120 | return ctx.disjunction().accept(this);
121 | }
122 |
123 | @Override
124 | public ParseTree visitDisjunction(DisjunctionContext ctx) {
125 | if (ctx.conjunction(1) != null) return defaultVal;
126 | return ctx.conjunction(0).accept(this);
127 | }
128 |
129 | @Override
130 | public ParseTree visitConjunction(ConjunctionContext ctx) {
131 | if (ctx.inversion(1) != null) return defaultVal;
132 | return ctx.inversion(0).accept(this);
133 | }
134 |
135 | @Override
136 | public ParseTree visitInversion(InversionContext ctx) {
137 | var comparison = ctx.comparison();
138 | if (comparison == null) return defaultVal;
139 | return comparison.accept(this);
140 | }
141 |
142 | @Override
143 | public ParseTree visitComparison(ComparisonContext ctx) {
144 | if (ctx.compareOpBitwiseOrPair(0) != null) return defaultVal;
145 | return ctx.bitwiseOr().accept(this);
146 | }
147 |
148 | @Override
149 | public ParseTree visitBitwiseOr(BitwiseOrContext ctx) {
150 | if (ctx.bitwiseOr() != null) return defaultVal;
151 | return ctx.bitwiseXor().accept(this);
152 | }
153 |
154 | @Override
155 | public ParseTree visitBitwiseXor(BitwiseXorContext ctx) {
156 | if (ctx.bitwiseXor() != null) return defaultVal;
157 | return ctx.bitwiseAnd().accept(this);
158 | }
159 |
160 | @Override
161 | public ParseTree visitBitwiseAnd(BitwiseAndContext ctx) {
162 | if (ctx.bitwiseAnd() != null) return defaultVal;
163 | return ctx.shiftExpr().accept(this);
164 | }
165 |
166 | @Override
167 | public ParseTree visitShiftExpr(ShiftExprContext ctx) {
168 | if (ctx.shiftExpr() != null) return defaultVal;
169 | return ctx.sum().accept(this);
170 | }
171 |
172 | @Override
173 | public ParseTree visitSum(SumContext ctx) {
174 | if (ctx.sum() != null) return defaultVal;
175 | return ctx.term().accept(this);
176 | }
177 |
178 | @Override
179 | public ParseTree visitTerm(TermContext ctx) {
180 | if (ctx.term() != null) return defaultVal;
181 | return ctx.factor().accept(this);
182 | }
183 |
184 | @Override
185 | public ParseTree visitFactor(FactorContext ctx) {
186 | var power = ctx.power();
187 | if (power == null) return defaultVal;
188 | return power.accept(this);
189 | }
190 |
191 | @Override
192 | public ParseTree visitPower(PowerContext ctx) {
193 | if (ctx.factor() != null) return defaultVal;
194 | return ctx.awaitPrimary().accept(this);
195 | }
196 |
197 | @Override
198 | public ParseTree visitAwaitPrimary(AwaitPrimaryContext ctx) {
199 | if (ctx.AWAIT() != null) return defaultVal;
200 | return ctx.primary().accept(this);
201 | }
202 |
203 | @Override
204 | public ParseTree visitAtomPrimary(AtomPrimaryContext ctx) {
205 | return ctx.atom();
206 | }
207 |
208 | // @Override
209 | // public ParseTree visitDelTargets(DelTargetsContext ctx) {
210 | // if (ctx.COMMA(0) != null) return defaultVal;
211 | // return ctx.delTarget(0).accept(this);
212 | // }
213 |
214 | public static ParseTree getGroupAtom(ParseTree input) {
215 | return input.accept(new GetGroupAtom(input));
216 | }
217 | }
218 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/tree/GetGroupAtomContents.java:
--------------------------------------------------------------------------------
1 | package pyjava.tree;
2 |
3 | import org.antlr.v4.runtime.tree.ParseTree;
4 | import org.antlr.v4.runtime.tree.RuleNode;
5 |
6 | import pyjava.parser.PyJavaParserBaseVisitor;
7 | import pyjava.parser.PyJavaParser.*;
8 |
9 | public class GetGroupAtomContents extends PyJavaParserBaseVisitor {
10 | protected ParseTree defaultVal;
11 | protected boolean includeTuples;
12 |
13 | public GetGroupAtomContents(ParseTree defaultVal, boolean includeTuples) {
14 | this.defaultVal = defaultVal;
15 | this.includeTuples = includeTuples;
16 | }
17 |
18 | @Override
19 | protected ParseTree defaultResult() {
20 | return defaultVal;
21 | }
22 |
23 | @Override
24 | @Deprecated
25 | public ParseTree visitChildren(RuleNode node) {
26 | return defaultVal;
27 | }
28 |
29 | @Override
30 | public ParseTree visitPatterns(PatternsContext ctx) {
31 | var pattern = ctx.pattern();
32 | if (pattern == null) return defaultVal;
33 | return pattern.accept(this);
34 | }
35 |
36 | @Override
37 | public ParseTree visitPattern(PatternContext ctx) {
38 | return ctx.getChild(0).accept(this);
39 | }
40 |
41 | @Override
42 | public ParseTree visitOrPattern(OrPatternContext ctx) {
43 | if (ctx.BAR(0) != null) return defaultVal;
44 | return ctx.closedPattern(0).accept(this);
45 | }
46 |
47 | @Override
48 | public ParseTree visitGroupPattern(GroupPatternContext ctx) {
49 | return ctx.pattern();
50 | }
51 |
52 | @Override
53 | public ParseTree visitTupleSequencePattern(TupleSequencePatternContext ctx) {
54 | if (!includeTuples) return defaultVal;
55 | var openSequencePattern = ctx.openSequencePattern();
56 | if (openSequencePattern == null) return defaultVal;
57 | return openSequencePattern;
58 | }
59 |
60 | @Override
61 | public ParseTree visitArgument(ArgumentContext ctx) {
62 | return ctx.getChild(0).accept(this);
63 | }
64 |
65 | @Override
66 | public ParseTree visitStarTargets(StarTargetsContext ctx) {
67 | var iter = ctx.starTarget().iterator();
68 | var starTarget = iter.next();
69 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
70 | return starTarget.accept(this);
71 | }
72 |
73 | @Override
74 | public ParseTree visitStarTarget(StarTargetContext ctx) {
75 | if (ctx.STAR() != null) return defaultVal;
76 | return ctx.targetWithStarAtom().accept(this);
77 | }
78 |
79 | @Override
80 | public ParseTree visitTargetStarAtom(TargetStarAtomContext ctx) {
81 | return ctx.starAtom().accept(this);
82 | }
83 |
84 | @Override
85 | public ParseTree visitStarAtomGroup(StarAtomGroupContext ctx) {
86 | return ctx.targetWithStarAtom();
87 | }
88 |
89 | @Override
90 | public ParseTree visitTupleStarAtom(TupleStarAtomContext ctx) {
91 | if (!includeTuples) return defaultVal;
92 | var starTargets = ctx.starTargets();
93 | if (starTargets == null) return defaultVal;
94 | return starTargets;
95 | }
96 |
97 | @Override
98 | public ParseTree visitSubjectExpr(SubjectExprContext ctx) {
99 | var namedExpression = ctx.namedExpression();
100 | if (namedExpression == null) return defaultVal;
101 | return namedExpression.accept(this);
102 | }
103 |
104 | @Override
105 | public ParseTree visitStarExpressions(StarExpressionsContext ctx) {
106 | var iter = ctx.starExpression().iterator();
107 | var starExpression = iter.next();
108 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
109 | return starExpression.accept(this);
110 | }
111 |
112 | @Override
113 | public ParseTree visitStarExpression(StarExpressionContext ctx) {
114 | var expression = ctx.expression();
115 | if (expression == null) return defaultVal;
116 | return expression.accept(this);
117 | }
118 |
119 | @Override
120 | public ParseTree visitStarNamedExpressions(StarNamedExpressionsContext ctx) {
121 | var iter = ctx.starNamedExpression().iterator();
122 | var starNamedExpression = iter.next();
123 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
124 | return starNamedExpression.accept(this);
125 | }
126 |
127 | @Override
128 | public ParseTree visitStarNamedExpression(StarNamedExpressionContext ctx) {
129 | var namedExpression = ctx.namedExpression();
130 | if (namedExpression == null) return defaultVal;
131 | return namedExpression.accept(this);
132 | }
133 |
134 | @Override
135 | public ParseTree visitAtomTPrimary(AtomTPrimaryContext ctx) {
136 | return ctx.atom().accept(this);
137 | }
138 |
139 | @Override
140 | public ParseTree visitNamedExpression(NamedExpressionContext ctx) {
141 | var expression = ctx.expression();
142 | if (expression == null) return defaultVal;
143 | return expression.accept(this);
144 | }
145 |
146 | @Override
147 | public ParseTree visitDisjunctionExpression(DisjunctionExpressionContext ctx) {
148 | return ctx.disjunction().accept(this);
149 | }
150 |
151 | @Override
152 | public ParseTree visitDisjunction(DisjunctionContext ctx) {
153 | if (ctx.conjunction(1) != null) return defaultVal;
154 | return ctx.conjunction(0).accept(this);
155 | }
156 |
157 | @Override
158 | public ParseTree visitConjunction(ConjunctionContext ctx) {
159 | if (ctx.inversion(1) != null) return defaultVal;
160 | return ctx.inversion(0).accept(this);
161 | }
162 |
163 | @Override
164 | public ParseTree visitInversion(InversionContext ctx) {
165 | var comparison = ctx.comparison();
166 | if (comparison == null) return defaultVal;
167 | return comparison.accept(this);
168 | }
169 |
170 | @Override
171 | public ParseTree visitComparison(ComparisonContext ctx) {
172 | if (ctx.compareOpBitwiseOrPair(0) != null) return defaultVal;
173 | return ctx.bitwiseOr().accept(this);
174 | }
175 |
176 | @Override
177 | public ParseTree visitBitwiseOr(BitwiseOrContext ctx) {
178 | if (ctx.bitwiseOr() != null) return defaultVal;
179 | return ctx.bitwiseXor().accept(this);
180 | }
181 |
182 | @Override
183 | public ParseTree visitBitwiseXor(BitwiseXorContext ctx) {
184 | if (ctx.bitwiseXor() != null) return defaultVal;
185 | return ctx.bitwiseAnd().accept(this);
186 | }
187 |
188 | @Override
189 | public ParseTree visitBitwiseAnd(BitwiseAndContext ctx) {
190 | if (ctx.bitwiseAnd() != null) return defaultVal;
191 | return ctx.shiftExpr().accept(this);
192 | }
193 |
194 | @Override
195 | public ParseTree visitShiftExpr(ShiftExprContext ctx) {
196 | if (ctx.shiftExpr() != null) return defaultVal;
197 | return ctx.sum().accept(this);
198 | }
199 |
200 | @Override
201 | public ParseTree visitSum(SumContext ctx) {
202 | if (ctx.sum() != null) return defaultVal;
203 | return ctx.term().accept(this);
204 | }
205 |
206 | @Override
207 | public ParseTree visitTerm(TermContext ctx) {
208 | if (ctx.term() != null) return defaultVal;
209 | return ctx.factor().accept(this);
210 | }
211 |
212 | @Override
213 | public ParseTree visitFactor(FactorContext ctx) {
214 | var power = ctx.power();
215 | if (power == null) return defaultVal;
216 | return power.accept(this);
217 | }
218 |
219 | @Override
220 | public ParseTree visitPower(PowerContext ctx) {
221 | if (ctx.factor() != null) return defaultVal;
222 | return ctx.awaitPrimary().accept(this);
223 | }
224 |
225 | @Override
226 | public ParseTree visitAwaitPrimary(AwaitPrimaryContext ctx) {
227 | if (ctx.AWAIT() != null) return defaultVal;
228 | return ctx.primary().accept(this);
229 | }
230 |
231 | @Override
232 | public ParseTree visitAtomPrimary(AtomPrimaryContext ctx) {
233 | return ctx.atom().accept(this);
234 | }
235 |
236 | @Override
237 | public ParseTree visitGroupAtom(GroupAtomContext ctx) {
238 | return ctx.getChild(1);
239 | }
240 |
241 | @Override
242 | public ParseTree visitTupleAtom(TupleAtomContext ctx) {
243 | if (!includeTuples) return defaultVal;
244 | var starNamedExpressions = ctx.starNamedExpressions();
245 | if (starNamedExpressions == null) return defaultVal;
246 | return starNamedExpressions;
247 | }
248 |
249 | public static ParseTree getGroupAtomContents(ParseTree input) {
250 | return getGroupAtomContents(input, false);
251 | }
252 |
253 | public static ParseTree getGroupAtomContents(ParseTree input, boolean includeTuples) {
254 | return input.accept(new GetGroupAtomContents(input, includeTuples));
255 | }
256 | }
257 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/tree/GetPrimary.java:
--------------------------------------------------------------------------------
1 | package pyjava.tree;
2 |
3 | import org.antlr.v4.runtime.tree.ParseTree;
4 | import org.antlr.v4.runtime.tree.RuleNode;
5 |
6 | import pyjava.parser.PyJavaParserBaseVisitor;
7 | import pyjava.parser.PyJavaParser.*;
8 |
9 | public class GetPrimary extends PyJavaParserBaseVisitor {
10 | protected ParseTree defaultVal;
11 |
12 | public GetPrimary(ParseTree defaultVal) {
13 | this.defaultVal = defaultVal;
14 | }
15 |
16 | @Override
17 | protected ParseTree defaultResult() {
18 | return defaultVal;
19 | }
20 |
21 | @Override
22 | @Deprecated
23 | public ParseTree visitChildren(RuleNode node) {
24 | return defaultVal;
25 | }
26 |
27 | @Override
28 | public ParseTree visitPatterns(PatternsContext ctx) {
29 | var pattern = ctx.pattern();
30 | if (pattern == null) return defaultVal;
31 | return pattern.accept(this);
32 | }
33 |
34 | @Override
35 | public ParseTree visitPattern(PatternContext ctx) {
36 | return ctx.getChild(0).accept(this);
37 | }
38 |
39 | @Override
40 | public ParseTree visitOrPattern(OrPatternContext ctx) {
41 | if (ctx.BAR(0) != null) return defaultVal;
42 | return ctx.closedPattern(0);
43 | }
44 |
45 | @Override
46 | public ParseTree visitArgument(ArgumentContext ctx) {
47 | return ctx.getChild(0).accept(this);
48 | }
49 |
50 | @Override
51 | public ParseTree visitStarTargets(StarTargetsContext ctx) {
52 | var iter = ctx.starTarget().iterator();
53 | var starTarget = iter.next();
54 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
55 | return starTarget.accept(this);
56 | }
57 |
58 | @Override
59 | public ParseTree visitStarTarget(StarTargetContext ctx) {
60 | if (ctx.STAR() != null) return defaultVal;
61 | return ctx.targetWithStarAtom();
62 | }
63 |
64 | @Override
65 | public ParseTree visitSubjectExpr(SubjectExprContext ctx) {
66 | var namedExpression = ctx.namedExpression();
67 | if (namedExpression == null) return defaultVal;
68 | return namedExpression.accept(this);
69 | }
70 |
71 | @Override
72 | public ParseTree visitStarExpressions(StarExpressionsContext ctx) {
73 | var iter = ctx.starExpression().iterator();
74 | var starExpression = iter.next();
75 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
76 | return starExpression.accept(this);
77 | }
78 |
79 | @Override
80 | public ParseTree visitStarExpression(StarExpressionContext ctx) {
81 | var expression = ctx.expression();
82 | if (expression == null) return defaultVal;
83 | return expression.accept(this);
84 | }
85 |
86 | @Override
87 | public ParseTree visitStarNamedExpressions(StarNamedExpressionsContext ctx) {
88 | var iter = ctx.starNamedExpression().iterator();
89 | var starNamedExpression = iter.next();
90 | if (iter.hasNext() || ctx.COMMA(0) != null) return defaultVal;
91 | return starNamedExpression.accept(this);
92 | }
93 |
94 | @Override
95 | public ParseTree visitStarNamedExpression(StarNamedExpressionContext ctx) {
96 | var namedExpression = ctx.namedExpression();
97 | if (namedExpression == null) return defaultVal;
98 | return namedExpression.accept(this);
99 | }
100 |
101 | @Override
102 | public ParseTree visitAtomTPrimary(AtomTPrimaryContext ctx) {
103 | return ctx.atom();
104 | }
105 |
106 | @Override
107 | public ParseTree visitNamedExpression(NamedExpressionContext ctx) {
108 | var expression = ctx.expression();
109 | if (expression == null) return defaultVal;
110 | return expression.accept(this);
111 | }
112 |
113 | @Override
114 | public ParseTree visitDisjunctionExpression(DisjunctionExpressionContext ctx) {
115 | return ctx.disjunction().accept(this);
116 | }
117 |
118 | @Override
119 | public ParseTree visitDisjunction(DisjunctionContext ctx) {
120 | if (ctx.conjunction(1) != null) return defaultVal;
121 | return ctx.conjunction(0).accept(this);
122 | }
123 |
124 | @Override
125 | public ParseTree visitConjunction(ConjunctionContext ctx) {
126 | if (ctx.inversion(1) != null) return defaultVal;
127 | return ctx.inversion(0).accept(this);
128 | }
129 |
130 | @Override
131 | public ParseTree visitInversion(InversionContext ctx) {
132 | var comparison = ctx.comparison();
133 | if (comparison == null) return defaultVal;
134 | return comparison.accept(this);
135 | }
136 |
137 | @Override
138 | public ParseTree visitComparison(ComparisonContext ctx) {
139 | if (ctx.compareOpBitwiseOrPair(0) != null) return defaultVal;
140 | return ctx.bitwiseOr().accept(this);
141 | }
142 |
143 | @Override
144 | public ParseTree visitBitwiseOr(BitwiseOrContext ctx) {
145 | if (ctx.bitwiseOr() != null) return defaultVal;
146 | return ctx.bitwiseXor().accept(this);
147 | }
148 |
149 | @Override
150 | public ParseTree visitBitwiseXor(BitwiseXorContext ctx) {
151 | if (ctx.bitwiseXor() != null) return defaultVal;
152 | return ctx.bitwiseAnd().accept(this);
153 | }
154 |
155 | @Override
156 | public ParseTree visitBitwiseAnd(BitwiseAndContext ctx) {
157 | if (ctx.bitwiseAnd() != null) return defaultVal;
158 | return ctx.shiftExpr().accept(this);
159 | }
160 |
161 | @Override
162 | public ParseTree visitShiftExpr(ShiftExprContext ctx) {
163 | if (ctx.shiftExpr() != null) return defaultVal;
164 | return ctx.sum().accept(this);
165 | }
166 |
167 | @Override
168 | public ParseTree visitSum(SumContext ctx) {
169 | if (ctx.sum() != null) return defaultVal;
170 | return ctx.term().accept(this);
171 | }
172 |
173 | @Override
174 | public ParseTree visitTerm(TermContext ctx) {
175 | if (ctx.term() != null) return defaultVal;
176 | return ctx.factor().accept(this);
177 | }
178 |
179 | @Override
180 | public ParseTree visitFactor(FactorContext ctx) {
181 | var power = ctx.power();
182 | if (power == null) return defaultVal;
183 | return power.accept(this);
184 | }
185 |
186 | @Override
187 | public ParseTree visitPower(PowerContext ctx) {
188 | if (ctx.factor() != null) return defaultVal;
189 | return ctx.awaitPrimary().accept(this);
190 | }
191 |
192 | @Override
193 | public ParseTree visitAwaitPrimary(AwaitPrimaryContext ctx) {
194 | if (ctx.AWAIT() != null) return defaultVal;
195 | return ctx.primary();
196 | }
197 |
198 | public static ParseTree getPrimary(ParseTree input) {
199 | return input.accept(new GetPrimary(input));
200 | }
201 | }
202 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/tree/IndentationAwareAppender.java:
--------------------------------------------------------------------------------
1 | package pyjava.tree;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Objects;
5 |
6 | public class IndentationAwareAppender implements LazyAppendable {
7 | private LinkedList appendables = new LinkedList<>();
8 |
9 | @Override
10 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
11 | for (var appendable : appendables) {
12 | appendable.doAppend(a, state);
13 | }
14 | }
15 |
16 | public IndentationAwareAppender append(char c) {
17 | appendables.addLast(new AppendChar(c));
18 | return this;
19 | }
20 |
21 | protected static record AppendChar(char c) implements LazyAppendable {
22 | @Override
23 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
24 | a.append(c);
25 | }
26 | }
27 |
28 | public IndentationAwareAppender append(CharSequence str) {
29 | appendables.addLast(new AppendCharSequence(str));
30 | return this;
31 | }
32 |
33 | protected static record AppendCharSequence(CharSequence str) implements LazyAppendable {
34 | public AppendCharSequence {
35 | Objects.requireNonNull(str);
36 | }
37 |
38 | @Override
39 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
40 | a.append(str);
41 | }
42 | }
43 |
44 | public IndentationAwareAppender append(CharSequence str, int start, int end) {
45 | appendables.addLast(new AppendCharSequenceFromTo(str, start, end));
46 | return this;
47 | }
48 |
49 | protected static record AppendCharSequenceFromTo(CharSequence str, int start, int end) implements LazyAppendable {
50 | public AppendCharSequenceFromTo {
51 | Objects.checkFromToIndex(start, end, str.length());
52 | }
53 |
54 | @Override
55 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
56 | a.append(str, start, end);
57 | }
58 | }
59 |
60 | public IndentationAwareAppender decrIndentNewline() {
61 | if (!appendables.isEmpty() && appendables.getLast() instanceof Newline) {
62 | appendables.add(appendables.size() - 1, DecrIndent.DEFAULT_INSTANCE);
63 | return this;
64 | } else {
65 | return decrIndent().newline();
66 | }
67 | }
68 |
69 | public IndentationAwareAppender newline() {
70 | appendables.addLast(Newline.DEFAULT_INSTANCE);
71 | return this;
72 | }
73 |
74 | protected static class Newline implements LazyAppendable {
75 | public static final Newline DEFAULT_INSTANCE = new Newline();
76 |
77 | @Override
78 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
79 | a.append('\n');
80 | synchronized (state) {
81 | for (int i = 0; i < state.indent; i++) {
82 | a.append(" ");
83 | }
84 | }
85 | }
86 | }
87 |
88 | public IndentationAwareAppender incrIndent() {
89 | if (!appendables.isEmpty()) {
90 | var last = appendables.getLast();
91 | if (last instanceof IncrIndent oldIncrIndent) {
92 | appendables.set(appendables.size() - 1, new IncrIndent(oldIncrIndent.amount() + 1));
93 | return this;
94 | }
95 | if (last instanceof DecrIndent oldDecrIndent) {
96 | if (oldDecrIndent.amount() == 1) {
97 | appendables.removeLast();
98 | } else {
99 | appendables.set(appendables.size() - 1, new DecrIndent(oldDecrIndent.amount() - 1));
100 | }
101 | return this;
102 | }
103 | }
104 | appendables.addLast(IncrIndent.DEFAULT_INSTANCE);
105 | return this;
106 | }
107 |
108 | protected static record IncrIndent(int amount) implements LazyAppendable {
109 | public static final IncrIndent DEFAULT_INSTANCE = new IncrIndent(1);
110 |
111 | public IncrIndent {
112 | if (amount < 1) {
113 | throw new IllegalArgumentException("invalid increase indent amount");
114 | }
115 | }
116 |
117 | @Override
118 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
119 | state.indent += amount;
120 | }
121 | }
122 |
123 | public IndentationAwareAppender decrIndent() {
124 | if (!appendables.isEmpty()) {
125 | var last = appendables.getLast();
126 | if (last instanceof DecrIndent oldDecrIndent) {
127 | appendables.set(appendables.size() - 1, new DecrIndent(oldDecrIndent.amount() + 1));
128 | return this;
129 | }
130 | if (last instanceof IncrIndent oldIncrIndent) {
131 | if (oldIncrIndent.amount() == 1) {
132 | appendables.removeLast();
133 | } else {
134 | appendables.set(appendables.size() - 1, new IncrIndent(oldIncrIndent.amount() - 1));
135 | }
136 | return this;
137 | }
138 | }
139 | appendables.addLast(DecrIndent.DEFAULT_INSTANCE);
140 | return this;
141 | }
142 |
143 | protected static record DecrIndent(int amount) implements LazyAppendable {
144 | public static final DecrIndent DEFAULT_INSTANCE = new DecrIndent(1);
145 |
146 | public DecrIndent {
147 | if (amount < 1) {
148 | throw new IllegalArgumentException("invalid decrease indent amount");
149 | }
150 | }
151 |
152 | @Override
153 | public void doAppend(AppendFunction extends T> a, AppenderState state) throws T {
154 | if ((state.indent -= amount) < 0) {
155 | throw new IllegalStateException("cannot decrease indent, already at 0");
156 | }
157 | }
158 | }
159 |
160 | public IndentationAwareAppender later() {
161 | var result = new IndentationAwareAppender();
162 | appendables.addLast(result);
163 | return result;
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/src/main/java/pyjava/tree/LazyAppendable.java:
--------------------------------------------------------------------------------
1 | package pyjava.tree;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 | import java.io.PrintStream;
6 | import java.io.PrintWriter;
7 | import java.nio.CharBuffer;
8 | import java.nio.charset.Charset;
9 | import java.util.Objects;
10 |
11 | public interface LazyAppendable {
12 | void doAppend(AppendFunction extends T> a, AppenderState state) throws T;
13 |
14 | public static final class AppenderState {
15 | int indent;
16 | }
17 |
18 | @FunctionalInterface
19 | public static interface AppendFunction {
20 | void append(CharSequence str, int start, int end) throws T;
21 |
22 | default void append(CharSequence str) throws T {
23 | if (str == null) str = "null";
24 | append(str, 0, str.length());
25 | }
26 |
27 | default void append(char c) throws T {
28 | append(Character.toString(c));
29 | }
30 |
31 | public static AppendFunctionNoThrow wrap(final PrintStream ps) {
32 | Objects.requireNonNull(ps);
33 | return new AppendFunctionNoThrow() {
34 | @Override
35 | public void append(CharSequence str, int start, int end) {
36 | ps.append(str, start, end);
37 | }
38 |
39 | @Override
40 | public void append(CharSequence str) {
41 | ps.append(str);
42 | }
43 |
44 | @Override
45 | public void append(char ch) {
46 | ps.append(ch);
47 | }
48 | };
49 | }
50 |
51 | public static AppendFunctionNoThrow wrap(final PrintWriter pw) {
52 | Objects.requireNonNull(pw);
53 | return new AppendFunctionNoThrow() {
54 | @Override
55 | public void append(CharSequence str, int start, int end) {
56 | pw.append(str, start, end);
57 | }
58 |
59 | @Override
60 | public void append(CharSequence str) {
61 | pw.append(str);
62 | }
63 |
64 | @Override
65 | public void append(char c) {
66 | pw.write(c);
67 | }
68 | };
69 | }
70 |
71 | public static AppendFunctionNoThrow wrap(final StringBuilder sb) {
72 | Objects.requireNonNull(sb);
73 | return new AppendFunctionNoThrow() {
74 | @Override
75 | public void append(CharSequence str, int start, int end) {
76 | sb.append(str, start, end);
77 | }
78 |
79 | @Override
80 | public void append(CharSequence str) {
81 | sb.append(str);
82 | }
83 |
84 | @Override
85 | public void append(char c) {
86 | sb.append(c);
87 | }
88 | };
89 | }
90 |
91 | public static AppendFunctionNoThrow wrap(final StringBuffer sb) {
92 | Objects.requireNonNull(sb);
93 | return new AppendFunctionNoThrow() {
94 | @Override
95 | public void append(CharSequence str, int start, int end) {
96 | sb.append(str, start, end);
97 | }
98 |
99 | @Override
100 | public void append(CharSequence str) {
101 | sb.append(str);
102 | }
103 |
104 | @Override
105 | public void append(char c) {
106 | sb.append(c);
107 | }
108 | };
109 | }
110 |
111 | public static AppendFunction wrap(final Appendable a) {
112 | Objects.requireNonNull(a);
113 | return new AppendFunction<>() {
114 | @Override
115 | public void append(CharSequence str, int start, int end) throws IOException {
116 | a.append(str, start, end);
117 | }
118 |
119 | @Override
120 | public void append(CharSequence str) throws IOException {
121 | a.append(str);
122 | }
123 |
124 | @Override
125 | public void append(char c) throws IOException {
126 | a.append(c);
127 | }
128 | };
129 | }
130 |
131 | public static AppendFunction wrap(final OutputStream o) {
132 | return wrap(o, Charset.defaultCharset());
133 | }
134 |
135 | public static AppendFunction wrap(final OutputStream o, final Charset cs) {
136 | Objects.requireNonNull(o);
137 | Objects.requireNonNull(cs);
138 | return new AppendFunction<>() {
139 | @Override
140 | public void append(CharSequence str, int start, int end) throws IOException {
141 | var cbuf = CharBuffer.wrap(str, start, end);
142 | var bbuf = cs.encode(cbuf);
143 | assert bbuf.hasArray();
144 | o.write(bbuf.array());
145 | }
146 |
147 | @Override
148 | public void append(CharSequence str) throws IOException {
149 | var cbuf = CharBuffer.wrap(str);
150 | var bbuf = cs.encode(cbuf);
151 | assert bbuf.hasArray();
152 | o.write(bbuf.array());
153 | }
154 |
155 | @Override
156 | public void append(char c) throws IOException {
157 | var cbuf = CharBuffer.wrap(new char[] {c});
158 | var bbuf = cs.encode(cbuf);
159 | assert bbuf.hasArray();
160 | o.write(bbuf.array());
161 | }
162 | };
163 | }
164 | }
165 |
166 | @FunctionalInterface
167 | public static interface AppendFunctionNoThrow extends AppendFunction {
168 | void append(CharSequence str, int start, int end);
169 |
170 | default void append(CharSequence str) {
171 | AppendFunction.super.append(str);
172 | }
173 |
174 | default void append(char c) {
175 | AppendFunction.super.append(c);
176 | }
177 | }
178 | }
--------------------------------------------------------------------------------
/src/test/java/pyjava/BasicTests.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 | import static org.junit.jupiter.api.Assertions.assertTrue;
6 |
7 | import java.util.function.Supplier;
8 |
9 | import org.antlr.v4.runtime.*;
10 | import org.antlr.v4.runtime.misc.ParseCancellationException;
11 | import org.junit.jupiter.api.Test;
12 | import org.junit.jupiter.params.ParameterizedTest;
13 | import org.junit.jupiter.params.provider.ValueSource;
14 |
15 | import pyjava.parser.PyJavaLexer;
16 | import pyjava.parser.PyJavaParser;
17 | import pyjava.tree.LazyAppendable.AppendFunction;
18 | import pyjava.tree.Transpiler;
19 |
20 | class BasicTests {
21 | static final int REQUIRE_SEMICOLONS = 1, OPTIONAL_SEMICOLONS = 0;
22 | static final int FORCE_PARENS = 1 << 1;
23 | static final int FORCE_PARENS_IN_RETURN = 1 << 2;
24 |
25 | @Test
26 | void basicTest() {
27 | runTest(
28 | """
29 | x = 20
30 | y: list[str] = []
31 | z: list[str]
32 | z = None
33 | """,
34 | """
35 | x = 20
36 | y: list[str] = []
37 | z: list[str]
38 | z = None
39 | """
40 | );
41 | }
42 |
43 | @Test
44 | void testMissingRequiredSemicolons() {
45 | var e = assertThrows(ParseCancellationException.class, () ->
46 | runTest(
47 | """
48 | 2 + 3 * 5
49 | """,
50 | REQUIRE_SEMICOLONS,
51 | null
52 | )
53 | );
54 | assertException(e.getCause(), FailedPredicateException.class, "expected semicolon");
55 | }
56 |
57 | @Test
58 | void testRequiredSemicolons() {
59 | runTest(
60 | """
61 | print
62 | ("Hello, world");
63 | """,
64 | OPTIONAL_SEMICOLONS,
65 | """
66 | print
67 | ("Hello, world")
68 | """
69 | );
70 | runTest(
71 | """
72 | print
73 | ("Hello, world");
74 | """,
75 | REQUIRE_SEMICOLONS,
76 | """
77 | print("Hello, world")
78 | """
79 | );
80 | }
81 |
82 | @ParameterizedTest
83 | @ValueSource(strings = {
84 | """
85 | if (x < 10) {
86 | print(x);
87 | }
88 | """,
89 | """
90 | if (x < 10):
91 | print(x);
92 | """,
93 | """
94 | if (x < 10): print(x);
95 | """,
96 | """
97 | if (x < 10)
98 | print(x)
99 | """,
100 | """
101 | if (x < 10) print(x);
102 | """
103 | })
104 | void testBlocks(String input) {
105 | runTest(
106 | input,
107 | """
108 | if (x < 10):
109 | print(x)
110 | """
111 | );
112 | }
113 |
114 | @Test
115 | void testInconsistentIndentation() {
116 | runTest(
117 | """
118 | x = 20
119 | y = 30
120 | z = 50
121 | if (x <
122 | z) { print(
123 | y, end
124 | = ""
125 | )}
126 | """,
127 | """
128 | x = 20
129 | y = 30
130 | z = 50
131 | if (x < z):
132 | print(y, end="")
133 | """
134 | );
135 | }
136 |
137 | @Test
138 | void testIfExpression() {
139 | runTest(
140 | """
141 | x if x < 5 else 9
142 | """,
143 | """
144 | x if x < 5 else 9
145 | """
146 | );
147 | runTest(
148 | """
149 | x
150 | if x < 5
151 | else 9
152 | """,
153 | """
154 | x if x < 5 else 9
155 | """
156 | );
157 | }
158 |
159 | @Test
160 | void testMatchExpression() {
161 | runTest(
162 | """
163 | from typing import NamedTuple;
164 | class Point2d(NamedTuple) { x: int; y: int; }
165 | class Point3d(NamedTuple) { x: int; y: int; z: int; }
166 | def make_point_3d(pt) {
167 | match (pt) {
168 | case Point3d(_, _, _) {
169 | return pt;
170 | }
171 | case Point2d(x, y) | (x, y) {
172 | return Point3d(x, y, 0);
173 | }
174 | case (x, y, z) {
175 | return Point3d(x, y, z);
176 | }
177 | case _ {
178 | raise TypeError("Not a point we support");
179 | }
180 | }
181 | }
182 | """,
183 | REQUIRE_SEMICOLONS,
184 | """
185 | from typing import NamedTuple
186 | class Point2d(NamedTuple):
187 | x: int
188 | y: int
189 | class Point3d(NamedTuple):
190 | x: int
191 | y: int
192 | z: int
193 | def make_point_3d(pt):
194 | match (pt):
195 | case Point3d(_, _, _):
196 | return pt
197 | case Point2d(x, y) | (x, y):
198 | return Point3d(x, y, 0)
199 | case (x, y, z):
200 | return Point3d(x, y, z)
201 | case _:
202 | raise TypeError("Not a point we support")
203 | """
204 | );
205 | }
206 |
207 | @Test
208 | void testRidiculousSingleLineInput() {
209 | runTest(
210 | """
211 | def join_natural(iterable,separator=', ',word='and',oxford_comma=True,add_spaces=True){if add_spaces{if len(word)!=0 and not word[-1].isspace()word+=' ';if len(separator)!=0 and len(word)!=0 and not separator[-1].isspace()word=' '+word;}last2=None;set_last2=False;last1=None;set_last1=False;result="";for i,item in enumerate(iterable){if set_last2{if i==2 result+=str(last2);else result+=separator+str(last2);}last2=last1;set_last2=set_last1;last1=item;set_last1=True;}if set_last2{if result{if oxford_comma result+=separator+str(last2)+separator+word+str(last1);else{if add_spaces and not word[0].isspace()word=' '+word;result+=separator+str(last2)+word+str(last1);}}else{if add_spaces and not word[0].isspace()word=' '+word;result=str(last2)+word+str(last1);}}elif set_last1 result=str(last1);return result;}class LookAheadListIterator(object){def __init__(self,iterable){self.list=list(iterable);self.marker=0;self.saved_markers=[];self.default=None;self.value=None;}def __iter__(self){return self;}def set_default(self,value){self.default=value;}def next(self){return self.__next__();}def previous(self){try{self.value=self.list[self.marker-1];self.marker-=1;}except IndexError;return self.value;}def __next__(self){try{self.value=self.list[self.marker];self.marker+=1;}except IndexError raise StopIteration();return self.value;}def look(self,i=0){try{self.value=self.list[self.marker+i];}except IndexError return self.default;return self.value;}def last(self){return self.value;}def __enter__(self){self.push_marker();return self;}def __exit__(self,exc_type,exc_val,exc_tb){if exc_type or exc_val or exc_tb self.pop_marker(True);else self.pop_marker(False);}def push_marker(self){self.saved_markers.append(self.marker);}def pop_marker(self,reset){saved=self.saved_markers.pop();if reset self.marker=saved;}}
212 | """,
213 | REQUIRE_SEMICOLONS,
214 | """
215 | def join_natural(iterable, separator=', ', word='and', oxford_comma=True, add_spaces=True):
216 | if add_spaces:
217 | if len(word) != 0 and not word[-1].isspace():
218 | word += ' '
219 | if len(separator) != 0 and len(word) != 0 and not separator[-1].isspace():
220 | word = ' ' + word
221 | last2 = None
222 | set_last2 = False
223 | last1 = None
224 | set_last1 = False
225 | result = ""
226 | for i, item in enumerate(iterable):
227 | if set_last2:
228 | if i == 2:
229 | result += str(last2)
230 | else:
231 | result += separator + str(last2)
232 | last2 = last1
233 | set_last2 = set_last1
234 | last1 = item
235 | set_last1 = True
236 | if set_last2:
237 | if result:
238 | if oxford_comma:
239 | result += separator + str(last2) + separator + word + str(last1)
240 | else:
241 | if add_spaces and not word[0].isspace():
242 | word = ' ' + word
243 | result += separator + str(last2) + word + str(last1)
244 | else:
245 | if add_spaces and not word[0].isspace():
246 | word = ' ' + word
247 | result = str(last2) + word + str(last1)
248 | elif set_last1:
249 | result = str(last1)
250 | return result
251 | class LookAheadListIterator(object):
252 | def __init__(self, iterable):
253 | self.list = list(iterable)
254 | self.marker = 0
255 | self.saved_markers = []
256 | self.default = None
257 | self.value = None
258 | def __iter__(self):
259 | return self
260 | def set_default(self, value):
261 | self.default = value
262 | def next(self):
263 | return self.__next__()
264 | def previous(self):
265 | try:
266 | self.value = self.list[self.marker - 1]
267 | self.marker -= 1
268 | except IndexError:
269 | pass
270 | return self.value
271 | def __next__(self):
272 | try:
273 | self.value = self.list[self.marker]
274 | self.marker += 1
275 | except IndexError:
276 | raise StopIteration()
277 | return self.value
278 | def look(self, i=0):
279 | try:
280 | self.value = self.list[self.marker + i]
281 | except IndexError:
282 | return self.default
283 | return self.value
284 | def last(self):
285 | return self.value
286 | def __enter__(self):
287 | self.push_marker()
288 | return self
289 | def __exit__(self, exc_type, exc_val, exc_tb):
290 | if exc_type or exc_val or exc_tb:
291 | self.pop_marker(True)
292 | else:
293 | self.pop_marker(False)
294 | def push_marker(self):
295 | self.saved_markers.append(self.marker)
296 | def pop_marker(self, reset):
297 | saved = self.saved_markers.pop()
298 | if reset:
299 | self.marker = saved
300 | """
301 | );
302 | }
303 |
304 | /* (Blank test body for quick copy-paste)
305 |
306 | runTest(
307 | """
308 |
309 | """,
310 |
311 | """
312 |
313 | """
314 | );
315 |
316 | */
317 |
318 | static void runTest(String input, String expected) {
319 | runTest(input, 0, expected);
320 | }
321 |
322 | static void runTest(String input, int flags, String expected) {
323 | var source = CharStreams.fromString(input);
324 | var lexer = new PyJavaLexer(source);
325 | var errorListener = new BaseErrorListener();
326 | lexer.removeErrorListeners();
327 | lexer.addErrorListener(errorListener);
328 | var tokens = new CommonTokenStream(lexer);
329 | var parser = new PyJavaParser(tokens,
330 | PyJavaOptions.builder()
331 | .requireSemicolons((flags & REQUIRE_SEMICOLONS) != 0)
332 | .forceParensInStatements((flags & FORCE_PARENS) != 0)
333 | .forceParensInReturnYieldRaise((flags & FORCE_PARENS_IN_RETURN) != 0)
334 | .build()
335 | );
336 | parser.setErrorHandler(new BailErrorStrategy());
337 | //parser.removeErrorListeners();
338 | parser.addErrorListener(errorListener);
339 | var file = parser.file();
340 | var transpiler = new Transpiler();
341 | file.accept(transpiler);
342 | var sb = new StringBuilder();
343 | transpiler.appendTo(AppendFunction.wrap(sb));
344 | assertEquals(expected, sb.toString());
345 | }
346 |
347 | static void assertException(Throwable e, Class extends Throwable> exceptionType) {
348 | assertTrue(exceptionType.isInstance(e), () -> "cause was not "+exceptionType.getName()+", was "+(e.getCause() == null? "null" : e.getCause().getClass().getName()));
349 | }
350 |
351 | static void assertException(Throwable e, Class extends Throwable> exceptionType, String message) {
352 | assertTrue(exceptionType.isInstance(e), () -> "cause was not "+exceptionType.getName()+", was "+(e == null? "null" : e.getClass().getName()));
353 | assertEquals(e.getMessage(), message);
354 | }
355 |
356 | static void assertException(Throwable e, Class extends Throwable> exceptionType, Supplier extends String> message) {
357 | assertTrue(exceptionType.isInstance(e), () -> "cause was not "+exceptionType.getName()+", was "+(e == null? "null" : e.getClass().getName()));
358 | assertEquals(e.getMessage(), message.get());
359 | }
360 | }
361 |
--------------------------------------------------------------------------------
/src/test/java/pyjava/TestComments.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import static pyjava.BasicTests.runTest;
4 |
5 | import org.junit.jupiter.api.Test;
6 | import org.junit.jupiter.params.ParameterizedTest;
7 | import org.junit.jupiter.params.provider.ValueSource;
8 |
9 | class TestComments {
10 | @Test
11 | void testBlockCommentIndentedStyle() {
12 | runTest(
13 | """
14 | #{
15 | Block comment
16 | style #1:
17 | indented
18 | #}
19 | """,
20 |
21 | """
22 | # Block comment
23 | # style #1:
24 | # indented
25 | """
26 | );
27 | }
28 |
29 | @Test
30 | void testBlockCommentPrecedingHashtagsStyle() {
31 | runTest(
32 | """
33 | #{
34 | # Block comment
35 | # style #2:
36 | # preceding hashtags
37 | #}
38 | """,
39 |
40 | """
41 | # Block comment
42 | # style #2:
43 | # preceding hashtags
44 | """
45 | );
46 | }
47 |
48 | @Test
49 | void testBlockCommentPrecedingHashtagsStyleWithClosingBraceOnSameLineAsText() {
50 | runTest(
51 | """
52 | #{
53 | # Block comment
54 | # style #2a:
55 | # preceding hashtags, close brace
56 | # is on same line as last text line #}
57 | """,
58 |
59 | """
60 | # Block comment
61 | # style #2a:
62 | # preceding hashtags, close brace
63 | # is on same line as last text line
64 | """
65 | );
66 | }
67 |
68 | @Test
69 | void testBlockCommentInconsistentIndentation() {
70 | runTest(
71 | """
72 | #{
73 | # invalid block
74 | # comment preceding
75 | #hashtags,
76 | #result may look weird
77 | #}
78 | """,
79 |
80 | """
81 | # # invalid block
82 | # # comment preceding
83 | # #hashtags,
84 | # #result may look weird
85 | """
86 | );
87 | }
88 |
89 | @Test
90 | void testBlockCommentIndentedStyleOpeningBraceOnSameLineAsText() {
91 | runTest(
92 | """
93 | #{ Block comment
94 | style #3:
95 | first text line is on same
96 | line as opening brace
97 | #}
98 | """,
99 |
100 | """
101 | # Block comment
102 | # style #3:
103 | # first text line is on same
104 | # line as opening brace
105 | """
106 | );
107 | }
108 |
109 | @Test
110 | void testBlockCommentFollowingStatement() {
111 | runTest(
112 | """
113 | x = 0 #{ Block comment
114 | following statement
115 | is treated special #}
116 | """,
117 |
118 | """
119 | x = 0 # Block comment following statement is treated special
120 | """
121 | );
122 | }
123 |
124 | @Test
125 | void testMultipleComments() {
126 | runTest(
127 | """
128 | x = 3 #Comment after statement
129 | #Comment before statement
130 | y = 4
131 | """,
132 |
133 | """
134 | x = 3 # Comment after statement
135 | # Comment before statement
136 | y = 4
137 | """
138 | );
139 | }
140 |
141 | @Test
142 | void testMultipleComments2() {
143 | runTest(
144 | """
145 | # Line comment test
146 | #{
147 | Block comment Test
148 | Block comment Test line 2
149 | #} x = 3
150 | y = 4 # Comment after statement Test
151 | """,
152 |
153 | """
154 | # Line comment test
155 | # Block comment Test
156 | # Block comment Test line 2
157 | x = 3
158 | y = 4 # Comment after statement Test
159 | """
160 | );
161 | }
162 |
163 | @Test
164 | void testFunctionComments() {
165 | runTest(
166 | """
167 | # Comment before function
168 | def function() #{ Comment after function params #} {}
169 | """,
170 |
171 | """
172 | # Comment before function
173 | def function(): # Comment after function params
174 | pass
175 | """
176 | );
177 | }
178 |
179 | @Test
180 | void testFunctionComments2() {
181 | runTest(
182 | """
183 | def function() # Comment after function params
184 | #{
185 | # Comment before
186 | # function body
187 | #}
188 | {
189 | # Function body
190 | }
191 | """,
192 |
193 | """
194 | def function(): # Comment after function params
195 | # Comment before
196 | # function body
197 | pass
198 | # Function body
199 | """
200 | );
201 | }
202 |
203 | @Test
204 | void testFunctionDecoratorComments() {
205 | runTest(
206 | """
207 | # Comment before decorator
208 | @decorator # Comment after decorator
209 | # Comment between decorator and function
210 | def function() {}
211 | """,
212 |
213 | """
214 | # Comment before decorator
215 | @decorator # Comment after decorator
216 | # Comment between decorator and function
217 | def function():
218 | pass
219 | """
220 | );
221 | }
222 |
223 | @Test
224 | void testClassDecoratorComments() {
225 | runTest(
226 | """
227 | # Comment before class decorator
228 | @decorator # Comment after decorator
229 | # Comment before class
230 | class A # Comment after class
231 | # Comment before class body
232 | {
233 | # Class body
234 | }
235 | """,
236 |
237 | """
238 | # Comment before class decorator
239 | @decorator # Comment after decorator
240 | # Comment before class
241 | class A: # Comment after class
242 | # Comment before class body
243 | pass
244 | # Class body
245 | """
246 | );
247 | }
248 |
249 | @ParameterizedTest
250 | @ValueSource(strings = {
251 | """
252 | try # Comment after try
253 | {
254 | foo();
255 | }
256 | except Exception # Comment after except
257 | {
258 | handle();
259 | }
260 | else # Comment after else
261 | {
262 | bar();
263 | }
264 | finally # Comment after finally
265 | {
266 | finish();
267 | }
268 | """,
269 | """
270 | try { # Comment after try
271 | foo();
272 | } except Exception { # Comment after except
273 | handle();
274 | } else { # Comment after else
275 | bar();
276 | } finally { # Comment after finally
277 | finish();
278 | }
279 | """,
280 | """
281 | try: # Comment after try
282 | foo();
283 | except Exception: # Comment after except
284 | handle();
285 | else: # Comment after else
286 | bar();
287 | finally: # Comment after finally
288 | finish();
289 | """,
290 | """
291 | try #{ Comment after try #} {
292 | foo();
293 | } except Exception #{ Comment after except #} {
294 | handle();
295 | } else #{ Comment after else #} {
296 | bar();
297 | } finally #{ Comment after finally #} {
298 | finish();
299 | }
300 | """
301 | })
302 | void testCommentsInTryBlock(String input) {
303 | runTest(
304 | input,
305 | """
306 | try: # Comment after try
307 | foo()
308 | except Exception: # Comment after except
309 | handle()
310 | else: # Comment after else
311 | bar()
312 | finally: # Comment after finally
313 | finish()
314 | """
315 | );
316 | }
317 |
318 | @ParameterizedTest
319 | @ValueSource(strings = {
320 | """
321 | # Comment before match
322 | match expr # Comment after match
323 | {
324 | # Comment before case
325 | case 0 # Comment after case
326 | {}
327 | case 1 {}
328 | }
329 | """,
330 | """
331 | # Comment before match
332 | match expr { # Comment after match
333 | # Comment before case
334 | case 0 { # Comment after case
335 | pass;
336 | }
337 | case 1 {}
338 | }
339 | """
340 | })
341 | void testCommentsInMatchBlock(String input) {
342 | runTest(
343 | input,
344 | """
345 | # Comment before match
346 | match expr: # Comment after match
347 | # Comment before case
348 | case 0: # Comment after case
349 | pass
350 | case 1: pass
351 | """
352 | );
353 | }
354 | }
355 |
--------------------------------------------------------------------------------
/src/test/java/pyjava/TestCompoundExpressions.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import static pyjava.BasicTests.runTest;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Test cases for lambdas and class expressions
9 | */
10 | class TestCompoundExpressions {
11 | @Test
12 | void testMultilineLambda() {
13 | runTest(
14 | """
15 | from random import randrange
16 | elems = [randrange(10) for _ in range(10)] # Generate 10 random integers from 0 to 9
17 | elems = list(filter(lambda elem {
18 | if elem < 10: return True
19 | if elem == 2 return False;
20 | return True
21 | }, elems));
22 | print(elems)
23 | """,
24 | """
25 | from random import randrange
26 | elems = [randrange(10) for _ in range(10)] # Generate 10 random integers from 0 to 9
27 | def __lambda0(elem):
28 | if elem < 10:
29 | return True
30 | if elem == 2:
31 | return False
32 | return True
33 | elems = list(filter(__lambda0, elems))
34 | print(elems)
35 | """
36 | );
37 | }
38 |
39 | @Test
40 | void testAnonymousClass() {
41 | runTest(
42 | """
43 | class() { def say_hello(self) { print("Hello!"); } }
44 | .say_hello();
45 | """,
46 | """
47 | def __object0():
48 | class __object0:
49 | def say_hello(self):
50 | print("Hello!")
51 | return __object0
52 | __object0()().say_hello()
53 | """
54 | );
55 | }
56 |
57 | @Test
58 | void testAnonymousClass2() {
59 | runTest(
60 | """
61 | from abc import ABCMeta, abstractmethod;
62 | class Animal(metaclass=ABCMeta) {
63 | @abstractmethod def speak(self) { ... }
64 | @property
65 | @abstractmethod def name(self) -> str { ... }
66 | }
67 | mouse = class(Animal)("Mouse") {
68 | def __init__(self, name: str) {
69 | self._name = name;
70 | }
71 |
72 | def speak(self) { print("Squeak!"); }
73 |
74 | @property
75 | def name(self) -> str { return self._name; }
76 | };
77 | print(mouse.name, "says:");
78 | mouse.speak();
79 | """,
80 | """
81 | from abc import ABCMeta, abstractmethod
82 | class Animal(metaclass=ABCMeta):
83 | @abstractmethod
84 | def speak(self): ...
85 | @property
86 | @abstractmethod
87 | def name(self) -> str: ...
88 | def __Animal0():
89 | class __Animal0(Animal):
90 | def __init__(self, name: str):
91 | self._name = name
92 | def speak(self):
93 | print("Squeak!")
94 | @property
95 | def name(self) -> str:
96 | return self._name
97 | return __Animal0
98 | mouse = __Animal0()("Mouse")
99 | print(mouse.name, "says:")
100 | mouse.speak()
101 | """
102 | );
103 | }
104 |
105 | @Test
106 | void testMultilineAnnotatedLambda() {
107 | runTest(
108 | """
109 | click_counter = 0;
110 | click_display = document['#clickDisplay'];
111 | document.add_event_listener('click', lambda (event: EventInfo) {
112 | nonlocal click_counter;
113 | x = event.mouse_x;
114 | y = event.mouse_y;
115 | if 20 <= x <= 30 and 55 <= y <= 75 {
116 | alert("You found a secret button!");
117 | }
118 | click_counter += 1;
119 | click_display.text = f"You have clicked {click_counter} time(s).";
120 | });
121 | """,
122 | """
123 | click_counter = 0
124 | click_display = document['#clickDisplay']
125 | def __lambda0(event: EventInfo):
126 | nonlocal click_counter
127 | x = event.mouse_x
128 | y = event.mouse_y
129 | if 20 <= x <= 30 and 55 <= y <= 75:
130 | alert("You found a secret button!")
131 | click_counter += 1
132 | click_display.text = f"You have clicked {click_counter} time(s)."
133 | document.add_event_listener('click', __lambda0)
134 | """
135 | );
136 | }
137 |
138 | @Test
139 | void testMultipleLambdas() {
140 | runTest(
141 | """
142 | foo(
143 | lambda {
144 | print("Hello, world!");
145 | return 5;
146 | },
147 | lambda (x): x + 2,
148 | lambda (x: str, y: int) -> str: x * y,
149 | lambda (): 0,
150 | lambda -> str: "Hello, world!"
151 | )
152 | """,
153 | """
154 | def __lambda0():
155 | print("Hello, world!")
156 | return 5
157 | def __lambda1(x: str, y: int) -> str: return x * y
158 | def __lambda2() -> str: return "Hello, world!"
159 | foo(__lambda0, lambda x: x + 2, __lambda1, lambda: 0, __lambda2)
160 | """
161 | );
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/test/java/pyjava/TestDecorators.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import static pyjava.BasicTests.runTest;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class TestDecorators {
8 | @Test
9 | void testMultipleDecoratorsOnSameLine() {
10 | runTest(
11 | """
12 | @decorator1 @decorator2 def foo() { ... }
13 | """,
14 |
15 | """
16 | @decorator1
17 | @decorator2
18 | def foo(): ...
19 | """
20 | );
21 | }
22 |
23 | @Test
24 | void testNamedExpression() {
25 | runTest(
26 | """
27 | @x := decorator1(args) @decorator2(x)
28 | def foo() { ... }
29 | """,
30 |
31 | """
32 | @x := decorator1(args)
33 | @decorator2(x)
34 | def foo(): ...
35 | """
36 | );
37 | }
38 |
39 | @Test
40 | void testMatrixMultiplyOperatorInParens() {
41 | runTest(
42 | """
43 | @(value1 @ value2)
44 | def foo() { ... }
45 | """,
46 |
47 | """
48 | @(value1 @ value2)
49 | def foo(): ...
50 | """
51 | );
52 | }
53 |
54 | @Test
55 | void testMatrixMultiplyOperatorInIndex() {
56 | runTest(
57 | """
58 | @decorator[x @ y]
59 | def foo() { ... }
60 | """,
61 |
62 | """
63 | @decorator[x @ y]
64 | def foo(): ...
65 | """
66 | );
67 | }
68 |
69 | @Test
70 | void testMatrixMultiplyOperatorInGeneratorExpr() {
71 | runTest(
72 | """
73 | @decorator(x @ y for x, y in items)
74 | def foo() { ... }
75 | """,
76 |
77 | """
78 | @decorator(x @ y for x, y in items)
79 | def foo(): ...
80 | """
81 | );
82 | }
83 |
84 | @Test
85 | void testMatrixMultiplyOperatorInArguments() {
86 | runTest(
87 | """
88 | @decorator(x @ y, x / y)
89 | def foo() { ... }
90 | """,
91 |
92 | """
93 | @decorator(x @ y, x / y)
94 | def foo(): ...
95 | """
96 | );
97 | }
98 |
99 | @Test
100 | void testMatrixMultiplyOperatorInIfExprCondition() {
101 | runTest(
102 | """
103 | @decorator1 if x @ y else decorator2 @decorator3
104 | def foo() { ... }
105 | """,
106 |
107 | """
108 | @decorator1 if x @ y else decorator2
109 | @decorator3
110 | def foo(): ...
111 | """
112 | );
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/test/java/pyjava/TestForceParens.java:
--------------------------------------------------------------------------------
1 | package pyjava;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertThrows;
4 | import static org.junit.jupiter.params.provider.Arguments.arguments;
5 | import static pyjava.BasicTests.*;
6 |
7 | import java.util.stream.Stream;
8 |
9 | import org.antlr.v4.runtime.NoViableAltException;
10 | import org.antlr.v4.runtime.misc.ParseCancellationException;
11 | import org.junit.jupiter.api.Test;
12 | import org.junit.jupiter.params.ParameterizedTest;
13 | import org.junit.jupiter.params.provider.Arguments;
14 | import org.junit.jupiter.params.provider.MethodSource;
15 |
16 | class TestForceParens {
17 | @Test
18 | void testParensAroundCompoundStatements() {
19 | runTest(
20 | """
21 | if (condition) {
22 | doStuff1();
23 | } elif (condition2) {
24 | doStuff2();
25 | } else {
26 | doStuff3();
27 | }
28 | while (condition) {
29 | doStuff4();
30 | }
31 | for (var in exprs) {
32 | doStuff5();
33 | }
34 | with (open(filename) as file) {
35 | doStuff6();
36 | }
37 | try {
38 | doStuff7();
39 | } except (Exception as e) {
40 | doStuff8();
41 | }
42 | match (exprs) {
43 | case 0 {
44 | doStuff9();
45 | }
46 | case 1 {
47 | doStuff10();
48 | }
49 | }
50 | """,
51 | FORCE_PARENS | REQUIRE_SEMICOLONS,
52 | """
53 | if (condition):
54 | doStuff1()
55 | elif (condition2):
56 | doStuff2()
57 | else:
58 | doStuff3()
59 | while (condition):
60 | doStuff4()
61 | for var in exprs:
62 | doStuff5()
63 | with open(filename) as file:
64 | doStuff6()
65 | try:
66 | doStuff7()
67 | except Exception as e:
68 | doStuff8()
69 | match (exprs):
70 | case 0:
71 | doStuff9()
72 | case 1:
73 | doStuff10()
74 | """
75 | );
76 | }
77 |
78 | @Test
79 | void testMissingParensAroundIfStatement() {
80 | var e = assertThrows(ParseCancellationException.class, () ->
81 | runTest(
82 | """
83 | if condition {
84 | doStuff();
85 | }
86 | """,
87 | FORCE_PARENS | REQUIRE_SEMICOLONS,
88 | null
89 | )
90 | );
91 | assertException(e.getCause(), NoViableAltException.class);
92 | }
93 |
94 | @Test
95 | void testMissingParensAroundWhileLoop() {
96 | var e = assertThrows(ParseCancellationException.class, () ->
97 | runTest(
98 | """
99 | while condition {
100 | doStuff();
101 | }
102 | """,
103 | FORCE_PARENS | REQUIRE_SEMICOLONS,
104 | null
105 | )
106 | );
107 | assertException(e.getCause(), NoViableAltException.class);
108 | }
109 |
110 | @Test
111 | void testMissingParensAroundForLoop() {
112 | var e = assertThrows(ParseCancellationException.class, () ->
113 | runTest(
114 | """
115 | for var in exprs {
116 | doStuff();
117 | }
118 | """,
119 | FORCE_PARENS | REQUIRE_SEMICOLONS,
120 | null
121 | )
122 | );
123 | assertException(e.getCause(), NoViableAltException.class);
124 | }
125 |
126 | @Test
127 | void testMissingParensAroundWithStatement() {
128 | var e = assertThrows(ParseCancellationException.class, () ->
129 | runTest(
130 | """
131 | with open(filename) as file {
132 | doStuff();
133 | }
134 | """,
135 | FORCE_PARENS | REQUIRE_SEMICOLONS,
136 | null
137 | )
138 | );
139 | assertException(e.getCause(), NoViableAltException.class);
140 | }
141 |
142 | @Test
143 | void testMissingParensAroundExceptClause() {
144 | var e = assertThrows(ParseCancellationException.class, () ->
145 | runTest(
146 | """
147 | try {
148 | doStuff();
149 | } except Exception as e {
150 | handleError();
151 | }
152 | """,
153 | FORCE_PARENS | REQUIRE_SEMICOLONS,
154 | null
155 | )
156 | );
157 | assertException(e.getCause(), NoViableAltException.class);
158 | }
159 |
160 | @Test
161 | void testMissingParensAroundAssertStatement() {
162 | var e = assertThrows(ParseCancellationException.class, () ->
163 | runTest(
164 | """
165 | assert True
166 | """,
167 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
168 | null
169 | )
170 | );
171 | assertException(e.getCause(), NoViableAltException.class);
172 | }
173 |
174 | @Test
175 | void testMissingParensAroundReturnStatement() {
176 | var e = assertThrows(ParseCancellationException.class, () ->
177 | runTest(
178 | """
179 | return x
180 | """,
181 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
182 | null
183 | )
184 | );
185 | assertException(e.getCause(), NoViableAltException.class);
186 | }
187 |
188 | @Test
189 | void testMissingParensAroundRaiseStatement() {
190 | var e = assertThrows(ParseCancellationException.class, () ->
191 | runTest(
192 | """
193 | raise Exception
194 | """,
195 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
196 | null
197 | )
198 | );
199 | assertException(e.getCause(), NoViableAltException.class);
200 | }
201 |
202 | @Test
203 | void testMissingParensAroundDelStatement() {
204 | var e = assertThrows(ParseCancellationException.class, () ->
205 | runTest(
206 | """
207 | del x.y
208 | """,
209 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
210 | null
211 | )
212 | );
213 | assertException(e.getCause(), NoViableAltException.class);
214 | }
215 |
216 | @Test
217 | void testMissingParensAroundYieldStatement() {
218 | var e = assertThrows(ParseCancellationException.class, () ->
219 | runTest(
220 | """
221 | yield z
222 | """,
223 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
224 | null
225 | )
226 | );
227 | assertException(e.getCause(), NoViableAltException.class);
228 | }
229 |
230 | @Test
231 | void testParensAroundSimpleStatements() {
232 | // Note: the match statement below is actually
233 | // testing for parentheses around the case patterns.
234 | runTest(
235 | """
236 | return
237 | return (x)
238 | yield
239 | yield from (y)
240 | raise
241 | raise (Exception)
242 | assert (condition)
243 | assert (condition, )
244 | assert (condition, "message")
245 | del (x.y)
246 | match (x) {
247 | case (0) {}
248 | case (y) {}
249 | }
250 | """,
251 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
252 | """
253 | return
254 | return (x)
255 | yield
256 | yield from (y)
257 | raise
258 | raise (Exception)
259 | assert (condition)
260 | assert (condition)
261 | assert (condition), ("message")
262 | del x.y
263 | match (x):
264 | case 0: pass
265 | case y: pass
266 | """
267 | );
268 | }
269 |
270 | @ParameterizedTest
271 | @MethodSource
272 | void testAssertParens(int flags, String expectedOutput) {
273 | runTest(
274 | """
275 | assert (condition)
276 | assert (condition,)
277 | assert (condition, "message")
278 | """,
279 | flags,
280 | expectedOutput
281 | );
282 | }
283 |
284 | static Stream testAssertParens() {
285 | return Stream.of(
286 | arguments(
287 | FORCE_PARENS | FORCE_PARENS_IN_RETURN | OPTIONAL_SEMICOLONS,
288 | """
289 | assert (condition)
290 | assert (condition)
291 | assert (condition), ("message")
292 | """
293 | ),
294 | arguments(
295 | OPTIONAL_SEMICOLONS,
296 | """
297 | assert (condition)
298 | assert (condition,)
299 | assert (condition, "message")
300 | """
301 | )
302 | );
303 | }
304 | }
305 |
--------------------------------------------------------------------------------
/tool-tests/1/expected/main.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template, request, redirect, session
2 | app = Flask(__name__)
3 | app.secret_key = "ILoveBraces"
4 |
5 | @app.route('/')
6 | def index():
7 | try:
8 | session['counter'] += 1
9 | except:
10 | session['counter'] = 0
11 | return render_template('index.html')
12 |
13 | @app.route('/add', methods=["POST"])
14 | def add():
15 | try:
16 | session['counter'] += 2
17 | except:
18 | session['counter'] = 0
19 | return render_template('index.html')
20 |
21 | @app.route('/rest', methods=["POST"])
22 | def reset():
23 | session['counter'] = 0
24 | return redirect('/')
25 |
26 | app.run(debug=True)
--------------------------------------------------------------------------------
/tool-tests/1/expected/utils/points.py:
--------------------------------------------------------------------------------
1 | from typing import NamedTuple
2 |
3 | class Point2d(NamedTuple):
4 | x: int
5 | y: int
6 |
7 | class Point3d(NamedTuple):
8 | x: int
9 | y: int
10 | z: int
11 |
12 | def make_point_3d(arg) -> Point3d:
13 | match (arg):
14 | case Point3d():
15 | return arg
16 | case (int(x), int(y), int(z)):
17 | return Point3d(x, y, z)
18 | case (int(x), int(y)):
19 | return Point3d(x, y, 0)
20 | case _:
21 | raise ValueError(f"Cannot convert {arg!r} to Point3d")
22 |
--------------------------------------------------------------------------------
/tool-tests/1/input/main.pyj:
--------------------------------------------------------------------------------
1 | from flask import Flask,
2 | render_template,
3 | request,
4 | redirect,
5 | session;
6 | app = Flask(__name__);
7 | app.secret_key = "ILoveBraces";
8 |
9 | @app.route('/')
10 | def index() {
11 | try {
12 | session['counter'] += 1;
13 | } except {
14 | session['counter'] = 0;
15 | }
16 | return render_template('index.html');
17 | }
18 |
19 | @app.route('/add', methods = ["POST"])
20 | def add() {
21 | try {
22 | session['counter'] += 2;
23 | } except {
24 | session['counter'] = 0;
25 | }
26 | return render_template('index.html');
27 | }
28 |
29 | @app.route('/rest', methods = ["POST"])
30 | def reset() {
31 | session['counter'] = 0;
32 | return redirect('/');
33 | }
34 |
35 | app.run(debug=True);
36 |
--------------------------------------------------------------------------------
/tool-tests/1/input/utils/points.pyj:
--------------------------------------------------------------------------------
1 | from typing import NamedTuple;
2 |
3 | class Point2d(NamedTuple) {
4 | x: int;
5 | y: int;
6 | }
7 |
8 | class Point3d(NamedTuple) {
9 | x: int;
10 | y: int;
11 | z: int;
12 | }
13 |
14 | def make_point_3d(arg) -> Point3d {
15 | match (arg) {
16 | case Point3d() {
17 | return arg;
18 | }
19 | case (int(x), int(y), int(z)) {
20 | return Point3d(x, y, z);
21 | }
22 | case (int(x), int(y)) {
23 | return Point3d(x, y, 0);
24 | }
25 | case _ {
26 | raise ValueError(f"Cannot convert {arg!r} to Point3d");
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/tool-tests/runtests.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/bash
2 | pushd $(dirname -- "$0") 1> /dev/null
3 | testCount=0
4 | failCount=0
5 | fail(){
6 | echo "Test failed: $1" 1>&2
7 | ((failCount++))
8 | }
9 | for testName in $(find -mindepth 1 -maxdepth 1 -type d); do
10 | ((testCount++))
11 | pushd $testName 1> /dev/null
12 | java -jar ../../target/pyjava-2.0.jar input/ --output output/
13 | if [ $? -ne 0 ]; then
14 | fail $testName
15 | continue
16 | fi
17 | diff --brief --recursive --text --ignore-trailing-space --ignore-blank-lines output/ expected/
18 | if [ $? -ne 0 ]; then
19 | rm -rf output/
20 | fail $testName
21 | fi
22 | rm -rf output/
23 | popd 1> /dev/null
24 | done
25 |
26 | echo "Ran $testCount tests: $((testCount - failCount)) passed, $failCount failed."
--------------------------------------------------------------------------------