Initial commit from JAPL with some changes
parent
a20cfc532b
commit
76812a2091
222
LICENSE
222
LICENSE
|
@ -1,85 +1,201 @@
|
|||
The Artistic License 2.0
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Copyright (c) 2000-2006, The Perl Foundation.
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
1. Definitions.
|
||||
|
||||
Preamble
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
Definitions
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures.
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"You" and "your" means any person who would like to copy, distribute, or modify the Package.
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version.
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization.
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees.
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
"Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
"Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
"Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future.
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
"Source" form means the source code, documentation source, and configuration files for the Package.
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
"Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form.
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
Permission for Use and Modification Without Distribution
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version.
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
Permissions for Redistribution of the Standard Version
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
(2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
(3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
Distribution of Modified Versions of the Package as Source
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
(4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following:
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
(a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version.
|
||||
(b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version.
|
||||
(c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
(i) the Original License or
|
||||
(ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed.
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
(5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license.
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
(6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version.
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Aggregating or Linking the Package
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
(7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation.
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
(8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package.
|
||||
|
||||
Items That are Not Considered Part of a Modified Version
|
||||
|
||||
(9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license.
|
||||
|
||||
General Provisions
|
||||
|
||||
(10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
|
||||
|
||||
(11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
|
||||
|
||||
(12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
|
||||
|
||||
(13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
|
||||
|
||||
(14) Disclaimer of Warranty:
|
||||
THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
|
@ -0,0 +1,196 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Implementation of a custom list data type for JAPL objects (used also internally by the VM)
|
||||
|
||||
import iterable
|
||||
import ../../memory/allocator
|
||||
import baseObject
|
||||
|
||||
import strformat
|
||||
|
||||
|
||||
type
|
||||
ArrayList*[T] = object of Iterable
|
||||
## Implementation of a simple dynamic
|
||||
## array with amortized O(1) append complexity
|
||||
## and O(1) complexity when popping/deleting
|
||||
## the last element
|
||||
container: ptr UncheckedArray[T]
|
||||
ArrayListIterator*[T] = object of Iterator
|
||||
list: ArrayList[T]
|
||||
current: int
|
||||
|
||||
|
||||
proc newArrayList*[T]: ptr ArrayList[T] =
|
||||
## Allocates a new, empty array list
|
||||
result = allocateObj(ArrayList[T], ObjectType.List)
|
||||
result.capacity = 0
|
||||
result.container = nil
|
||||
result.length = 0
|
||||
|
||||
|
||||
proc append*[T](self: ptr ArrayList[T], elem: T) =
|
||||
## Appends an object to the end of the list
|
||||
## in amortized constant time (~O(1))
|
||||
if self.capacity <= self.length:
|
||||
self.capacity = growCapacity(self.capacity)
|
||||
self.container = resizeArray(T, self.container, self.length, self.capacity)
|
||||
self.container[self.length] = elem
|
||||
self.length += 1
|
||||
|
||||
|
||||
proc pop*[T](self: ptr ArrayList[T], idx: int = -1): T =
|
||||
## Pops an item from the list. By default, the last
|
||||
## element is popped, in which case the operation's
|
||||
## time complexity is O(1). When an arbitrary element
|
||||
## is popped, the complexity rises to O(k) where k
|
||||
## is the number of elements that had to be shifted
|
||||
## by 1 to avoid empty slots
|
||||
var idx = idx
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, "pop from empty ArrayList")
|
||||
if idx == -1:
|
||||
idx = self.length - 1
|
||||
if idx notin 0..self.length - 1:
|
||||
raise newException(IndexDefect, &"ArrayList index out of bounds: {idx} notin 0..{self.length - 1}")
|
||||
result = self.container[idx]
|
||||
if idx != self.length - 1:
|
||||
for i in countup(idx, self.length - 1):
|
||||
self.container[i] = self.container[i + 1]
|
||||
self.capacity -= 1
|
||||
self.length -= 1
|
||||
|
||||
|
||||
proc `[]`*[T](self: ptr ArrayList[T], idx: int): T =
|
||||
## Retrieves an item from the list, in constant
|
||||
## time
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, &"ArrayList index out of bounds: : {idx} notin 0..{self.length - 1}")
|
||||
if idx notin 0..self.length - 1:
|
||||
raise newException(IndexDefect, &"ArrayList index out of bounds: {idx} notin 0..{self.length - 1}")
|
||||
result = self.container[idx]
|
||||
|
||||
|
||||
proc `[]`*[T](self: ptr ArrayList[T], slice: Hslice[int, int]): ptr ArrayList[T] =
|
||||
## Retrieves a subset of the list, in O(k) time where k is the size
|
||||
## of the slice
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, "ArrayList index out of bounds")
|
||||
if slice.a notin 0..self.length - 1 or slice.b notin 0..self.length:
|
||||
raise newException(IndexDefect, "ArrayList index out of bounds")
|
||||
result = newArrayList[T]()
|
||||
for i in countup(slice.a, slice.b - 1):
|
||||
result.append(self.container[i])
|
||||
|
||||
|
||||
proc `[]=`*[T](self: ptr ArrayList[T], idx: int, obj: T) =
|
||||
## Assigns an object to the given index, in constant
|
||||
## time
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, "ArrayList is empty")
|
||||
if idx notin 0..self.length - 1:
|
||||
raise newException(IndexDefect, "ArrayList index out of bounds")
|
||||
self.container[idx] = obj
|
||||
|
||||
|
||||
proc delete*[T](self: ptr ArrayList[T], idx: int) =
|
||||
## Deletes an object from the given index.
|
||||
## This method shares the time complexity
|
||||
## of self.pop()
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, "delete from empty ArrayList")
|
||||
if idx notin 0..self.length - 1:
|
||||
raise newException(IndexDefect, &"ArrayList index out of bounds: {idx} notin 0..{self.length - 1}")
|
||||
discard self.pop(idx)
|
||||
|
||||
|
||||
proc contains*[T](self: ptr ArrayList[T], elem: T): bool =
|
||||
## Returns true if the given object is present
|
||||
## in the list, false otherwise. O(n) complexity
|
||||
if self.length > 0:
|
||||
for i in 0..self.length - 1:
|
||||
if self[i] == elem:
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
proc high*[T](self: ptr ArrayList[T]): int =
|
||||
## Returns the index of the last
|
||||
## element in the list, in constant time
|
||||
if self.length == 0:
|
||||
raise newException(IndexDefect, "ArrayList is empty")
|
||||
result = self.length - 1
|
||||
|
||||
|
||||
proc len*[T](self: ptr ArrayList[T]): int =
|
||||
## Returns the length of the list
|
||||
## in constant time
|
||||
result = self.length
|
||||
|
||||
|
||||
iterator pairs*[T](self: ptr ArrayList[T]): tuple[key: int, val: T] =
|
||||
## Implements pairwise iteration (similar to python's enumerate)
|
||||
for i in countup(0, self.length - 1):
|
||||
yield (key: i, val: self[i])
|
||||
|
||||
|
||||
iterator items*[T](self: ptr ArrayList[T]): T =
|
||||
## Implements iteration
|
||||
for i in countup(0, self.length - 1):
|
||||
yield self[i]
|
||||
|
||||
|
||||
proc reversed*[T](self: ptr ArrayList[T], first: int = -1, last: int = 0): ptr ArrayList[T] =
|
||||
## Returns a reversed version of the given list, from first to last.
|
||||
## First defaults to -1 (the end of the list) and last defaults to 0 (the
|
||||
## beginning of the list)
|
||||
var first = first
|
||||
if first == -1:
|
||||
first = self.length - 1
|
||||
result = newArrayList[T]()
|
||||
for i in countdown(first, last):
|
||||
result.append(self[i])
|
||||
|
||||
|
||||
proc extend*[T](self: ptr ArrayList[T], other: seq[T]) =
|
||||
## Iteratively calls self.append() with the elements
|
||||
## from a nim sequence
|
||||
for elem in other:
|
||||
self.append(elem)
|
||||
|
||||
|
||||
proc extend*[T](self: ptr ArrayList[T], other: ptr ArrayList[T]) =
|
||||
## Iteratively calls self.append() with the elements
|
||||
## from another ArrayList
|
||||
for elem in other:
|
||||
self.append(elem)
|
||||
|
||||
|
||||
proc `$`*[T](self: ptr ArrayList[T]): string =
|
||||
## Returns a string representation
|
||||
## of self
|
||||
result = "["
|
||||
if self.length > 0:
|
||||
for i in 0..self.length - 1:
|
||||
result = result & $self.container[i]
|
||||
if i < self.length - 1:
|
||||
result = result & ", "
|
||||
result = result & "]"
|
||||
|
||||
|
||||
proc getIter*[T](self: ptr ArrayList[T]): Iterator =
|
||||
## Returns the iterator object of the
|
||||
## arraylist
|
||||
result = allocate(ArrayListIterator, ) # TODO
|
|
@ -0,0 +1,84 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
## The base JAPL object
|
||||
|
||||
import ../../memory/allocator
|
||||
|
||||
|
||||
type
|
||||
ObjectType* {.pure.} = enum
|
||||
## All the possible object types
|
||||
String, Exception, Function,
|
||||
Class, Module, BaseObject,
|
||||
Native, Integer, Float,
|
||||
Bool, NotANumber, Infinity,
|
||||
Nil, List, Dict, Set, Tuple
|
||||
Obj* = object of RootObj
|
||||
## The base object for all
|
||||
## JAPL types. Every object
|
||||
## in JAPL implicitly inherits
|
||||
## from this base type and extends
|
||||
## its functionality
|
||||
kind*: ObjectType
|
||||
hashValue*: uint64
|
||||
|
||||
|
||||
## Object constructors and allocators
|
||||
|
||||
proc allocateObject*(size: int, kind: ObjectType): ptr Obj =
|
||||
## Wrapper around reallocate() to create a new generic JAPL object
|
||||
result = cast[ptr Obj](reallocate(nil, 0, size))
|
||||
result.kind = kind
|
||||
|
||||
|
||||
template allocateObj*(kind: untyped, objType: ObjectType): untyped =
|
||||
## Wrapper around allocateObject to cast a generic object
|
||||
## to a more specific type
|
||||
cast[ptr kind](allocateObject(sizeof kind, objType))
|
||||
|
||||
|
||||
proc newObj*: ptr Obj =
|
||||
## Allocates a generic JAPL object
|
||||
result = allocateObj(Obj, ObjectType.BaseObject)
|
||||
result.hashValue = 0x123FFFF
|
||||
|
||||
|
||||
## Default object methods implementations
|
||||
|
||||
# In JAPL code, this method will be called
|
||||
# stringify()
|
||||
proc `$`*(self: ptr Obj): string = "<object>"
|
||||
proc stringify*(self: ptr Obj): string = $self
|
||||
|
||||
proc hash*(self: ptr Obj): int64 = 0x123FFAA # Constant hash value
|
||||
# I could've used mul, sub and div, but "div" is a reserved
|
||||
# keyword and using `div` looks ugly. So to keep everything
|
||||
# consistent I just made all names long
|
||||
proc multiply*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc sum*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc divide*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc subtract*(self, other: ptr Obj): ptr Obj = nil
|
||||
# Returns 0 if self == other, a negative number if self < other
|
||||
# and a positive number if self > other. This is a convenience
|
||||
# method to implement all basic comparison operators in one
|
||||
# method
|
||||
proc compare*(self, other: ptr Obj): ptr Obj = nil
|
||||
# Specific methods for each comparison
|
||||
proc equalTo*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc greaterThan*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc lessThan*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc greaterOrEqual*(self, other: ptr Obj): ptr Obj = nil
|
||||
proc lessOrEqual*(self, other: ptr Obj): ptr Obj = nil
|
|
@ -0,0 +1,48 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## Type dispatching module
|
||||
import baseObject
|
||||
import intObject
|
||||
import floatObject
|
||||
|
||||
|
||||
proc dispatch*(obj: ptr Obj, p: proc (self: ptr Obj): ptr Obj): ptr Obj =
|
||||
## Dispatches a given one-argument procedure according to
|
||||
## the provided object's runtime type and returns its result
|
||||
case obj.kind:
|
||||
of BaseObject:
|
||||
result = p(obj)
|
||||
of ObjectType.Float:
|
||||
result = p(cast[ptr Float](obj))
|
||||
of ObjectType.Integer:
|
||||
result = p(cast[ptr Integer](obj))
|
||||
else:
|
||||
discard
|
||||
|
||||
|
||||
proc dispatch*(a, b: ptr Obj, p: proc (self: ptr Obj, other: ptr Obj): ptr Obj): ptr Obj =
|
||||
## Dispatches a given two-argument procedure according to
|
||||
## the provided object's runtime type and returns its result
|
||||
case a.kind:
|
||||
of BaseObject:
|
||||
result = p(a, b)
|
||||
of ObjectType.Float:
|
||||
# Further type casting for b is expected to occur later
|
||||
# in the given procedure
|
||||
result = p(cast[ptr Float](a), b)
|
||||
of ObjectType.Integer:
|
||||
result = p(cast[ptr Integer](a), b)
|
||||
else:
|
||||
discard
|
|
@ -0,0 +1,49 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## Implementation of integer types
|
||||
|
||||
import baseObject
|
||||
import lenientops
|
||||
|
||||
|
||||
type Float* = object of Obj
|
||||
value: float64
|
||||
|
||||
|
||||
proc newFloat*(value: float): ptr Float =
|
||||
## Initializes a new JAPL
|
||||
## float object from
|
||||
## a machine native float
|
||||
result = allocateObj(Float, ObjectType.Float)
|
||||
result.value = value
|
||||
|
||||
|
||||
proc toNativeFloat*(self: ptr Float): float =
|
||||
## Returns the float's machine
|
||||
## native underlying value
|
||||
result = self.value
|
||||
|
||||
|
||||
proc `$`*(self: ptr Float): string = $self.value
|
||||
|
||||
|
||||
proc hash*(self: ptr Float): int64 =
|
||||
## Implements hashing
|
||||
## for the given float
|
||||
if self.value - int(self.value) == self.value:
|
||||
result = int(self.value)
|
||||
else:
|
||||
result = 2166136261 xor int(self.value) # TODO: Improve this
|
||||
result *= 16777619
|
|
@ -0,0 +1,207 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
import ../../memory/allocator
|
||||
import ../../config
|
||||
|
||||
import baseObject
|
||||
import iterable
|
||||
|
||||
|
||||
type
|
||||
Entry = object
|
||||
## Low-level object to store key/value pairs.
|
||||
## Using an extra value for marking the entry as
|
||||
## a tombstone instead of something like detecting
|
||||
## tombstones as entries with null keys but full values
|
||||
## may seem wasteful. The thing is, though, that since
|
||||
## we want to implement sets on top of this hashmap and
|
||||
## the implementation of a set is *literally* a dictionary
|
||||
## with empty values and keys as the elements, this would
|
||||
## confuse our findEntry method and would force us to override
|
||||
## it to account for a different behavior.
|
||||
## Using a third field takes up more space, but saves us
|
||||
## from the hassle of rewriting code
|
||||
key: ptr Obj
|
||||
value: ptr Obj
|
||||
tombstone: bool
|
||||
HashMap* = object of Iterable
|
||||
## An associative array with O(1) lookup time,
|
||||
## similar to nim's Table type, but using raw
|
||||
## memory to be more compatible with JAPL's runtime
|
||||
## memory management
|
||||
entries: ptr UncheckedArray[ptr Entry]
|
||||
# This attribute counts *only* non-deleted entries
|
||||
actual_length: int
|
||||
|
||||
|
||||
proc newHashMap*: ptr HashMap =
|
||||
## Initializes a new, empty hashmap
|
||||
result = allocateObj(HashMap, ObjectType.Dict)
|
||||
result.actual_length = 0
|
||||
result.entries = nil
|
||||
result.capacity = 0
|
||||
result.length = 0
|
||||
|
||||
|
||||
proc freeHashMap*(self: ptr HashMap) =
|
||||
## Frees the memory associated with the hashmap
|
||||
discard freeArray(UncheckedArray[ptr Entry], self.entries, self.capacity)
|
||||
self.length = 0
|
||||
self.actual_length = 0
|
||||
self.capacity = 0
|
||||
self.entries = nil
|
||||
|
||||
|
||||
proc findEntry(self: ptr UncheckedArray[ptr Entry], key: ptr Obj, capacity: int): ptr Entry =
|
||||
## Low-level method used to find entries in the underlying
|
||||
## array, returns a pointer to an entry
|
||||
var capacity = uint64(capacity)
|
||||
var idx = uint64(key.hash()) mod capacity
|
||||
while true:
|
||||
result = self[idx]
|
||||
if system.`==`(result.key, nil):
|
||||
# We found an empty bucket
|
||||
break
|
||||
elif result.tombstone:
|
||||
# We found a previously deleted
|
||||
# entry. In this case, we need
|
||||
# to make sure the tombstone
|
||||
# will get overwritten when the
|
||||
# user wants to add a new value
|
||||
# that would replace it, BUT also
|
||||
# for it to not stop our linear
|
||||
# probe sequence. Hence, if the
|
||||
# key of the tombstone is the same
|
||||
# as the one we're looking for,
|
||||
# we break out of the loop, otherwise
|
||||
# we keep searching
|
||||
if result.key == key:
|
||||
break
|
||||
elif result.key == key:
|
||||
# We were looking for a specific key and
|
||||
# we found it, so we also bail out
|
||||
break
|
||||
# If none of these conditions match, we have a collision!
|
||||
# This means we can just move on to the next slot in our probe
|
||||
# sequence until we find an empty slot. The way our resizing
|
||||
# mechanism works makes the empty slot invariant easy to
|
||||
# maintain since we increase the underlying array's size
|
||||
# before we are actually full
|
||||
idx = (idx + 1) mod capacity
|
||||
|
||||
|
||||
proc adjustCapacity(self: ptr HashMap) =
|
||||
var newCapacity = growCapacity(self.capacity)
|
||||
var entries = allocate(UncheckedArray[ptr Entry], Entry, newCapacity)
|
||||
var oldEntry: ptr Entry
|
||||
var newEntry: ptr Entry
|
||||
self.length = 0
|
||||
for x in countup(0, newCapacity - 1):
|
||||
entries[x] = allocate(Entry, Entry, 1)
|
||||
entries[x].tombstone = false
|
||||
entries[x].key = nil
|
||||
entries[x].value = nil
|
||||
for x in countup(0, self.capacity - 1):
|
||||
oldEntry = self.entries[x]
|
||||
if not system.`==`(oldEntry.key, nil):
|
||||
newEntry = entries.findEntry(oldEntry.key, newCapacity)
|
||||
newEntry.key = oldEntry.key
|
||||
newEntry.value = oldEntry.value
|
||||
self.length += 1
|
||||
discard freeArray(UncheckedArray[ptr Entry], self.entries, self.capacity)
|
||||
self.entries = entries
|
||||
self.capacity = newCapacity
|
||||
|
||||
|
||||
proc setEntry(self: ptr HashMap, key: ptr Obj, value: ptr Obj): bool =
|
||||
if float64(self.length + 1) >= float64(self.capacity) * MAP_LOAD_FACTOR:
|
||||
self.adjustCapacity()
|
||||
var entry = findEntry(self.entries, key, self.capacity)
|
||||
result = system.`==`(entry.key, nil)
|
||||
if result:
|
||||
self.actual_length += 1
|
||||
self.length += 1
|
||||
entry.key = key
|
||||
entry.value = value
|
||||
entry.tombstone = false
|
||||
|
||||
|
||||
proc `[]`*(self: ptr HashMap, key: ptr Obj): ptr Obj =
|
||||
var entry = findEntry(self.entries, key, self.capacity)
|
||||
if system.`==`(entry.key, nil) or entry.tombstone:
|
||||
raise newException(KeyError, "Key not found: " & $key)
|
||||
result = entry.value
|
||||
|
||||
|
||||
proc `[]=`*(self: ptr HashMap, key: ptr Obj, value: ptr Obj) =
|
||||
discard self.setEntry(key, value)
|
||||
|
||||
|
||||
proc len*(self: ptr HashMap): int =
|
||||
result = self.actual_length
|
||||
|
||||
|
||||
proc del*(self: ptr HashMap, key: ptr Obj) =
|
||||
if self.len() == 0:
|
||||
raise newException(KeyError, "delete from empty hashmap")
|
||||
var entry = findEntry(self.entries, key, self.capacity)
|
||||
if not system.`==`(entry.key, nil):
|
||||
self.actual_length -= 1
|
||||
entry.tombstone = true
|
||||
else:
|
||||
raise newException(KeyError, "Key not found: " & $key)
|
||||
|
||||
|
||||
proc contains*(self: ptr HashMap, key: ptr Obj): bool =
|
||||
let entry = findEntry(self.entries, key, self.capacity)
|
||||
if not system.`==`(entry.key, nil) and not entry.tombstone:
|
||||
result = true
|
||||
else:
|
||||
result = false
|
||||
|
||||
|
||||
iterator keys*(self: ptr HashMap): ptr Obj =
|
||||
var entry: ptr Entry
|
||||
for i in countup(0, self.capacity - 1):
|
||||
entry = self.entries[i]
|
||||
if not system.`==`(entry.key, nil) and not entry.tombstone:
|
||||
yield entry.key
|
||||
|
||||
|
||||
iterator values*(self: ptr HashMap): ptr Obj =
|
||||
for key in self.keys():
|
||||
yield self[key]
|
||||
|
||||
|
||||
iterator pairs*(self: ptr HashMap): tuple[key: ptr Obj, val: ptr Obj] =
|
||||
for key in self.keys():
|
||||
yield (key: key, val: self[key])
|
||||
|
||||
|
||||
iterator items*(self: ptr HashMap): ptr Obj =
|
||||
for k in self.keys():
|
||||
yield k
|
||||
|
||||
|
||||
proc `$`*(self: ptr HashMap): string =
|
||||
var i = 0
|
||||
result &= "{"
|
||||
for key, value in self.pairs():
|
||||
result &= $key & ": " & $value
|
||||
if i < self.len() - 1:
|
||||
result &= ", "
|
||||
i += 1
|
||||
result &= "}"
|
|
@ -0,0 +1,40 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## Implementation of integer types
|
||||
|
||||
import baseObject
|
||||
|
||||
|
||||
type Integer* = object of Obj
|
||||
value: int64
|
||||
|
||||
|
||||
proc newInteger*(value: int64): ptr Integer =
|
||||
## Initializes a new JAPL
|
||||
## integer object from
|
||||
## a machine native integer
|
||||
result = allocateObj(Integer, ObjectType.Integer)
|
||||
result.value = value
|
||||
|
||||
|
||||
proc toNativeInteger*(self: ptr Integer): int64 =
|
||||
## Returns the integer's machine
|
||||
## native underlying value
|
||||
result = self.value
|
||||
|
||||
|
||||
proc `$`*(self: ptr Integer): string = $self.value
|
||||
proc hash*(self: ptr Integer): int64 = self.value
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Implementation of iterable types and iterators in JAPL
|
||||
|
||||
import baseObject
|
||||
|
||||
|
||||
type
|
||||
Iterable* = object of Obj
|
||||
## Defines the standard interface
|
||||
## for iterable types in JAPL
|
||||
length*: int
|
||||
capacity*: int
|
||||
Iterator* = object of Iterable
|
||||
## This object drives iteration
|
||||
## for every iterable type in JAPL except
|
||||
## generators
|
||||
iterable*: ptr Obj
|
||||
iterCount*: int
|
||||
|
||||
|
||||
proc getIter*(self: Iterable): ptr Iterator =
|
||||
## Returns the iterator object of an
|
||||
## iterable, which drives foreach
|
||||
## loops
|
||||
return nil
|
||||
|
||||
|
||||
proc next*(self: Iterator): ptr Obj =
|
||||
## Returns the next element from
|
||||
## the iterator or nil if the
|
||||
## iterator has been consumed
|
||||
return nil
|
|
@ -0,0 +1,15 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# JAPL string implementations
|
|
@ -0,0 +1,20 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## The JAPL runtime environment
|
||||
|
||||
|
||||
type
|
||||
VM* = ref object
|
||||
stack:
|
|
@ -0,0 +1,61 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import strformat
|
||||
|
||||
const BYTECODE_MARKER* = "JAPL_BYTECODE"
|
||||
const MAP_LOAD_FACTOR* = 0.75 # Load factor for builtin hashmaps
|
||||
when MAP_LOAD_FACTOR >= 1.0:
|
||||
{.fatal: "Hashmap load factor must be < 1".}
|
||||
const HEAP_GROW_FACTOR* = 2 # How much extra memory to allocate for dynamic arrays and garbage collection when resizing
|
||||
when HEAP_GROW_FACTOR <= 1:
|
||||
{.fatal: "Heap growth factor must be > 1".}
|
||||
const MAX_STACK_FRAMES* = 800 # The maximum number of stack frames at any one time. Acts as a recursion limiter (1 frame = 1 call)
|
||||
when MAX_STACK_FRAMES <= 0:
|
||||
{.fatal: "The frame limit must be > 0".}
|
||||
const JAPL_VERSION* = (major: 0, minor: 4, patch: 0)
|
||||
const JAPL_RELEASE* = "alpha"
|
||||
const JAPL_COMMIT_HASH* = "ba9c8b4e5664c0670eb8925d65b307e397d6ed82"
|
||||
when len(JAPL_COMMIT_HASH) != 40:
|
||||
{.fatal: "The git commit hash must be exactly 40 characters long".}
|
||||
const JAPL_BRANCH* = "master"
|
||||
when len(JAPL_BRANCH) >= 255:
|
||||
{.fatal: "The git branch name's length must be less than or equal to 255 characters".}
|
||||
const DEBUG_TRACE_VM* = false # Traces VM execution
|
||||
const SKIP_STDLIB_INIT* = false # Skips stdlib initialization (can be imported manually)
|
||||
const DEBUG_TRACE_GC* = false # Traces the garbage collector (TODO)
|
||||
const DEBUG_TRACE_ALLOCATION* = false # Traces memory allocation/deallocation
|
||||
const DEBUG_TRACE_COMPILER* = false # Traces the compiler
|
||||
const JAPL_VERSION_STRING* = &"JAPL {JAPL_VERSION.major}.{JAPL_VERSION.minor}.{JAPL_VERSION.patch} {JAPL_RELEASE} ({JAPL_BRANCH}, {CompileDate}, {CompileTime}, {JAPL_COMMIT_HASH[0..8]}) [Nim {NimVersion}] on {hostOS} ({hostCPU})"
|
||||
const HELP_MESSAGE* = """The JAPL programming language, Copyright (C) 2022 Mattia Giambirtone & All Contributors
|
||||
|
||||
This program is free software, see the license distributed with this program or check
|
||||
http://www.apache.org/licenses/LICENSE-2.0 for more info.
|
||||
|
||||
Basic usage
|
||||
-----------
|
||||
|
||||
$ jpl Opens an interactive session (REPL)
|
||||
$ jpl file.jpl Runs the given JAPL source file
|
||||
|
||||
Command-line options
|
||||
--------------------
|
||||
|
||||
-h, --help Shows this help text and exits
|
||||
-v, --version Prints the JAPL version number and exits
|
||||
-s, --string Executes the passed string as if it was a file
|
||||
-i, --interactive Enables interactive mode, which opens a REPL session after execution of a file or source string
|
||||
-c, --nocache Disables dumping the result of bytecode compilation to files for caching
|
||||
-d, --cache-delay Configures the bytecode cache invalidation threshold, in minutes (defaults to 60)
|
||||
"""
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,574 @@
|
|||
# Copyright 2022 Mattia Giambirtone & All Contributors
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
## A simple and modular tokenizer implementation with arbitrary lookahead
|
||||
|
||||
import strutils
|
||||
import parseutils
|
||||
import strformat
|
||||
import tables
|
||||
|
||||
import meta/token
|
||||
import meta/errors
|
||||
|
||||
|
||||
export token # Makes Token available when importing the lexer module
|
||||
export errors
|
||||
|
||||
|
||||
type SymbolTable = object
|
||||
## A table of symbols used
|
||||
## to lex a source file
|
||||
keywords: TableRef[string, Token]
|
||||
operators: TableRef[string, Token]
|
||||
|
||||
|
||||
# Table of all single-character tokens
|
||||
var tokens = to_table({
|
||||
'(': LeftParen, ')': RightParen,
|
||||
'{': LeftBrace, '}': RightBrace,
|
||||
'.': Dot, ',': Comma, '-': Minus,
|
||||
'+': Plus, '*': Asterisk,
|
||||
'>': GreaterThan, '<': LessThan, '=': Equal,
|
||||
'~': Tilde, '/': Slash, '%': Percentage,
|
||||
'[': LeftBracket, ']': RightBracket,
|
||||
':': Colon, '^': Caret, '&': Ampersand,
|
||||
'|': Pipe, ';': Semicolon})
|
||||
|
||||
# Table of all double-character tokens
|
||||
const double = to_table({"**": DoubleAsterisk,
|
||||
">>": RightShift,
|
||||
"<<": LeftShift,
|
||||
"==": DoubleEqual,
|
||||
"!=": NotEqual,
|
||||
">=": GreaterOrEqual,
|
||||
"<=": LessOrEqual,
|
||||
"//": FloorDiv,
|
||||
"+=": InplaceAdd,
|
||||
"-=": InplaceSub,
|
||||
"/=": InplaceDiv,
|
||||
"*=": InplaceMul,
|
||||
"^=": InplaceXor,
|
||||
"&=": InplaceAnd,
|
||||
"|=": InplaceOr,
|
||||
"%=": InplaceMod,
|
||||
})
|
||||
|
||||
# Table of all triple-character tokens
|
||||
const triple = to_table({"//=": InplaceFloorDiv,
|
||||
"**=": InplacePow,
|
||||
">>=": InplaceRightShift,
|
||||
"<<=": InplaceLeftShift
|
||||
})
|
||||
|
||||
|
||||
# Constant table storing all the reserved keywords (which are parsed as identifiers)
|
||||
const keywords = to_table({
|
||||
"fun": Fun, "raise": Raise,
|
||||
"if": If, "else": Else,
|
||||
"for": For, "while": While,
|
||||
"var": Var, "nil": Nil,
|
||||
"true": True, "false": False,
|
||||
"return": Return, "break": Break,
|
||||
"continue": Continue, "inf": Infinity,
|
||||
"nan": NotANumber, "is": Is,
|
||||
"lambda": Lambda, "class": Class,
|
||||
"async": Async, "import": Import,
|
||||
"isnot": IsNot, "from": From,
|
||||
"const": Const, "not": LogicalNot,
|
||||
"assert": Assert, "or": LogicalOr,
|
||||
"and": LogicalAnd, "del": Del,
|
||||
"async": Async, "await": Await,
|
||||
"foreach": Foreach, "yield": Yield,
|
||||
"private": Private, "public": Public,
|
||||
"static": Static, "dynamic": Dynamic,
|
||||
"as": As, "of": Of, "defer": Defer,
|
||||
"except": Except, "finally": Finally,
|
||||
"try": Try
|
||||
})
|
||||
|
||||
|
||||
type
|
||||
Lexer* = ref object
|
||||
## A lexer object
|
||||
source: string
|
||||
tokens: seq[Token]
|
||||
line: int
|
||||
start: int
|
||||
current: int
|
||||
file: string
|
||||
lines: seq[tuple[start, stop: int]]
|
||||
lastLine: int
|
||||
|
||||
|
||||
# Simple public getters
|
||||
proc getStart*(self: Lexer): int = self.start
|
||||
proc getCurrent*(self: Lexer): int = self.current
|
||||
proc getLine*(self: Lexer): int = self.line
|
||||
proc getSource*(self: Lexer): string = self.source
|
||||
proc getRelPos*(self: Lexer, line: int): tuple[start, stop: int] = (if line > 1: self.lines[line - 2] else: (start: 0, stop: self.current))
|
||||
|
||||
|
||||
proc initLexer*(self: Lexer = nil): Lexer =
|
||||
## Initializes the lexer or resets
|
||||
## the state of an existing one
|
||||
new(result)
|
||||
if self != nil:
|
||||
result = self
|
||||
result.source = ""
|
||||
result.tokens = @[]
|
||||
result.line = 1
|
||||
result.start = 0
|
||||
result.current = 0
|
||||
result.file = ""
|
||||
result.lines = @[]
|
||||
result.lastLine = 0
|
||||
|
||||
|
||||
proc done(self: Lexer): bool =
|
||||
## Returns true if we reached EOF
|
||||
result = self.current >= self.source.len
|
||||
|
||||
|
||||
proc incLine(self: Lexer) =
|
||||
## Increments the lexer's line
|
||||
## and updates internal line
|
||||
## metadata
|
||||
self.lines.add((start: self.lastLine, stop: self.current))
|
||||
self.line += 1
|
||||
self.lastLine = self.current
|
||||
|
||||
|
||||
proc step(self: Lexer, n: int = 1): string =
|
||||
## Steps n characters forward in the
|
||||
## source file (default = 1). A null
|
||||
## terminator is returned if the lexer
|
||||
## is at EOF. The amount of skipped
|
||||
## characters is returned
|
||||
if self.done():
|
||||
return "\0"
|
||||
self.current = self.current + n
|
||||
result = self.source[self.current..self.current + n]
|
||||
|
||||
|
||||
proc peek(self: Lexer, distance: int = 0): string =
|
||||
## Returns the character in the source file at
|
||||
## the given distance, without consuming it.
|
||||
## The character is converted to a string of
|
||||
## length one for compatibility with the rest
|
||||
## of the lexer.
|
||||
## A null terminator is returned if the lexer
|
||||
## is at EOF. The distance parameter may be
|
||||
## negative to retrieve previously consumed
|
||||
## tokens, while the default distance is 0
|
||||
## (retrieves the next token to be consumed).
|
||||
## If the given distance goes beyond EOF, a
|
||||
## null terminator is returned
|
||||
if self.done() or self.current + distance > self.source.high():
|
||||
result = "\0"
|
||||
else:
|
||||
# hack to "convert" a char to a string
|
||||
result = &"{self.source[self.current + distance]}"
|
||||
|
||||
|
||||
proc peek(self: Lexer, distance: int = 0, length: int = 1): string =
|
||||
## Behaves like self.peek(), but
|
||||
## can peek more than one character,
|
||||
## starting from the given distance.
|
||||
## A string of exactly length characters
|
||||
## is returned. If the length of the
|
||||
## desired string goes beyond EOF,
|
||||
## the resulting string is padded
|
||||
## with null terminators
|
||||
var i = distance
|
||||
while i <= length:
|
||||
result.add(self.peek(i))
|
||||
inc(i)
|
||||
|
||||
proc error(self: Lexer, message: string) =
|
||||
## Raises a lexing error with a formatted
|
||||
## error message
|
||||
|
||||
raise newException(LexingError, &"A fatal error occurred while parsing '{self.file}', line {self.line} at '{self.peek()}' -> {message}")
|
||||
|
||||
|
||||
proc check(self: Lexer, what: string, distance: int = 0): bool =
|
||||
## Behaves like match, without consuming the
|
||||
## token. False is returned if we're at EOF
|
||||
## regardless of what the token to check is.
|
||||
## The distance is passed directly to self.peek()
|
||||
if self.done():
|
||||
return false
|
||||
return self.peek(distance) == what
|
||||
|
||||
|
||||
proc check(self: Lexer, what: string): bool =
|
||||
## Calls self.check() in a loop with
|
||||
## each character from the given source
|
||||
## string. Useful to check multi-character
|
||||
## strings in one go
|
||||
for i, chr in what:
|
||||
# Why "i" you ask? Well, since check
|
||||
# does not consume the tokens it checks
|
||||
# against we need some way of keeping
|
||||
# track where we are in the string the
|
||||
# caller gave us, otherwise this will
|
||||
# not behave as expected
|
||||
if not self.check(&"{chr}", i):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
proc check(self: Lexer, what: openarray[string]): bool =
|
||||
## Calls self.check() in a loop with
|
||||
## each character from the given seq of
|
||||
## char and returns at the first match.
|
||||
## Useful to check multiple tokens in a situation
|
||||
## where only one of them may match at one time
|
||||
for s in what:
|
||||
if self.check(s):
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
proc match(self: Lexer, what: char): bool =
|
||||
## Returns true if the next character matches
|
||||
## the given character, and consumes it.
|
||||
## Otherwise, false is returned
|
||||
if self.done():
|
||||
self.error("unexpected EOF")
|
||||
return false
|
||||
elif not self.check(what):
|
||||
self.error(&"expecting '{what}', got '{self.peek()}' instead")
|
||||
return false
|
||||
self.current += 1
|
||||
return true
|
||||
|
||||
|
||||
proc match(self: Lexer, what: string): bool =
|
||||
## Calls self.match() in a loop with
|
||||
## each character from the given source
|
||||
## string. Useful to match multi-character
|
||||
## strings in one go
|
||||
for chr in what:
|
||||
if not self.match(chr):
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
proc createToken(self: Lexer, tokenType: TokenType) =
|
||||
## Creates a token object and adds it to the token
|
||||
## list
|
||||
var tok: Token = new(Token)
|
||||
tok.kind = tokenType
|
||||
tok.lexeme = self.source[self.start..<self.current]
|
||||
tok.line = self.line
|
||||
tok.pos = (start: self.start, stop: self.current)
|
||||
self.tokens.add(tok)
|
||||
|
||||
|
||||
proc parseEscape(self: Lexer) =
|
||||
# Boring escape sequence parsing. For more info check out
|
||||
# https://en.wikipedia.org/wiki/Escape_sequences_in_C.
|
||||
# As of now, \u and \U are not supported, but they'll
|
||||
# likely be soon. Another notable limitation is that
|
||||
# \xhhh and \nnn are limited to the size of a char
|
||||
# (i.e. uint8, or 256 values)
|
||||
case self.peek():
|
||||
of 'a':
|
||||
self.source[self.current] = cast[char](0x07)
|
||||
of 'b':
|
||||
self.source[self.current] = cast[char](0x7f)
|
||||
of 'e':
|
||||
self.source[self.current] = cast[char](0x1B)
|
||||
of 'f':
|
||||
self.source[self.current] = cast[char](0x0C)
|
||||
of 'n':
|
||||
when defined(windows):
|
||||
# We natively convert LF to CRLF on Windows, and
|
||||
# gotta thank Microsoft for the extra boilerplate!
|
||||
self.source[self.current] = cast[char](0x0D)
|
||||
self.source.insert(self.current + 1, 0X0A)
|
||||
when defined(darwin):
|
||||
# Thanks apple, lol
|
||||
self.source[self.current] = cast[char](0x0A)
|
||||
when defined(linux):
|
||||
self.source[self.current] = cast[char](0X0D)
|
||||
of 'r':
|
||||
self.source[self.current] = cast[char](0x0D)
|
||||
of 't':
|
||||
self.source[self.current] = cast[char](0x09)
|
||||
of 'v':
|
||||
self.source[self.current] = cast[char](0x0B)
|
||||
of '"':
|
||||
self.source[self.current] = '"'
|
||||
of '\'':
|
||||
self.source[self.current] = '\''
|
||||
of '\\':
|
||||
self.source[self.current] = cast[char](0x5C)
|
||||
of '0'..'9':
|
||||
var code = ""
|
||||
var value = 0
|
||||
var i = self.current
|
||||
while i < self.source.high() and (let c = self.source[
|
||||
i].toLowerAscii(); c in '0'..'7') and len(code) < 3:
|
||||
code &= self.source[i]
|
||||
i += 1
|
||||
assert parseOct(code, value) == code.len()
|
||||
if value > uint8.high().int:
|
||||
self.error("escape sequence value too large (> 255)")
|
||||
self.source[self.current] = cast[char](value)
|
||||
of 'u', 'U':
|
||||
self.error("unicode escape sequences are not supported (yet)")
|
||||
of 'x':
|
||||
var code = ""
|
||||
var value = 0
|
||||
var i = self.current
|
||||
while i < self.source.high() and (let c = self.source[
|
||||
i].toLowerAscii(); c in 'a'..'f' or c in '0'..'9'):
|
||||
code &= self.source[i]
|
||||
i += 1
|
||||
assert parseHex(code, value) == code.len()
|
||||
if value > uint8.high().int:
|
||||
self.error("escape sequence value too large (> 255)")
|
||||
self.source[self.current] = cast[char](value)
|
||||
else:
|
||||
self.error(&"invalid escape sequence '\\{self.peek()}'")
|
||||
|
||||
|
||||
proc parseString(self: Lexer, delimiter: char, mode: string = "single") =
|
||||
## Parses string literals. They can be expressed using matching pairs
|
||||
## of either single or double quotes. Most C-style escape sequences are
|
||||
## supported, moreover, a specific prefix may be prepended
|
||||
## to the string to instruct the lexer on how to parse it:
|
||||
## - b -> declares a byte string, where each character is
|
||||
## interpreted as an integer instead of a character
|
||||
## - r -> declares a raw string literal, where escape sequences
|
||||
## are not parsed and stay as-is
|
||||
## - f -> declares a format string, where variables may be
|
||||
## interpolated using curly braces like f"Hello, {name}!".
|
||||
## Braces may be escaped using a pair of them, so to represent
|
||||
## a literal "{" in an f-string, one would use {{ instead
|
||||
## Multi-line strings can be declared using matching triplets of
|
||||
## either single or double quotes. They can span across multiple
|
||||
## lines and escape sequences in them are not parsed, like in raw
|
||||
## strings, so a multi-line string prefixed with the "r" modifier
|
||||
## is redundant, although multi-line byte/format strings are supported
|
||||
while not self.check(delimiter) and not self.done():
|
||||
if self.check('\n'):
|
||||
if mode == "multi":
|
||||
self.incLine()
|
||||
else:
|
||||
self.error("unexpected EOL while parsing string literal")
|
||||
if mode in ["raw", "multi"]:
|
||||
discard self.step()
|
||||
if self.check('\\'):
|
||||
# This madness here serves to get rid of the slash, since \x is mapped
|
||||
# to a one-byte sequence but the string '\x' actually 2 bytes (or more,
|
||||
# depending on the specific escape sequence)
|
||||
self.source = self.source[0..<self.current] & self.source[
|
||||
self.current + 1..^1]
|
||||
self.parseEscape()
|
||||
if mode == "format" and self.check('{'):
|
||||
discard self.step()
|
||||
if self.check('{'):
|
||||
self.source = self.source[0..<self.current] & self.source[
|
||||
self.current + 1..^1]
|
||||
continue
|
||||
while not self.check(['}', '"']):
|
||||
discard self.step()
|
||||
if self.check('"'):
|
||||
self.error("unclosed '{' in format string")
|
||||
elif mode == "format" and self.check('}'):
|
||||
if not self.check('}', 1):
|
||||
self.error("unmatched '}' in format string")
|
||||
else:
|
||||
self.source = self.source[0..<self.current] & self.source[
|
||||
self.current + 1..^1]
|
||||
discard self.step()
|
||||
if mode == "multi":
|
||||
if not self.match(delimiter.repeat(3)):
|
||||
self.error("unexpected EOL while parsing multi-line string literal")
|
||||
if self.done():
|
||||
self.error("unexpected EOF while parsing string literal")
|
||||
return
|
||||
else:
|
||||
discard self.step()
|
||||
self.createToken(String)
|
||||
|
||||
|
||||
proc parseBinary(self: Lexer) =
|
||||
## Parses binary numbers
|
||||
while self.peek().isDigit():
|
||||
if not self.check(['0', '1']):
|
||||
self.error(&"invalid digit '{self.peek()}' in binary literal")
|
||||
discard self.step()
|
||||
self.createToken(Binary)
|
||||
# To make our life easier, we pad the binary number in here already
|
||||
while (self.tokens[^1].lexeme.len() - 2) mod 8 != 0:
|
||||
self.tokens[^1].lexeme = "0b" & "0" & self.tokens[^1].lexeme[2..^1]
|
||||
|
||||
|
||||
proc parseOctal(self: Lexer) =
|
||||
## Parses octal numbers
|
||||
while self.peek().isDigit():
|
||||
if self.peek() notin '0'..'7':
|
||||
self.error(&"invalid digit '{self.peek()}' in octal literal")
|
||||
discard self.step()
|
||||
self.createToken(Octal)
|
||||
|
||||
|
||||
proc parseHex(self: Lexer) =
|
||||
## Parses hexadecimal numbers
|
||||
while self.peek().isAlphaNumeric():
|
||||
if not self.peek().isDigit() and self.peek().toLowerAscii() notin 'a'..'f':
|
||||
self.error(&"invalid hexadecimal literal")
|
||||
discard self.step()
|
||||
self.createToken(Hex)
|
||||
|
||||
|
||||
proc parseNumber(self: Lexer) =
|
||||
## Parses numeric literals, which encompass
|
||||
## integers and floats composed of arabic digits.
|
||||
## Floats also support scientific notation
|
||||
## (i.e. 3e14), while the fractional part
|
||||
## must be separated from the decimal one
|
||||
## using a dot (which acts as a "comma").
|
||||
## Literals such as 32.5e3 are also supported.
|
||||
## The "e" for the scientific notation of floats
|
||||
## is case-insensitive. Binary number literals are
|
||||
## expressed using the prefix 0b, hexadecimal
|
||||
## numbers with the prefix 0x and octal numbers
|
||||
## with the prefix 0o
|
||||
case self.peek():
|
||||
of 'b':
|
||||
discard self.step()
|
||||
self.parseBinary()
|
||||
of 'x':
|
||||
discard self.step()
|
||||
self.parseHex()
|
||||
of 'o':
|
||||
discard self.step()
|
||||
self.parseOctal()
|
||||
else:
|
||||
var kind: TokenType = Integer
|
||||
while isDigit(self.peek()):
|
||||
discard self.step()
|
||||
if self.check(['e', 'E']):
|
||||
kind = Float
|
||||
discard self.step()
|
||||
while self.peek().isDigit():
|
||||
discard self.step()
|
||||
elif self.check('.'):
|
||||
# TODO: Is there a better way?
|
||||
discard self.step()
|
||||
if not isDigit(self.peek()):
|
||||
self.error("invalid float number literal")
|
||||
kind = Float
|
||||
while isDigit(self.peek()):
|
||||
discard self.step()
|
||||
if self.check(['e', 'E']):
|
||||
discard self.step()
|
||||
while isDigit(self.peek()):
|
||||
discard self.step()
|
||||
self.createToken |