├── .github
└── FUNDING.yml
├── CMakeLists.txt
├── LICENSE
├── eci.c
├── parse.c
├── parse.h
├── utils.c
└── utils.h
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: TheDcoder
2 | liberapay: DcodingTheWeb
3 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.0)
2 |
3 | # Define the project and executable
4 | project(EasyCodeIt C)
5 | add_executable(eci utils.c parse.c eci.c)
6 |
7 | # Enable warnings
8 | if(CMAKE_COMPILER_IS_GNUCC)
9 | add_compile_options(-Wall -Wpedantic -Wextra -Wshadow -Wno-maybe-uninitialized -Wno-parentheses)
10 | if(CMAKE_BUILD_TYPE STREQUAL "Debug")
11 | message(STATUS "Adding address and undefined sanitzers")
12 | add_compile_options(-fsanitize=undefined,address)
13 | endif()
14 | endif()
15 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/eci.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of EasyCodeIt.
3 | *
4 | * Copyright (C) 2020 TheDcoder
5 | *
6 | * EasyCodeIt is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #include
21 | #include
22 | #include
23 | #include "utils.h"
24 | #include "parse.h"
25 |
26 | int main(int argc, char *argv[]) {
27 | if (argc < 2) die("No arguments!");
28 |
29 | // Open the source file
30 | FILE *source_file = fopen(argv[1], "r");
31 | if (!source_file) die("Can't open source file! :(");
32 |
33 | // Read the source file
34 | char *code = readfile(source_file);
35 | if (!code) die("Failed to read from source file!");
36 |
37 | // Parse the code
38 | parse(code);
39 |
40 | // Free the resources
41 | free(code);
42 | fclose(source_file);
43 |
44 | return EXIT_SUCCESS;
45 | }
46 |
--------------------------------------------------------------------------------
/parse.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of EasyCodeIt.
3 | *
4 | * Copyright (C) 2020 TheDcoder
5 | *
6 | * EasyCodeIt is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #define _GNU_SOURCE /* Required to enable (v)asprintf */
21 |
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include "parse.h"
31 | #include "utils.h"
32 |
33 | const char CHR_COMMENT = ';';
34 | const char CHR_DIRECTIVE = '#';
35 | const char CHR_MACRO = '@';
36 | const char CHR_VARIABLE = '$';
37 | const char CHR_DOT = '.';
38 | const char CHR_COMMA = ',';
39 |
40 | char CHRSET_WHITESPACE[] = {' ', '\t', '\r', '\n'};
41 | char CHRSET_QUOTE[] = {'\'', '"'};
42 | char CHRSET_OPERATOR[] = {
43 | '+', '-', '*', '/', '^',
44 | '&',
45 | '=', '<', '>',
46 | '?', ':',
47 | };
48 | char CHRSET_OPERATOR_EQUABLE[] = {'+', '-', '*', '/', '^', '&', '='};
49 | char CHRSET_BRACKET[] = {'[', ']', '(', ')'};
50 |
51 | char STRING_CS[] = "cs";
52 | char STRING_CE[] = "ce";
53 | char STRING_COMMENT_START[] = "comments-start";
54 | char STRING_COMMENT_END[] = "comments-end";
55 |
56 | enum Keyword KWDSET_DECLARATOR[] = {
57 | KWD_FUNC,
58 | KWD_GLOBAL,
59 | KWD_LOCAL,
60 | KWD_STATIC,
61 | KWD_CONST,
62 | };
63 |
64 | struct KeywordMap {
65 | char *string;
66 | enum Keyword symbol;
67 | };
68 |
69 | struct KeywordMap KEYWORD_MAP[] = {
70 | {"Dim", KWD_DIM},
71 | {"Local", KWD_LOCAL},
72 | {"Global", KWD_GLOBAL},
73 | {"Enum", KWD_ENUM},
74 | {"Const", KWD_CONST},
75 | {"Static", KWD_STATIC},
76 | {"ContinueCase", KWD_CONT_CASE},
77 | {"ContinueLoop", KWD_CONT_LOOP},
78 | {"Default", KWD_DEFAULT},
79 | {"Null", KWD_NULL},
80 | {"Do", KWD_DO},
81 | {"Until", KWD_UNTIL},
82 | {"While", KWD_WHILE},
83 | {"WEnd", KWD_END_WHILE},
84 | {"For", KWD_FOR},
85 | {"In", KWD_IN},
86 | {"To", KWD_TO},
87 | {"Step", KWD_STEP},
88 | {"Next", KWD_NEXT},
89 | {"Exit", KWD_EXIT},
90 | {"ExitLoop", KWD_EXITLOOP},
91 | {"Func", KWD_FUNC},
92 | {"Return", KWD_RETURN},
93 | {"EndFunc", KWD_END_FUNC},
94 | {"If", KWD_IF},
95 | {"Else", KWD_ELSE},
96 | {"ElseIf", KWD_ELSE_IF},
97 | {"EndIf", KWD_END_IF},
98 | {"ReDim", KWD_REDIM},
99 | {"Select", KWD_SELECT},
100 | {"Switch", KWD_SWITCH},
101 | {"Case", KWD_CASE},
102 | {"EndSelect", KWD_END_SELECT},
103 | {"EndSwitch", KWD_END_SWITCH},
104 | {"And", KWD_AND},
105 | {"Or", KWD_OR},
106 | {"Not", KWD_NOT},
107 | };
108 |
109 | struct {
110 | jmp_buf jump;
111 | char *msg;
112 | bool free_msg;
113 | } parse_error = {.free_msg = false};
114 |
115 | static void print_token(struct Token *token) {
116 | puts("---### TOKEN ###---");
117 | char *token_type;
118 | switch (token->type) {
119 | case TOK_UNKNOWN:
120 | token_type = "Unknown";
121 | break;
122 | case TOK_WHITESPACE:
123 | token_type = "Whitespace";
124 | break;
125 | case TOK_COMMENT:
126 | token_type = "Comment";
127 | break;
128 | case TOK_DIRECTIVE:
129 | token_type = "Directive";
130 | break;
131 | case TOK_NUMBER:
132 | token_type = "Number";
133 | break;
134 | case TOK_STRING:
135 | token_type = "String";
136 | break;
137 | case TOK_WORD:
138 | token_type = "Word";
139 | break;
140 | case TOK_MACRO:
141 | token_type = "Macro";
142 | break;
143 | case TOK_VARIABLE:
144 | token_type = "Variable";
145 | break;
146 | case TOK_OPERATOR:
147 | token_type = "Operator";
148 | break;
149 | case TOK_BRACKET:
150 | token_type = "Bracket";
151 | break;
152 | case TOK_DOT:
153 | token_type = "Dot";
154 | break;
155 | case TOK_COMMA:
156 | token_type = "Comma";
157 | break;
158 | default:
159 | token_type = "Unnamed";
160 | break;
161 | }
162 | fputs("Type: ", stdout);
163 | puts(token_type);
164 | fputs("Data: ", stdout);
165 | size_t i = 0;
166 | switch (token->type) {
167 | case TOK_WORD:
168 | if (token->keyword == KWD_NONE) goto print_raw_data;
169 | fputs("", stdout);
170 | while (KEYWORD_MAP[i].symbol != token->keyword) ++i;
171 | fputs(KEYWORD_MAP[i].string, stdout);
172 | break;
173 | default:
174 | print_raw_data:
175 | for (size_t c = 0; c < token->data_len; c++) putchar(token->data[c]);
176 | }
177 | putchar('\n');
178 | }
179 |
180 | bool parse(char *code) {
181 | if (setjmp(parse_error.jump)) return false;
182 |
183 | struct TokenList token_list = token_get_list(code);
184 | if (!token_list.length) raise_mem("generating token list");
185 | struct TokenListNode *token_list_node = token_list.head;
186 |
187 | if (token_list.dirty) fputs("!!! WARNING: Unknown token(s) encountered !!!\n", stderr);
188 | do {
189 | struct Token *token = token_list_node->token;
190 | if (token->type != TOK_WHITESPACE) print_token(token);
191 | token_list_node = token_list_node->next;
192 | } while (token_list_node);
193 | }
194 |
195 | struct Token token_get(char *code, char **next) {
196 | struct Token token = {
197 | .type = TOK_UNKNOWN,
198 | .data = NULL,
199 | .data_len = 0,
200 | .info = NULL,
201 | };
202 | size_t length;
203 | char *next_code = NULL;
204 |
205 | // Identify the token
206 | if (length = scan_string(code, char_is_whitespace)) {
207 | // Whitespace
208 | token.type = TOK_WHITESPACE;
209 | token.data = code;
210 | token.data_len = length;
211 | } else if (*code == CHR_COMMENT || *code == CHR_DIRECTIVE) {
212 | // Comment or Directive
213 | token.type = *code == CHR_COMMENT ? TOK_COMMENT : TOK_DIRECTIVE;
214 | token.data = ++code;
215 | token.data_len = scan_string(code, char_is_not_eol);
216 |
217 | // Check if this is a multi-line comment
218 | bool multiline_comment = false;
219 | if (token.type == TOK_DIRECTIVE) {
220 | bool match_short, match_long = false;
221 | match_short = strncasecmp(STRING_CS, code, (sizeof STRING_CS) - 1) == 0;
222 | if (!match_short) match_long = strncasecmp(STRING_COMMENT_START, code, (sizeof STRING_COMMENT_START) - 1) == 0;
223 | // Make sure we have a whitespace after the directive
224 | char *comment_start;
225 | if (match_long || match_short) {
226 | comment_start = code + (match_long ? sizeof STRING_COMMENT_START : sizeof STRING_CS);
227 | multiline_comment = char_is_whitespace(comment_start[-1]);
228 | }
229 | if (multiline_comment) {
230 | token.type = TOK_COMMENT;
231 | token.data = code = comment_start;
232 | }
233 | }
234 |
235 | if (multiline_comment) {
236 | // Scan for the ending directive token
237 | char *comment_end;
238 | size_t level = 1;
239 | while (true) {
240 | while (*++code != '\0') if (*code == CHR_DIRECTIVE) break;
241 | if (*code == '\0') break;
242 |
243 | bool match_short, match_long = false, match = false;
244 | bool begin = false, end = false;
245 | ++code;
246 | match_short = (
247 | (end = strncasecmp(STRING_CE, code, (sizeof STRING_CE) - 1) == 0)
248 | ||
249 | (begin = strncasecmp(STRING_CS, code, (sizeof STRING_CE) - 1) == 0)
250 | );
251 | if (!match_short) match_long = (
252 | (end = strncasecmp(STRING_COMMENT_END, code, (sizeof STRING_COMMENT_END) - 1) == 0)
253 | ||
254 | (begin = strncasecmp(STRING_COMMENT_START, code, (sizeof STRING_COMMENT_START) - 1) == 0)
255 | );
256 | // Make sure we have a whitespace after the directive
257 | if (match_long || match_short) {
258 | comment_end = code + ((match_long ? sizeof STRING_COMMENT_END : sizeof STRING_CE) - 1);
259 | match = char_is_whitespace(*comment_end);
260 | }
261 | if (match) level += begin ? +1 : -1;
262 | if (!level) break;
263 | }
264 | token.data_len = (code - token.data) - 1;
265 | next_code = comment_end;
266 | } else {
267 | token.data_len = scan_string(code, char_is_not_eol);
268 | }
269 | } else if (length = scan_number(code)){
270 | // Number
271 | token.type = TOK_NUMBER;
272 | token.data = code;
273 | token.data_len = length;
274 |
275 | // Parse the number
276 | char boundary_char = code[length];
277 | code[length] = '\0';
278 | token.number = strtod(code, NULL);
279 | code[length] = boundary_char;
280 | } else if (chrcmp(*code, CHRSET_QUOTE, sizeof CHRSET_QUOTE)) {
281 | // String
282 | token.type = TOK_STRING;
283 | token.quote = *code;
284 | token.data = code + 1;
285 | for (token.data_len = 0; token.data[token.data_len] != '\0' && (token.data[token.data_len] != token.quote || (token.data[token.data_len + 1] == token.quote ? ++token.data_len : false)); ++token.data_len);
286 | next_code = token.data + token.data_len + 1;
287 | } else if (length = scan_string(code, char_is_alphanum)){
288 | // Word
289 | token.type = TOK_WORD;
290 | token.data = code;
291 | token.data_len = length;
292 | token.keyword = KWD_NONE;
293 |
294 | // Identify keywords
295 | for (size_t i = 0; i < sizeof KEYWORD_MAP / sizeof(struct KeywordMap); ++i) if (strncmp(KEYWORD_MAP[i].string, code, length) == 0) {
296 | token.info = &(KEYWORD_MAP[i].symbol);
297 | token.keyword = KEYWORD_MAP[i].symbol;
298 | break;
299 | }
300 |
301 | // Special: Convert "And" and "Or" to operators
302 | if (token.keyword == KWD_AND) {
303 | token.type = TOK_OPERATOR;
304 | token.op_info.sym = OPR_AND;
305 | token.op_info.op = OP_AND;
306 | } else if (token.keyword == KWD_OR) {
307 | token.type = TOK_OPERATOR;
308 | token.op_info.sym = OPR_OR;
309 | token.op_info.op = OP_OR;
310 | }
311 | } else if (*code == CHR_MACRO || *code == CHR_VARIABLE){
312 | // Macro or Variable
313 | token.type = *code == CHR_MACRO ? TOK_MACRO : TOK_VARIABLE;
314 | token.data = ++code;
315 | token.data_len = scan_string(code, char_is_alphanum);
316 | } else if (char_is_opsym(*code)) {
317 | // Operator
318 | token.type = TOK_OPERATOR;
319 | token.data = code;
320 | token.op_info.sym = opsym_to_opr(*code);
321 |
322 | // Include the trailing `=` if possible
323 | bool equable = code[1] == '=' && chrcmp(*code, CHRSET_OPERATOR_EQUABLE, sizeof CHRSET_OPERATOR_EQUABLE);
324 | if (equable) {
325 | token.data_len = 2;
326 | //token.equal_op = token.op;
327 | token.op_info.sym = OPR_EQU;
328 | token.op_info.op = OP_EQU;
329 | } else {
330 | token.data_len = 1;
331 | }
332 |
333 | // Assign the operation
334 | if (equable) {
335 | enum Operator equal_opr = opsym_to_opr(code[1]);
336 | token.op_info.equal_op = opr_to_op(equal_opr);
337 | } else {
338 | token.op_info.op = opr_to_op(token.op_info.sym);
339 | }
340 |
341 | // Assign the precedence
342 | token.op_info.precedence = op_to_precedence(token.op_info.op);
343 | } else if (char_is_bracket(*code)) {
344 | // Bracket (Parenthesis)
345 | token.type = TOK_BRACKET;
346 | token.data = code;
347 | token.data_len = 1;
348 | } else if (*code == CHR_DOT) {
349 | // Dot (Full Stop)
350 | token.type = TOK_DOT;
351 | token.data = code;
352 | token.data_len = 1;
353 | } else if (*code == CHR_COMMA) {
354 | // Comma
355 | token.type = TOK_COMMA;
356 | token.data = code;
357 | token.data_len = 1;
358 | } else {
359 | // Unknown
360 | token.data = code;
361 | token.data_len = 1;
362 | }
363 |
364 | // Set the next code
365 | if (next_code) {
366 | *next = *next_code == '\0' ? NULL : next_code;
367 | } else {
368 | code += token.data_len;
369 | *next = *code == '\0' ? NULL : code;
370 | }
371 |
372 | // Return the token
373 | return token;
374 | }
375 |
376 | struct TokenList token_get_list(char *code) {
377 | struct TokenList list = {.length = 0, .dirty = false};
378 |
379 | while (code) {
380 | struct Token *token = malloc(sizeof(struct Token));
381 | if (!token) goto end;
382 |
383 | *token = token_get(code, &code);
384 | if (token->type == TOK_UNKNOWN) list.dirty = true;
385 |
386 | struct TokenListNode *new_node = malloc(sizeof(struct TokenListNode));
387 | if (!new_node) goto end;
388 | if (list.tail) {
389 | list.tail->next = new_node;
390 | new_node->prev = list.tail;
391 | list.tail = new_node;
392 | } else {
393 | list.head = new_node;
394 | list.tail = new_node;
395 | new_node->prev = NULL;
396 | }
397 | new_node->token = token;
398 | new_node->next = NULL;
399 | list.length += 1;
400 | }
401 |
402 | end: return list;
403 | };
404 |
405 | struct Token *token_list_to_array(struct TokenList *list, bool pad) {
406 | struct Token *tokens = malloc(sizeof(struct Token) * (list->length + (pad ? 2 : 0)));
407 | if (!tokens) return NULL;
408 | if (pad) /* Reserve first element for padding */ ++tokens;
409 |
410 | struct TokenListNode *node = list->head;
411 | for (size_t i = 0; i < list->length; ++i) {
412 | tokens[i] = *node->token;
413 | node = node->next;
414 | }
415 |
416 | if (pad) {
417 | // Apply padding
418 | //struct Token padding = {.type = TOK_EOF};
419 | tokens[list->length] = (struct Token){
420 | .type = TOK_EOF,
421 | .data = list->tail->token->data + list->tail->token->data_len,
422 | .data_len = 0,
423 | };
424 | *--tokens = (struct Token){
425 | .type = TOK_EOF,
426 | .data = list->head->token->data,
427 | .data_len = 0,
428 | };
429 | }
430 |
431 | return tokens;
432 | }
433 |
434 | enum Operator opsym_to_opr(char sym) {
435 | enum Operator opr = OPR_ERR;
436 | switch (sym) {
437 | case '+':
438 | opr = OPR_ADD;
439 | break;
440 | case '-':
441 | opr = OPR_SUB;
442 | break;
443 | case '*':
444 | opr = OPR_MUL;
445 | break;
446 | case '/':
447 | opr = OPR_DIV;
448 | break;
449 | case '^':
450 | opr = OPR_EXP;
451 | break;
452 | case '&':
453 | opr = OPR_CAT;
454 | break;
455 | case '=':
456 | opr = OPR_EQU;
457 | break;
458 | case '<':
459 | opr = OPR_LES;
460 | break;
461 | case '>':
462 | opr = OPR_GRT;
463 | break;
464 | case '?':
465 | opr = OPR_CON_MRK;
466 | break;
467 | case ':':
468 | opr = OPR_CON_SEP;
469 | break;
470 | }
471 | return opr;
472 | }
473 |
474 | enum Operation opr_to_op(enum Operator opr) {
475 | enum Operation op = OP_ERR;
476 | switch (opr) {
477 | case OPR_ADD:
478 | op = OP_ADD;
479 | break;
480 | case OPR_SUB:
481 | op = OP_SUB;
482 | break;
483 | case OPR_MUL:
484 | op = OP_MUL;
485 | break;
486 | case OPR_DIV:
487 | op = OP_DIV;
488 | break;
489 | case OPR_EXP:
490 | op = OP_EXP;
491 | break;
492 | case OPR_CAT:
493 | op = OP_CAT;
494 | break;
495 | case OPR_EQU:
496 | op = OP_EQU;
497 | break;
498 | case OPR_LES:
499 | op = OP_LT;
500 | break;
501 | case OPR_GRT:
502 | op = OP_GT;
503 | break;
504 | case OPR_CON_MRK:
505 | case OPR_CON_SEP:
506 | op = OP_CON;
507 | break;
508 | case OPR_AND:
509 | op = OP_AND;
510 | break;
511 | case OPR_OR:
512 | op = OP_OR;
513 | break;
514 | }
515 | return op;
516 | }
517 |
518 | int op_to_precedence(enum Operation op) {
519 | int p = 0; // Precedence
520 |
521 | switch (op) {
522 | case OP_INV:
523 | return p;
524 | }
525 | ++p;
526 |
527 | switch (op) {
528 | case OP_NOT:
529 | return p;
530 | }
531 | ++p;
532 |
533 | switch (op) {
534 | case OP_EXP:
535 | return p;
536 | }
537 | ++p;
538 |
539 | switch (op) {
540 | case OP_MUL:
541 | case OP_DIV:
542 | return p;
543 | }
544 | ++p;
545 |
546 | switch (op) {
547 | case OP_ADD:
548 | case OP_SUB:
549 | return p;
550 | }
551 | ++p;
552 |
553 | switch (op) {
554 | case OP_CAT:
555 | return p;
556 | }
557 | ++p;
558 |
559 | switch (op) {
560 | case OP_LT:
561 | case OP_GT:
562 | case OP_LTE:
563 | case OP_GTE:
564 | case OP_EQU:
565 | case OP_NEQ:
566 | case OP_SEQU:
567 | return p;
568 | }
569 | ++p;
570 |
571 | switch (op) {
572 | case OP_AND:
573 | case OP_OR:
574 | return p;
575 | }
576 | ++p;
577 |
578 | switch (op) {
579 | case OP_CON:
580 | return p;
581 | }
582 |
583 | return -1;
584 | }
585 |
586 | size_t scan_number(char *str) {
587 | size_t len = scan_string(str, char_is_num);
588 | if (len == 1 && chrcmp(str[1], "xX", 2)) {
589 | // Hexadecimal
590 | len += 1 + scan_string(str + len + 1, char_is_hexnum);
591 | } else {
592 | if (str[len] == '.') len += 1 + scan_string(str + len + 1, char_is_num); // Fraction
593 | if (chrcmp(str[len], "eE", 2)) {
594 | // Exponent (scientific notation)
595 | if (str[++len] == '-') ++len; // Negative exponent
596 | len += scan_string(str + len, char_is_num);
597 | }
598 | }
599 | return len;
600 | }
601 |
602 | size_t scan_string(char *str, bool (cmpfunc)(char)) {
603 | size_t len = 0;
604 | while (true) {
605 | if (!cmpfunc(*str)) break;
606 | ++len; ++str;
607 | }
608 | return len;
609 | }
610 |
611 | bool char_is_whitespace(char chr) {
612 | return chrcmp(chr, CHRSET_WHITESPACE, sizeof CHRSET_WHITESPACE);
613 | }
614 |
615 | bool char_is_alpha(char chr) {
616 | return isalpha(chr);
617 | }
618 |
619 | bool char_is_num(char chr) {
620 | return isdigit(chr);
621 | }
622 |
623 | bool char_is_alphanum(char chr) {
624 | return char_is_alpha(chr) || char_is_num(chr) || chr == '_';
625 | }
626 |
627 | bool char_is_hexnum(char chr) {
628 | return char_is_num(chr) || chrcmp(chr, "ABCDEFabcdef", 12);
629 | }
630 |
631 | bool char_is_opsym(char chr) {
632 | return chrcmp(chr, CHRSET_OPERATOR, sizeof CHRSET_OPERATOR);
633 | }
634 |
635 | bool char_is_bracket(char chr) {
636 | return chrcmp(chr, CHRSET_BRACKET, sizeof CHRSET_BRACKET);
637 | }
638 |
639 | bool char_is_not_eol(char chr) {
640 | return chr != '\n' && chr != '\0';
641 | }
642 |
643 | struct Primitive primitive_get(struct Token *token) {
644 | struct Primitive value;
645 |
646 | switch (token->type) {
647 | case TOK_NUMBER:
648 | value.type = PRI_NUMBER;
649 | value.number = token->number;
650 | break;
651 | case TOK_STRING:
652 | value.type = PRI_STRING;
653 | value.string = malloc(token->data_len + 1);
654 | strncpy(value.string, token->data, token->data_len);
655 | break;
656 | case TOK_BOOL:
657 | // FIXME: Parse booleans
658 | break;
659 | }
660 |
661 | return value;
662 | }
663 |
664 | bool kwd_is_declarator(enum Keyword kwd) {
665 | for (size_t i = 0; i < lenof(KWDSET_DECLARATOR); ++i) {
666 | if (kwd == KWDSET_DECLARATOR[i]) return true;
667 | }
668 | return false;
669 | }
670 |
671 | struct Expression expression_get(struct Token *tokens, size_t count) {
672 | struct Expression expression = {.op = OP_NOP};
673 |
674 | // Calculate the number of actual tokens (anything not a whitespace)
675 | size_t actual_count = 0;
676 | struct Token *actual_tokens = tokens;
677 | for (size_t i = 0; i < count; ++i) if (tokens[i].type != TOK_WHITESPACE) ++actual_count;
678 | if (actual_count == count) goto skip_strip;
679 |
680 | // Allocate a new array with only actual tokens
681 | actual_tokens = malloc(sizeof(struct Token) * actual_count);
682 | if (!actual_tokens) raise_mem("collecting actual tokens");
683 | size_t actual_i = 0;
684 | for (size_t i = 0; i < count; ++i) if (tokens[i].type != TOK_WHITESPACE) actual_tokens[actual_i++] = tokens[i];
685 | skip_strip:;
686 |
687 | enum Precedence precedence = PRE__START;
688 | bool success;
689 | do {
690 | success = expression_parse(actual_tokens, actual_count, --precedence, &expression);
691 | if (expression.op == OP_ERR) raise_error("Unable to parse expression", false);
692 | } while (!success);
693 |
694 | return expression;
695 | }
696 |
697 | bool expression_parse(struct Token *token, size_t count, enum Precedence precedence, struct Expression *expression) {
698 | static char *err_mem_ctx = "parsing expression";
699 |
700 | size_t operand_count = 2;
701 | if (count == 1) {
702 | expression->op = OP_NOP;
703 |
704 | struct Operand *term = malloc(sizeof(struct Operand));
705 | if (!term) raise_mem(err_mem_ctx);
706 | term->type = OPE_PRIMITIVE;
707 |
708 | term->value = malloc(sizeof(struct Primitive));
709 | if (!term->value) raise_mem(err_mem_ctx);
710 | *term->value = primitive_get(token);
711 |
712 | expression->operands = term;
713 | } else {
714 | struct Token *op_token;
715 | switch (precedence) {
716 | case PRE_INV:
717 | if (token->type != TOK_OPERATOR || token->op_info.sym != OPR_SUB) return false;
718 | expression->op = OP_INV;
719 | expression->operands = expression_alloc_operands(operand_count = 1);
720 | *expression->operands[0].expression = expression_get(token + 1, count - 1);
721 | break;
722 | case PRE_NEG:
723 | if (token->type != TOK_WORD || token->keyword != KWD_NOT) return false;
724 | expression->op = OP_NOT;
725 | expression->operands = expression_alloc_operands(operand_count = 1);
726 | *expression->operands[0].expression = expression_get(token + 1, count - 1);
727 | break;
728 | case PRE_EXP:
729 | op_token = expression_parse_infix_binary(token, count, (enum Operator []){OPR_EXP}, 1, false, expression);
730 | if (!op_token) return false;
731 | break;
732 | case PRE_MUL_DIV:
733 | op_token = expression_parse_infix_binary(token, count, (enum Operator []){OPR_MUL, OPR_DIV}, 2, true, expression);
734 | if (!op_token) return false;
735 | break;
736 | case PRE_ADD_SUB:
737 | op_token = expression_parse_infix_binary(token, count, (enum Operator []){OPR_ADD, OPR_SUB}, 2, true, expression);
738 | if (!op_token) return false;
739 | break;
740 | case PRE_CAT:
741 | op_token = expression_parse_infix_binary(token, count, (enum Operator []){OPR_CAT}, 1, true, expression);
742 | if (!op_token) return false;
743 | break;
744 | case PRE_COMP:
745 | op_token = expression_parse_comp(token, count, expression);
746 | if (!op_token) return false;
747 | break;
748 | case PRE_CONJ:
749 | op_token = expression_parse_infix_binary(token, count, (enum Operator []){OPR_AND, OPR_OR}, 2, true, expression);
750 | if (!op_token) return false;
751 | break;
752 | case PRE_ASS:
753 | op_token = expression_parse_assign(token, count, expression);
754 | if (!op_token) return false;
755 | break;
756 | default:
757 | expression->op = OP_ERR;
758 | return false;
759 | }
760 |
761 | // Flatten expression operands
762 | for (size_t i = 0; i < operand_count; ++i) {
763 | if (expression->operands[i].expression->op == OP_NOP) {
764 | struct Expression *wrapped_expression = expression->operands[i].expression;
765 | expression->operands[i] = wrapped_expression->operands[0];
766 | free(wrapped_expression);
767 | }
768 | }
769 | }
770 |
771 | return true;
772 | }
773 |
774 | struct Token *expression_parse_infix_binary(struct Token *tokens, size_t count, enum Operator opr_list[], size_t opr_count, bool left, struct Expression *expression) {
775 | if (count < 3) return false;
776 | struct Token *op_token = find_token_by_opr(tokens, count, opr_list, opr_count, left);
777 | if (!op_token) return NULL;
778 | expression->op = opr_to_op(op_token->op_info.sym);
779 | expression->operands = expression_alloc_operands(2);
780 | *expression->operands[0].expression = expression_get(tokens, op_token - tokens);
781 | *expression->operands[1].expression = expression_get(op_token + 1, count - (op_token - tokens) - 1);
782 | return op_token;
783 | }
784 |
785 | struct Token *expression_parse_comp(struct Token *tokens, size_t count, struct Expression *expression) {
786 | if (count < 3) return false;
787 | struct Token *op_token = find_token_by_opr(tokens, count, (enum Operator []){OPR_GRT, OPR_LES, OPR_EQU}, 3, true);
788 | if (!op_token) return false;
789 | if (op_token == tokens || op_token == &tokens[count - 1]) return false;
790 |
791 | bool dual_token = op_token[1].type == TOK_OPERATOR;
792 | if (dual_token) {
793 | // Dual-token operator
794 | dual_token = true;
795 | if (op_token[1].op_info.sym == OPR_EQU) {
796 | switch (op_token->op_info.sym) {
797 | case OPR_EQU:
798 | // Strictly equal to
799 | expression->op = OP_SEQU;
800 | break;
801 | case OPR_GRT:
802 | // Greater than or equal to
803 | expression->op = OP_GTE;
804 | break;
805 | case OPR_LES:
806 | // Lesser than or equal to
807 | expression->op = OP_LTE;
808 | break;
809 | default:
810 | return NULL;
811 | }
812 | } else if (op_token->op_info.sym == OPR_LES && op_token[1].op_info.sym == OPR_GRT) {
813 | // Inequality
814 | expression->op = OP_NEQ;
815 | } else return NULL;
816 |
817 | expression->operands = expression_alloc_operands(2);
818 | *expression->operands[0].expression = expression_get(tokens, op_token - tokens);
819 | *expression->operands[1].expression = expression_get(op_token + 2, count - ((op_token + 1) - tokens) - 1);
820 | } else {
821 | switch (op_token->op_info.sym) {
822 | case OPR_EQU:
823 | // Equal to
824 | expression->op = OP_SEQU;
825 | break;
826 | case OPR_GRT:
827 | // Greater than
828 | expression->op = OP_GT;
829 | break;
830 | case OPR_LES:
831 | // Lesser than
832 | expression->op = OP_LT;
833 | break;
834 | default:
835 | return NULL;
836 | }
837 | }
838 |
839 | expression->operands = expression_alloc_operands(2);
840 | *expression->operands[0].expression = expression_get(tokens, op_token - tokens);
841 | if (dual_token) op_token += 1;
842 | *expression->operands[1].expression = expression_get(op_token + 1, count - (op_token - tokens) - 1);
843 |
844 | return op_token;
845 | }
846 |
847 | struct Token *expression_parse_assign(struct Token *tokens, size_t count, struct Expression *expression) {
848 | struct Token *op_token = expression_parse_infix_binary(tokens, count, &(enum Operator){OPR_EQU}, 1, false, expression);
849 |
850 | if (op_token->op_info.equal_op != OP_EQU) {
851 | // Modify the expression to add the pre-assignment operation
852 | struct Operand original = expression->operands[1];
853 |
854 | expression->operands[1].type = OPE_EXPRESSION;
855 | struct Expression *pre_exp = malloc(sizeof(struct Expression));
856 | if (!pre_exp) raise_mem("parsing assignment expression");
857 | expression->operands[1].expression = pre_exp;
858 |
859 | pre_exp->op = op_token->op_info.equal_op;
860 | pre_exp->operands = expression_alloc_operands(2);
861 | pre_exp->operands[0] = expression->operands[0];
862 | pre_exp->operands[1] = original;
863 | }
864 |
865 | return op_token;
866 | }
867 |
868 | struct Operand *expression_alloc_operands(size_t count) {
869 | static char *err_mem_ctx = "adding operands to an operation";
870 |
871 | // Allocate space for operand array
872 | struct Operand *operands = malloc(sizeof(struct Operand) * count);
873 | if (!operands) raise_mem(err_mem_ctx);
874 |
875 | // Initialize each element with an empty expression
876 | for (size_t i = 0; i < count; ++i) {
877 | operands[i].type = OPE_EXPRESSION;
878 | operands[i].expression = malloc(sizeof(struct Expression));
879 | if (!operands[i].expression) raise_mem(err_mem_ctx);
880 | }
881 | return operands;
882 | }
883 |
884 | struct Token *find_token_by_opr(struct Token *tokens, size_t count, enum Operator opr_list[], size_t opr_count, bool left) {
885 | size_t open_brackets = 0;
886 | size_t i = left ? 0 : count - 1;
887 | while (true) {
888 | if (tokens[i].type == TOK_BRACKET && tokens[i].data[0] == '(') {
889 | ++open_brackets;
890 | goto next;
891 | }
892 | if (open_brackets) {
893 | if (tokens[i].type == TOK_BRACKET && tokens[i].data[0] == ')') --open_brackets;
894 | goto next;
895 | }
896 | if (tokens[i].type == TOK_OPERATOR) {
897 | for (size_t opr = 0; opr < opr_count; ++opr) if (tokens[i].op_info.sym == opr_list[opr]) return tokens + i;
898 | }
899 |
900 | // Iterate
901 | next: if (left) {if (i == count) break; ++i;} else {if (i == 0) break; --i;}
902 | }
903 | return NULL;
904 | }
905 |
906 | noreturn void raise_error(char *msg, bool free_msg) {
907 | if (parse_error.free_msg && parse_error.msg) free(parse_error.msg);
908 |
909 | parse_error.msg = msg;
910 | parse_error.free_msg = free_msg;
911 |
912 | longjmp(parse_error.jump, true);
913 | }
914 |
915 | noreturn void raise_error_fmt(char *def, char *fmt, ...) {
916 | va_list args;
917 | va_start(args, fmt);
918 |
919 | char *msg;
920 | int result = vasprintf(&msg, fmt, args);
921 | if (result == -1) msg = def;
922 |
923 | va_end(args);
924 |
925 | raise_error(msg, result != -1);
926 | }
927 |
928 | noreturn void raise_mem(char *context) {
929 | char *msg = "Failed to allocate memory";
930 | if (context) {
931 | raise_error_fmt(msg, "%s when %s", msg, context);
932 | } else {
933 | raise_error(msg, false);
934 | };
935 | }
936 |
937 | noreturn void raise_unexpected_token(char *expected, struct Token *got_token) {
938 | char *def_msg = "Unexpected token encountered!";
939 |
940 | // Find line number and position
941 | size_t line_num = 0;
942 | struct Token *first_token = got_token;
943 | while (first_token[-1].type != TOK_EOF) --first_token;
944 | char *code = first_token->data;
945 | char *line_start = code;
946 | do {
947 | if (*code == '\n') {
948 | ++line_num;
949 | line_start = code + 1;
950 | }
951 | } while (++code != got_token->data);
952 |
953 | if (expected) {
954 | raise_error_fmt(def_msg,
955 | "Unexpected token encountered at %zu:%tu! Was expecting %s but instead got '%.*s'",
956 | line_num,
957 | got_token->data - line_start,
958 | expected,
959 | (int) got_token->data_len,
960 | got_token->data
961 | );
962 | } else {
963 | raise_error_fmt(def_msg,
964 | "Unexpected token encountered at %zu:%tu! Was not expecting '%.*s'",
965 | line_num,
966 | got_token->data - line_start,
967 | (int) got_token->data_len,
968 | got_token->data
969 | );
970 | }
971 | }
972 |
--------------------------------------------------------------------------------
/parse.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of EasyCodeIt.
3 | *
4 | * Copyright (C) 2020 TheDcoder
5 | *
6 | * EasyCodeIt is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #ifndef PARSE_H
21 | #define PARSE_H
22 |
23 | #include
24 | #include
25 |
26 | enum TokenType {
27 | TOK_UNKNOWN,
28 | TOK_WHITESPACE,
29 | TOK_COMMENT,
30 | TOK_DIRECTIVE,
31 | TOK_NUMBER,
32 | TOK_STRING,
33 | TOK_BOOL,
34 | TOK_WORD,
35 | TOK_MACRO,
36 | TOK_VARIABLE,
37 | TOK_OPERATOR,
38 | TOK_BRACKET,
39 | TOK_DOT,
40 | TOK_COMMA,
41 | TOK_EOF,
42 | };
43 |
44 | enum Operator {
45 | // Invalid
46 | OPR_ERR,
47 | // '+', '-', '*', '/', '^',
48 | OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_EXP,
49 | // '&',
50 | OPR_CAT,
51 | // '=', '<', '>',
52 | OPR_EQU, OPR_LES, OPR_GRT,
53 | // '?', ':',
54 | OPR_CON_MRK, OPR_CON_SEP,
55 |
56 | // Special
57 | OPR_AND, OPR_OR, // And, Or
58 | };
59 |
60 | enum Keyword {
61 | KWD_NONE, // Special: Not a keyword
62 | KWD_DIM,
63 | KWD_LOCAL,
64 | KWD_GLOBAL,
65 | KWD_ENUM,
66 | KWD_CONST,
67 | KWD_STATIC,
68 | KWD_CONT_CASE,
69 | KWD_CONT_LOOP,
70 | KWD_DEFAULT,
71 | KWD_NULL,
72 | KWD_DO,
73 | KWD_UNTIL,
74 | KWD_WHILE,
75 | KWD_END_WHILE,
76 | KWD_FOR,
77 | KWD_IN,
78 | KWD_TO,
79 | KWD_STEP,
80 | KWD_NEXT,
81 | KWD_EXIT,
82 | KWD_EXITLOOP,
83 | KWD_FUNC,
84 | KWD_RETURN,
85 | KWD_END_FUNC,
86 | KWD_IF,
87 | KWD_ELSE,
88 | KWD_ELSE_IF,
89 | KWD_END_IF,
90 | KWD_REDIM,
91 | KWD_SELECT,
92 | KWD_SWITCH,
93 | KWD_CASE,
94 | KWD_END_SELECT,
95 | KWD_END_SWITCH,
96 | KWD_AND,
97 | KWD_OR,
98 | KWD_NOT,
99 | };
100 |
101 | enum Operation {
102 | /* Error */
103 | OP_ERR,
104 |
105 | /* No Operation */
106 | OP_NOP,
107 |
108 | /* Assignment */
109 | OP_ASS,
110 |
111 | /* Invert (Additive inversion) */
112 | OP_INV,
113 |
114 | /* Addition, Substraction, Multiplcation, Division, Exponentiation */
115 | OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_EXP,
116 |
117 | /* Concatenation */
118 | OP_CAT,
119 |
120 | /* Negation, Logical "And", Logical "Or" */
121 | OP_NOT, OP_AND, OP_OR,
122 | /* Equality, Strict equality, Inequality*/
123 | OP_EQU, OP_SEQU, OP_NEQ,
124 | /* Less than, Less than or equal to, Greater than, Greater than or equal to */
125 | OP_LT, OP_LTE, OP_GT, OP_GTE,
126 |
127 | /* Conditional */
128 | OP_CON,
129 | };
130 |
131 | enum Precedence {
132 | PRE__END,
133 | PRE_INV,
134 | PRE_NEG,
135 | PRE_EXP,
136 | PRE_MUL_DIV,
137 | PRE_ADD_SUB,
138 | PRE_CAT,
139 | PRE_COMP, // Comparison
140 | PRE_CONJ, // Conjunction (Logical)
141 | PRE_ASS,
142 | PRE__START,
143 | };
144 |
145 | struct TokenOperator {
146 | enum Operator sym;
147 | enum Operation op;
148 | enum Operation equal_op; // For equable operations (+=, *=, -=, /= etc.)
149 | int precedence;
150 | };
151 |
152 | struct Token {
153 | enum TokenType type;
154 | char *data;
155 | size_t data_len;
156 | union {
157 | // Number
158 | double number;
159 |
160 | // String
161 | char quote;
162 |
163 | // Operator
164 | struct TokenOperator op_info;
165 |
166 | // Keyword
167 | enum Keyword keyword;
168 |
169 | // Generic
170 | void *info;
171 | };
172 | };
173 |
174 | struct TokenList {
175 | size_t length;
176 | struct TokenListNode *head;
177 | struct TokenListNode *tail;
178 | bool dirty;
179 | };
180 |
181 | struct TokenListNode {
182 | struct Token *token;
183 | struct TokenListNode *prev;
184 | struct TokenListNode *next;
185 | };
186 |
187 | struct Primitive {
188 | enum {
189 | PRI_NUMBER,
190 | PRI_STRING,
191 | PRI_BOOLEAN,
192 | // ...
193 | } type;
194 | union {
195 | double number;
196 | char *string;
197 | bool boolean;
198 | };
199 | };
200 |
201 | struct Expression;
202 |
203 | struct Operand {
204 | enum {
205 | OPE_PRIMITIVE,
206 | //OPE_VARIABLE,
207 | //OPE_MACRO,
208 | OPE_EXPRESSION,
209 | } type;
210 | union {
211 | struct Primitive *value;
212 | //struct Variable *variable;
213 | //struct Macro *macro;
214 | struct Expression *expression;
215 | };
216 | };
217 |
218 | struct Expression {
219 | enum Operation op;
220 | struct Operand *operands;
221 | };
222 |
223 | struct Declaration {
224 | enum {SCO_AUTO, SCO_LOCAL, SCO_GLOBAL} scope;
225 | bool is_constant : 1;
226 | bool is_static : 1;
227 | bool is_function : 1;
228 | char *name;
229 | union {
230 | // Variable or constant
231 | struct Expression *initializer;
232 | // Function
233 | struct {
234 | struct Statement *block;
235 | size_t size;
236 | } code;
237 | };
238 | };
239 |
240 | struct Statement {
241 | enum StatementType {
242 | SMT_DECLARATION,
243 | SMT_EXPRESSION,
244 | } type;
245 | union {
246 | struct Declaration *declaration;
247 | struct Expression *expression;
248 | };
249 | };
250 |
251 | struct Unit {
252 | enum UnitType {
253 | UNT_COMMENT,
254 | UNT_DIRECTIVE,
255 | UNT_STATEMENT,
256 | } type;
257 | union {
258 | struct Token *token;
259 | struct Statement *statement;
260 | };
261 | };
262 |
263 | bool parse(char *code);
264 | struct Token token_get(char *code, char **next);
265 | struct TokenList token_get_list(char *code);
266 | struct Token *token_list_to_array(struct TokenList *list, bool pad);
267 |
268 | enum Operator opsym_to_opr(char sym);
269 | enum Operation opr_to_op(enum Operator opr);
270 | int op_to_precedence(enum Operation op);
271 |
272 | size_t scan_number(char *str);
273 | size_t scan_string(char *str, bool (cmpfunc)(char));
274 |
275 | bool char_is_whitespace(char chr);
276 | bool char_is_alpha(char chr);
277 | bool char_is_num(char chr);
278 | bool char_is_alphanum(char chr);
279 | bool char_is_hexnum(char chr);
280 | bool char_is_opsym(char chr);
281 | bool char_is_bracket(char chr);
282 | bool char_is_not_eol(char chr);
283 |
284 | struct Expression expression_get(struct Token *tokens, size_t count);
285 | bool expression_parse(struct Token *token, size_t count, enum Precedence precedence, struct Expression *expression);
286 | struct Token *expression_parse_infix_binary(struct Token *tokens, size_t count, enum Operator opr_list[], size_t opr_count, bool left, struct Expression *expression);
287 | struct Token *expression_parse_comp(struct Token *tokens, size_t count, struct Expression *expression);
288 | struct Token *expression_parse_assign(struct Token *tokens, size_t count, struct Expression *expression);
289 | struct Operand *expression_alloc_operands(size_t count);
290 | struct Token *find_token_by_opr(struct Token *tokens, size_t count, enum Operator opr_list[], size_t opr_count, bool left);
291 |
292 | noreturn void raise_error(char *msg, bool free_msg);
293 | noreturn void raise_error_fmt(char *def, char *fmt, ...);
294 | noreturn void raise_mem(char *context);
295 | noreturn void raise_unexpected_token(char *expected, struct Token *got_token);
296 |
297 | #endif
298 |
--------------------------------------------------------------------------------
/utils.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of EasyCodeIt.
3 | *
4 | * Copyright (C) 2020 TheDcoder
5 | *
6 | * EasyCodeIt is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include "utils.h"
26 |
27 | bool chrcmp(char chr, char *arr, size_t arr_len) {
28 | bool present;
29 | for (size_t i = 0; i < arr_len; ++i) if (present = chr == arr[i]) break;
30 | return present;
31 | }
32 |
33 | noreturn void die(char *msg) {
34 | fputs(msg, stderr);
35 | if (*msg != '\0') fputs("\n", stderr);
36 | exit(EXIT_FAILURE);
37 | }
38 |
39 | char *readfile(FILE *file) {
40 | // Define the final buffer
41 | char *final_buffer = NULL;
42 | size_t final_size = 0;
43 |
44 | // Define and allocate the initial node
45 | struct ReadFileBufferNode *initial_node = malloc(sizeof(struct ReadFileBufferNode));
46 | if (!initial_node) return NULL;
47 |
48 | // Read the contents of file in chunks
49 | struct ReadFileBufferNode *curr_node = initial_node;
50 | struct ReadFileBufferNode *next_node;
51 | while (true) {
52 | // Copy the current chunk
53 | size_t bytes_read = fread(curr_node->buffer, 1, READ_FILE_BUFFER_SIZE, file);
54 | curr_node->data_len = bytes_read;
55 | final_size += bytes_read;
56 | if (bytes_read < READ_FILE_BUFFER_SIZE) {
57 | // Check if we have an error
58 | if (ferror(file)) goto cleanup;
59 |
60 | // Mark this node as final
61 | curr_node->next = NULL;
62 |
63 | // Break the loop
64 | break;
65 | }
66 |
67 | // Allocate the next buffer node
68 | next_node = malloc(sizeof(struct ReadFileBufferNode));
69 | if (!next_node) goto cleanup;
70 | curr_node->next = next_node;
71 | curr_node = next_node;
72 | }
73 |
74 | // Allocate the buffer
75 | final_buffer = malloc(final_size + 1);
76 | if (!final_buffer) goto cleanup;
77 | final_buffer[final_size] = '\0';
78 |
79 | // Copy data into the final buffer
80 | curr_node = initial_node;
81 | char *curr_chunk = final_buffer;
82 | do {
83 | memcpy(curr_chunk, curr_node->buffer, curr_node->data_len);
84 | curr_chunk += curr_node->data_len;
85 | curr_node = curr_node->next;
86 | } while (curr_node);
87 |
88 | // Free all nodes
89 | cleanup:
90 | curr_node = initial_node;
91 | do {
92 | next_node = curr_node->next;
93 | free(curr_node);
94 | curr_node = next_node;
95 | } while (curr_node);
96 |
97 | // Return the final buffer
98 | return final_buffer;
99 | }
100 |
--------------------------------------------------------------------------------
/utils.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is part of EasyCodeIt.
3 | *
4 | * Copyright (C) 2020 TheDcoder
5 | *
6 | * EasyCodeIt is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * This program is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #ifndef UTILS_H
21 | #define UTILS_H
22 |
23 | #include
24 | #include
25 |
26 | #ifndef READ_FILE_BUFFER_SIZE
27 | #define READ_FILE_BUFFER_SIZE 1024
28 | #endif
29 |
30 | #define lenof(array) (sizeof array / sizeof array[0])
31 |
32 | struct ReadFileBufferNode {
33 | char buffer[READ_FILE_BUFFER_SIZE];
34 | size_t data_len;
35 | struct ReadFileBufferNode *next;
36 | };
37 |
38 | bool chrcmp(char chr, char *arr, size_t arr_len);
39 | noreturn void die(char *msg);
40 | char *readfile(FILE *file);
41 |
42 | #endif
43 |
--------------------------------------------------------------------------------