basic-pp 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: basic-pp
3
+ Version: 0.0.0
4
+ Summary: a simple language for begginers.
5
+ Author-email: R A Veeraragavan <veeracoder123@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/veeracoder508/e2eeftp
8
+ Project-URL: Issues, https://github.com/veeracoder508/e2eeftp/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.14
12
+ Description-Content-Type: text/markdown
13
+ License-File: license
14
+ Requires-Dist: pdoc3>=0.11.6
15
+ Requires-Dist: pytest>=9.0.3
16
+ Requires-Dist: rich>=15.0.0
17
+ Requires-Dist: zensical>=0.0.43
18
+ Dynamic: license-file
19
+
20
+ # basic++
21
+ An simple language for beginners.
22
+
23
+ ## usage
24
+ bpp \[options\] \<filename\>
25
+
26
+ ### positional arguments:
27
+ - **src_file** the source(.bpp)/byte(.bc) code
28
+
29
+ ### options:
30
+ - **-h**, **--help**: show this help message and exit
31
+ - **-v**, **--verbose**: increase output verbosity
32
+ - **-b**, **--bytecode**: display the byte code.
33
+ - **-bc**, **--write-bc**: write the byte code to a file.
34
+
35
+ ## how it works??
36
+ Basic++ is like python-compiles an byte code and then interpret the byte code.
37
+ The byte code is in the same style like python's.
38
+
39
+ For full documentation visit [veeracoder508/basic-pp](https://veeracoder508.github.io/basic-pp)
@@ -0,0 +1,14 @@
1
+ basic_pp-0.0.0.dist-info/licenses/license,sha256=zC39XHU09mWV6vHqWJ38CPQ4suunMFDpTsbF3mbXq-M,1069
2
+ basicpp/__init__.py,sha256=nAFi8DTnzkmlYQ5D05wXwIW5aFGBmARuVyuQjXZHIQs,62
3
+ basicpp/cli.py,sha256=YHVyIMcyn973DL5NRluWgvuuzRsrIpes-e3dtHBFdFY,2811
4
+ basicpp/bvm/__init__.py,sha256=76eQ5M58cBEXU17vQFoHv7iwdPPPgYawwJcokDM1IV0,70
5
+ basicpp/bvm/vm.py,sha256=_LsYt4Qs97RQHuJ-F-IgnvdjT8U5MXk0ZnlgHAfQg0M,6388
6
+ basicpp/compiler/__init__.py,sha256=Sz7hVgokXjSFGQ2lMAsEJZpZj8tG55HXlwHdB4DKlvY,231
7
+ basicpp/compiler/ast_a.py,sha256=XFx8Bhx5N8AoWhNeGYvyiD_66xFbtYUCaKUpzAAPEKE,20071
8
+ basicpp/compiler/lexer.py,sha256=_fgo-uicglr5_BqCaa9lykLU3XfEsJJH9vKy8Hk5JeY,13017
9
+ basicpp/compiler/tokens.py,sha256=XX_0BJSaHbf1tp3WpGdjyWjnfxTERrdM8llDVz0td4w,3595
10
+ basic_pp-0.0.0.dist-info/METADATA,sha256=jQwNJOwd_1eDsViqf3QOth84i4VJ__WvCDGloAEBNog,1316
11
+ basic_pp-0.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ basic_pp-0.0.0.dist-info/entry_points.txt,sha256=3nUmNnVtZ9d0dMes_JE8IFMga7vc4NDfzm7Ju4BrHuI,40
13
+ basic_pp-0.0.0.dist-info/top_level.txt,sha256=-Evl2Nvv3PdeLLE8un5ILeKgadx3hs-dvXUcODC6-gk,8
14
+ basic_pp-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bpp = basicpp.cli:cli
@@ -0,0 +1,19 @@
1
+ Copyright (c) Zensical LLC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to
5
+ deal in the Software without restriction, including without limitation the
6
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7
+ sell copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19
+ IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ basicpp
basicpp/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """A simple interpreted landuage."""
2
+
3
+ from .bvm import BVM
@@ -0,0 +1,3 @@
1
+ """The Basic Virtual Machine implementation."""
2
+
3
+ from .vm import BVM
basicpp/bvm/vm.py ADDED
@@ -0,0 +1,213 @@
1
+ """
2
+ Basic Virtual Machine (BVM) implementation for Basic++.
3
+ This module executes the bytecode produced by the compiler.
4
+ """
5
+
6
+ import sys
7
+ from typing import Any, List, Dict, Tuple
8
+ from pprint import pprint
9
+
10
+
11
+ class BVM:
12
+ """The VM for the Basic++ language."""
13
+
14
+ def __init__(self, bytecode: Dict[str, Any]):
15
+ """
16
+ Initializes the VM with the bytecode dictionary.
17
+
18
+ Args:
19
+ bytecode (dict): Dictionary containing 'code', 'consts', and 'names'.
20
+ """
21
+ self.code: List[Tuple[str, Any]] = bytecode.get('code', [])
22
+ self.consts: List[Any] = bytecode.get('consts', [])
23
+ self.names: List[str] = bytecode.get('names', [])
24
+
25
+ self.stack: List[Any] = []
26
+ self.variables: Dict[str, Any] = {}
27
+ self.ip = 0 # Instruction Pointer
28
+ self.labels: Dict[str, int] = {}
29
+
30
+ self._resolve_labels()
31
+
32
+ def _resolve_labels(self):
33
+ """Pre-pass to map labels to instruction indices."""
34
+ for i, (op, arg) in enumerate(self.code):
35
+ if op == 'LABEL':
36
+ self.labels[arg] = i
37
+
38
+ def push(self, value: Any):
39
+ self.stack.append(value)
40
+
41
+ def pop(self) -> Any:
42
+ if not self.stack:
43
+ raise RuntimeError("Stack underflow")
44
+ return self.stack.pop()
45
+
46
+ def run(self):
47
+ """Main execution loop."""
48
+ while self.ip < len(self.code):
49
+ op, arg = self.code[self.ip]
50
+
51
+ if op == 'RETURN_VALUE':
52
+ break
53
+
54
+ elif op == 'LOAD_CONST':
55
+ self.push(arg)
56
+
57
+ elif op == 'LOAD_NAME':
58
+ if arg not in self.variables:
59
+ raise NameError(f"Variable '{arg}' is not defined")
60
+ self.push(self.variables[arg])
61
+
62
+ elif op == 'STORE_NAME':
63
+ self.variables[arg] = self.pop()
64
+
65
+ elif op == 'READ_INPUT':
66
+ sys.stdout.flush()
67
+ val = input(arg)
68
+ # Attempt basic type conversion
69
+ try:
70
+ if '.' in val:
71
+ val = float(val)
72
+ else:
73
+ val = int(val)
74
+ except ValueError:
75
+ pass
76
+ self.push(val)
77
+
78
+ elif op == 'PRINT_ITEM':
79
+ print(self.pop(), end=' ', flush=True)
80
+
81
+ elif op == 'PRINT_NEWLINE':
82
+ print()
83
+
84
+ elif op == 'BINARY_ADD':
85
+ b = self.pop()
86
+ a = self.pop()
87
+ self.push(a + b)
88
+
89
+ elif op == 'BINARY_SUBTRACT':
90
+ b = self.pop()
91
+ a = self.pop()
92
+ self.push(a - b)
93
+
94
+ elif op == 'BINARY_MULTIPLY':
95
+ b = self.pop()
96
+ a = self.pop()
97
+ self.push(a * b)
98
+
99
+ elif op == 'BINARY_TRUE_DIVIDE':
100
+ b = self.pop()
101
+ a = self.pop()
102
+ self.push(a / b)
103
+
104
+ elif op == 'BINARY_MODULO':
105
+ b = self.pop()
106
+ a = self.pop()
107
+ self.push(a % b)
108
+
109
+ elif op == 'BINARY_AND':
110
+ b = self.pop()
111
+ a = self.pop()
112
+ self.push(a & b)
113
+
114
+ elif op == 'BINARY_OR':
115
+ b = self.pop()
116
+ a = self.pop()
117
+ self.push(a | b)
118
+
119
+ elif op == 'BINARY_XOR':
120
+ b = self.pop()
121
+ a = self.pop()
122
+ self.push(a ^ b)
123
+
124
+ elif op == 'BINARY_LSHIFT':
125
+ b = self.pop()
126
+ a = self.pop()
127
+ self.push(a << b)
128
+
129
+ elif op == 'BINARY_RSHIFT':
130
+ b = self.pop()
131
+ a = self.pop()
132
+ self.push(a >> b)
133
+
134
+ elif op == 'BINARY_POWER':
135
+ b = self.pop()
136
+ a = self.pop()
137
+ self.push(a ** b)
138
+
139
+ elif op.startswith('COMPARE_'):
140
+ b = self.pop()
141
+ a = self.pop()
142
+ if op == 'COMPARE_EQ': self.push(a == b)
143
+ elif op == 'COMPARE_NEQ': self.push(a != b)
144
+ elif op == 'COMPARE_GT': self.push(a > b)
145
+ elif op == 'COMPARE_LT': self.push(a < b)
146
+ elif op == 'COMPARE_GTE': self.push(a >= b)
147
+ elif op == 'COMPARE_LTE': self.push(a <= b)
148
+
149
+ elif op == 'UNARY_NEGATIVE':
150
+ self.push(-self.pop())
151
+
152
+ elif op == 'UNARY_POSITIVE':
153
+ self.push(+self.pop())
154
+
155
+ elif op == 'UNARY_NOT':
156
+ self.push(not self.pop())
157
+
158
+ elif op == 'UNARY_INVERT':
159
+ self.push(~self.pop())
160
+
161
+ elif op == 'LOGICAL_AND':
162
+ b = self.pop()
163
+ a = self.pop()
164
+ self.push(a and b)
165
+
166
+ elif op == 'LOGICAL_OR':
167
+ b = self.pop()
168
+ a = self.pop()
169
+ self.push(a or b)
170
+
171
+ elif op == 'JUMP':
172
+ self.ip = self.labels[arg]
173
+ continue
174
+
175
+ elif op == 'JUMP_IF_FALSE':
176
+ condition = self.pop()
177
+ if not condition:
178
+ self.ip = self.labels[arg]
179
+ continue
180
+
181
+ elif op == 'LABEL':
182
+ pass # Labels are handled in pre-pass
183
+
184
+ else:
185
+ raise RuntimeError(f"Unknown opcode: {op}")
186
+
187
+ self.ip += 1
188
+
189
+
190
+ def main():
191
+ from basicpp.compiler import compile_source
192
+
193
+ # A small integrated test to verify the BVM works as expected
194
+ test_src = """
195
+ START
196
+ SET x $INT = 10 ;
197
+ SET y $INT = 5 ;
198
+ result = (x + y) * 2 ;
199
+ PRINT "The result of (10 + 5) * 2 is:", result ;
200
+ END
201
+ """
202
+ print("Running BVM Self-Test...")
203
+ bc = compile_source(test_src)
204
+ print("===== SOURCE =====")
205
+ print(test_src)
206
+ print("===== BYTECODE =====")
207
+ pprint(bc)
208
+ print("===== OUTPUT =====")
209
+ BVM(bc).run()
210
+
211
+ if __name__ == '__main__':
212
+ main()
213
+
basicpp/cli.py ADDED
@@ -0,0 +1,93 @@
1
+ from . import BVM
2
+ from .compiler import compile_source
3
+ from .compiler.ast_a import write_bytecode_to_file
4
+ import argparse
5
+ import os
6
+ from pprint import pprint
7
+
8
+ parser = argparse.ArgumentParser(
9
+ prog="basicpp",
10
+ usage="%(prog)s [options] <filename>",
11
+ description="Basic++ Interpreter",
12
+ )
13
+
14
+ parser.add_argument('src_file',
15
+ help='the source(.bpp)/byte(.bc) code')
16
+ parser.add_argument('-v', '--verbose',
17
+ action='store_const',
18
+ dest='verbose',
19
+ const=True,
20
+ help='increase output verbosity')
21
+ parser.add_argument('-b', '--bytecode',
22
+ action='store_const',
23
+ const=True,
24
+ dest='bytecode',
25
+ help='display the byte code.')
26
+ parser.add_argument('-bc', '--write-bc',
27
+ action='store_const',
28
+ const=True,
29
+ dest='write_bc',
30
+ help='write the byte code to a file.')
31
+
32
+ args = parser.parse_args()
33
+
34
+ def file_extension(filename: str) -> str:
35
+ if filename.endswith('.bpp'):
36
+ return 'BPP'
37
+ elif filename.endswith('.bc'):
38
+ return 'BC'
39
+ else:
40
+ return filename.split('.')[-1]
41
+
42
+ def run_bc(src: str) -> str:
43
+ return compile_source(src)
44
+
45
+ def run_bpp(src: str) -> None:
46
+ return BVM(compile_source(src)).run()
47
+
48
+ def disp_bytecode(src: str) -> str:
49
+ return compile_source(src)
50
+
51
+
52
+ def cli():
53
+ """The cli for the script
54
+ Usage:
55
+ >>> basicpp <filename> [option]
56
+ """
57
+ if not os.path.exists(args.src_file):
58
+ print(f"Error: File '{args.src_file}' not found.")
59
+ return
60
+
61
+ with open(args.src_file, 'r', encoding='utf-8') as f:
62
+ content = f.read()
63
+
64
+ file_ex = file_extension(args.src_file)
65
+
66
+ if args.verbose:
67
+ print("===== ARGS =====")
68
+ print(f"file_name: {args.src_file}")
69
+ print(f"file_extension: {file_ex}")
70
+ print("================")
71
+
72
+ if args.bytecode:
73
+ pprint(disp_bytecode(content))
74
+ return
75
+
76
+ if args.write_bc:
77
+ write_bytecode_to_file(file_name=f"{args.src_file.split('.')[0]}.bc", content=run_bc(content))
78
+ return
79
+
80
+ if file_ex == 'BPP':
81
+ if args.verbose:
82
+ print("===== SOURCE =====")
83
+ print(content)
84
+ print("===== BYTECODE =====")
85
+ pprint(run_bc(content))
86
+ print("===== OUTPUT =====")
87
+ run_bpp(content)
88
+ elif file_ex == 'BC':
89
+ # Currently, the VM expects a bytecode dictionary.
90
+ # If .bc files are raw source, we run them; otherwise, a loader is needed.
91
+ run_bpp(content)
92
+ else:
93
+ raise ValueError(f"Invalid file extension: {file_ex}")
@@ -0,0 +1,6 @@
1
+ """The compiler to compile the source code to byte code."""
2
+
3
+ from .ast_a import compile_source, write_bytecode_to_file, Parser
4
+ from .lexer import Lexer
5
+
6
+ __all__ = ['compile_source', 'write_bytecode_to_file', 'Parser', 'Lexer']