flavour-pvm 1.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.
- dialects.py +108 -0
- flavour.py +339 -0
- flavour_pvm-1.0.0.dist-info/METADATA +176 -0
- flavour_pvm-1.0.0.dist-info/RECORD +14 -0
- flavour_pvm-1.0.0.dist-info/WHEEL +5 -0
- flavour_pvm-1.0.0.dist-info/entry_points.txt +2 -0
- flavour_pvm-1.0.0.dist-info/top_level.txt +3 -0
- pvm/__init__.py +4 -0
- pvm/compiler.py +221 -0
- pvm/disassembler.py +38 -0
- pvm/lexer.py +126 -0
- pvm/opcodes.py +47 -0
- pvm/parser.py +303 -0
- pvm/vm.py +151 -0
dialects.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Dialect Keyword Mappings for Python 'Flavour'.
|
|
3
|
+
|
|
4
|
+
Defines keyword translations from custom vernacular dialects
|
|
5
|
+
(e.g., Hinglish, Gen-Z) to standard Python keywords and built-in functions.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
HINGLISH_MAP = {
|
|
9
|
+
# Control Flow
|
|
10
|
+
"agar": "if",
|
|
11
|
+
"warna_agar": "elif",
|
|
12
|
+
"warna": "else",
|
|
13
|
+
"jabtak": "while",
|
|
14
|
+
"har": "for",
|
|
15
|
+
"mein": "in",
|
|
16
|
+
"ruko": "break",
|
|
17
|
+
"aage": "continue",
|
|
18
|
+
"pass_karo": "pass",
|
|
19
|
+
|
|
20
|
+
# Functions & Classes
|
|
21
|
+
"kaam": "def",
|
|
22
|
+
"wapas": "return",
|
|
23
|
+
"varg": "class",
|
|
24
|
+
|
|
25
|
+
# Exception Handling
|
|
26
|
+
"koshish": "try",
|
|
27
|
+
"pakdo": "except",
|
|
28
|
+
"aakhirkar": "finally",
|
|
29
|
+
"phenko": "raise",
|
|
30
|
+
|
|
31
|
+
# Logical & Boolean
|
|
32
|
+
"sahi": "True",
|
|
33
|
+
"galat": "False",
|
|
34
|
+
"shunya": "None",
|
|
35
|
+
"khali": "None",
|
|
36
|
+
"aur": "and",
|
|
37
|
+
"ya": "or",
|
|
38
|
+
"nahi": "not",
|
|
39
|
+
"hai": "is",
|
|
40
|
+
|
|
41
|
+
# Import / Context
|
|
42
|
+
"le_aao": "import",
|
|
43
|
+
"se": "from",
|
|
44
|
+
"saath": "with",
|
|
45
|
+
"jaise": "as",
|
|
46
|
+
|
|
47
|
+
# Common Built-ins
|
|
48
|
+
"likho": "print",
|
|
49
|
+
"batao": "print",
|
|
50
|
+
"bolo": "print",
|
|
51
|
+
"pucho": "input",
|
|
52
|
+
"ginti": "range",
|
|
53
|
+
"ginte": "range",
|
|
54
|
+
"lambai": "len",
|
|
55
|
+
"jodo": "sum",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
GENZ_MAP = {
|
|
59
|
+
# Control Flow
|
|
60
|
+
"lowkey": "if",
|
|
61
|
+
"highkey": "elif",
|
|
62
|
+
"deadass": "else",
|
|
63
|
+
"spin": "while",
|
|
64
|
+
"vibe": "for",
|
|
65
|
+
"wit": "in",
|
|
66
|
+
"period": "break",
|
|
67
|
+
"pass_it": "continue",
|
|
68
|
+
"ghost": "pass",
|
|
69
|
+
|
|
70
|
+
# Functions & Return
|
|
71
|
+
"flex": "def",
|
|
72
|
+
"bop": "return",
|
|
73
|
+
"squad": "class",
|
|
74
|
+
|
|
75
|
+
# Exception Handling
|
|
76
|
+
"vibe_check": "try",
|
|
77
|
+
"catch_hands": "except",
|
|
78
|
+
"yeet": "raise",
|
|
79
|
+
|
|
80
|
+
# Logical & Boolean
|
|
81
|
+
"fr": "True",
|
|
82
|
+
"no_cap": "True",
|
|
83
|
+
"cap": "False",
|
|
84
|
+
"sus": "None",
|
|
85
|
+
"and_that": "and",
|
|
86
|
+
"or_nah": "or",
|
|
87
|
+
"nah": "not",
|
|
88
|
+
|
|
89
|
+
# Common Built-ins
|
|
90
|
+
"spill": "print",
|
|
91
|
+
"listen": "input",
|
|
92
|
+
"count": "range",
|
|
93
|
+
"size": "len",
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
DIALECTS = {
|
|
97
|
+
"hinglish": HINGLISH_MAP,
|
|
98
|
+
"genz": GENZ_MAP,
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
def get_dialect(name: str = "hinglish") -> dict:
|
|
102
|
+
"""Retrieve dialect keyword mapping by name (case-insensitive)."""
|
|
103
|
+
normalized = name.strip().lower()
|
|
104
|
+
if normalized not in DIALECTS:
|
|
105
|
+
available = ", ".join(repr(k) for k in DIALECTS)
|
|
106
|
+
raise ValueError(f"Unknown dialect '{name}'. Available: {available}")
|
|
107
|
+
return DIALECTS[normalized]
|
|
108
|
+
|
flavour.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Flavour: A Custom-Keyword Python Dialect & Virtual Machine (Mini-PVM).
|
|
4
|
+
|
|
5
|
+
Features:
|
|
6
|
+
1. Mini-PVM Execution: Compiles custom dialect source directly into bytecode instructions
|
|
7
|
+
and executes on a stack-based virtual machine (no exec()).
|
|
8
|
+
2. Bytecode Disassembler: Inspects the compiled bytecode listing (opcodes, jump targets).
|
|
9
|
+
3. Transpiler: Source-to-source translator to standard Python syntax.
|
|
10
|
+
4. Interactive REPL: Live interactive shell.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
import io
|
|
15
|
+
import os
|
|
16
|
+
import argparse
|
|
17
|
+
import tokenize
|
|
18
|
+
import traceback
|
|
19
|
+
from dialects import get_dialect, DIALECTS
|
|
20
|
+
from pvm.vm import run_source as run_on_pvm, MiniPVM
|
|
21
|
+
from pvm.disassembler import disassemble_source
|
|
22
|
+
from pvm.compiler import compile_source
|
|
23
|
+
|
|
24
|
+
# --- Transpiler Core ---
|
|
25
|
+
|
|
26
|
+
def transpile(source_code: str, dialect: str = "hinglish") -> str:
|
|
27
|
+
"""
|
|
28
|
+
Transpiles source code from a custom dialect into standard Python.
|
|
29
|
+
Uses tokenization so strings, comments, and non-keyword identifiers are preserved.
|
|
30
|
+
"""
|
|
31
|
+
keyword_map = get_dialect(dialect)
|
|
32
|
+
|
|
33
|
+
source_bytes = source_code.encode("utf-8")
|
|
34
|
+
byte_reader = io.BytesIO(source_bytes).readline
|
|
35
|
+
|
|
36
|
+
replacements = []
|
|
37
|
+
try:
|
|
38
|
+
for tok in tokenize.tokenize(byte_reader):
|
|
39
|
+
if tok.type == tokenize.NAME and tok.string in keyword_map:
|
|
40
|
+
replacements.append((tok.start, tok.end, keyword_map[tok.string]))
|
|
41
|
+
except tokenize.TokenError as err:
|
|
42
|
+
raise SyntaxError(f"Tokenization error: {err}") from err
|
|
43
|
+
|
|
44
|
+
replacements.sort(key=lambda item: (item[0][0], item[0][1]), reverse=True)
|
|
45
|
+
|
|
46
|
+
lines = source_code.splitlines(keepends=True)
|
|
47
|
+
if not lines and source_code:
|
|
48
|
+
lines = [source_code]
|
|
49
|
+
|
|
50
|
+
for (s_row, s_col), (e_row, e_col), new_text in replacements:
|
|
51
|
+
line_idx = s_row - 1
|
|
52
|
+
line = lines[line_idx]
|
|
53
|
+
lines[line_idx] = line[:s_col] + new_text + line[e_col:]
|
|
54
|
+
|
|
55
|
+
return "".join(lines)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run_code_transpiled(source_code: str, filename: str = "<flavour>", dialect: str = "hinglish", global_scope: dict = None) -> dict:
|
|
59
|
+
"""Transpiles and executes custom dialect code using Python's exec()."""
|
|
60
|
+
transpiled = transpile(source_code, dialect=dialect)
|
|
61
|
+
|
|
62
|
+
if global_scope is None:
|
|
63
|
+
global_scope = {
|
|
64
|
+
"__name__": "__main__",
|
|
65
|
+
"__file__": os.path.abspath(filename) if filename != "<flavour>" else filename,
|
|
66
|
+
"__doc__": None,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
compiled = compile(transpiled, filename, "exec")
|
|
71
|
+
exec(compiled, global_scope)
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
sys.stderr.write(f"\n[Flavour Transpiler Runtime Error in '{filename}']:\n")
|
|
74
|
+
traceback.print_exc(file=sys.stderr)
|
|
75
|
+
raise exc
|
|
76
|
+
|
|
77
|
+
return global_scope
|
|
78
|
+
|
|
79
|
+
run_code = run_code_transpiled
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# --- Runners and Tools ---
|
|
83
|
+
|
|
84
|
+
def run_file(filepath: str, dialect: str = "hinglish", mode: str = "pvm") -> None:
|
|
85
|
+
"""Runs a source file using either Mini-PVM bytecode execution or transpiler."""
|
|
86
|
+
if not os.path.isfile(filepath):
|
|
87
|
+
sys.stderr.write(f"Error: File '{filepath}' not found.\n")
|
|
88
|
+
sys.exit(1)
|
|
89
|
+
|
|
90
|
+
with open(filepath, "r", encoding="utf-8") as f:
|
|
91
|
+
source = f.read()
|
|
92
|
+
|
|
93
|
+
if mode == "pvm":
|
|
94
|
+
try:
|
|
95
|
+
run_on_pvm(source)
|
|
96
|
+
except Exception as exc:
|
|
97
|
+
sys.stderr.write(f"\n[Mini-PVM Execution Error in '{filepath}']:\n")
|
|
98
|
+
traceback.print_exc(file=sys.stderr)
|
|
99
|
+
sys.exit(1)
|
|
100
|
+
else:
|
|
101
|
+
run_code_transpiled(source, filename=filepath, dialect=dialect)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def disassemble_file(filepath: str) -> None:
|
|
105
|
+
"""Compiles a source file and prints its disassembled bytecode instructions."""
|
|
106
|
+
if not os.path.isfile(filepath):
|
|
107
|
+
sys.stderr.write(f"Error: File '{filepath}' not found.\n")
|
|
108
|
+
sys.exit(1)
|
|
109
|
+
|
|
110
|
+
with open(filepath, "r", encoding="utf-8") as f:
|
|
111
|
+
source = f.read()
|
|
112
|
+
|
|
113
|
+
print(disassemble_source(source))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def transpile_file(filepath: str, output_path: str = None, dialect: str = "hinglish") -> str:
|
|
117
|
+
"""Transpiles a file to standard Python and saves it or prints to stdout."""
|
|
118
|
+
if not os.path.isfile(filepath):
|
|
119
|
+
sys.stderr.write(f"Error: File '{filepath}' not found.\n")
|
|
120
|
+
sys.exit(1)
|
|
121
|
+
|
|
122
|
+
with open(filepath, "r", encoding="utf-8") as f:
|
|
123
|
+
source = f.read()
|
|
124
|
+
|
|
125
|
+
transpiled = transpile(source, dialect=dialect)
|
|
126
|
+
|
|
127
|
+
if output_path:
|
|
128
|
+
with open(output_path, "w", encoding="utf-8") as f:
|
|
129
|
+
f.write(transpiled)
|
|
130
|
+
print(f"Transpiled code successfully written to: {output_path}")
|
|
131
|
+
else:
|
|
132
|
+
print(transpiled)
|
|
133
|
+
|
|
134
|
+
return transpiled
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def start_repl(dialect: str = "hinglish", mode: str = "pvm") -> None:
|
|
138
|
+
"""Starts an interactive REPL shell on Mini-PVM or transpiler."""
|
|
139
|
+
print("=" * 65)
|
|
140
|
+
print(f" Flavour Interactive REPL ({dialect.capitalize()} Dialect - Mode: {mode.upper()})")
|
|
141
|
+
print(" Type custom code, or 'exit()' / Ctrl+C to quit.")
|
|
142
|
+
print("=" * 65)
|
|
143
|
+
|
|
144
|
+
pvm_env = {}
|
|
145
|
+
transpile_scope = {"__name__": "__main__", "__doc__": None}
|
|
146
|
+
|
|
147
|
+
buffer = []
|
|
148
|
+
in_multiline = False
|
|
149
|
+
|
|
150
|
+
while True:
|
|
151
|
+
try:
|
|
152
|
+
prompt = "... " if in_multiline else ">>> "
|
|
153
|
+
line = input(prompt)
|
|
154
|
+
|
|
155
|
+
if not in_multiline and line.strip() in ("exit()", "quit()"):
|
|
156
|
+
print("Alvida! (Goodbye)")
|
|
157
|
+
break
|
|
158
|
+
|
|
159
|
+
buffer.append(line)
|
|
160
|
+
|
|
161
|
+
stripped = line.strip()
|
|
162
|
+
if stripped.endswith(":") or (in_multiline and stripped != ""):
|
|
163
|
+
in_multiline = True
|
|
164
|
+
continue
|
|
165
|
+
|
|
166
|
+
code_block = "\n".join(buffer)
|
|
167
|
+
buffer = []
|
|
168
|
+
in_multiline = False
|
|
169
|
+
|
|
170
|
+
if not code_block.strip():
|
|
171
|
+
continue
|
|
172
|
+
|
|
173
|
+
if mode == "pvm":
|
|
174
|
+
try:
|
|
175
|
+
pvm_env = run_on_pvm(code_block, environment=pvm_env)
|
|
176
|
+
except Exception as e:
|
|
177
|
+
print(f"PVM Error: {e}")
|
|
178
|
+
else:
|
|
179
|
+
transpiled_block = transpile(code_block, dialect=dialect)
|
|
180
|
+
try:
|
|
181
|
+
expr = compile(transpiled_block.strip(), "<repl>", "eval")
|
|
182
|
+
res = eval(expr, transpile_scope)
|
|
183
|
+
if res is not None:
|
|
184
|
+
print(repr(res))
|
|
185
|
+
except SyntaxError:
|
|
186
|
+
compiled = compile(transpiled_block, "<repl>", "exec")
|
|
187
|
+
exec(compiled, transpile_scope)
|
|
188
|
+
|
|
189
|
+
except (KeyboardInterrupt, EOFError):
|
|
190
|
+
print("\nAlvida! (Exiting)")
|
|
191
|
+
break
|
|
192
|
+
except Exception as e:
|
|
193
|
+
print(f"Error: {e}")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# --- CLI Parser ---
|
|
197
|
+
|
|
198
|
+
def parse_cli_args(argv=None):
|
|
199
|
+
if argv is None:
|
|
200
|
+
argv = sys.argv[1:]
|
|
201
|
+
|
|
202
|
+
parser = argparse.ArgumentParser(
|
|
203
|
+
description="Flavour: Custom-Keyword Python Dialect & Virtual Machine (Mini-PVM)"
|
|
204
|
+
)
|
|
205
|
+
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
|
206
|
+
|
|
207
|
+
# 'run' subcommand
|
|
208
|
+
run_parser = subparsers.add_parser("run", help="Run a source file on Mini-PVM or via Transpiler")
|
|
209
|
+
run_parser.add_argument("file", help="Path to custom dialect source file (.mypy)")
|
|
210
|
+
run_parser.add_argument(
|
|
211
|
+
"--mode",
|
|
212
|
+
choices=["pvm", "transpile"],
|
|
213
|
+
default="pvm",
|
|
214
|
+
help="Execution mode: 'pvm' (Stack Virtual Machine, default) or 'transpile'",
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# 'dis' subcommand (Disassemble)
|
|
218
|
+
dis_parser = subparsers.add_parser("dis", help="Disassemble source file into PVM bytecode")
|
|
219
|
+
dis_parser.add_argument("file", help="Path to custom dialect source file")
|
|
220
|
+
|
|
221
|
+
# 'transpile' subcommand
|
|
222
|
+
trans_parser = subparsers.add_parser("transpile", help="Transpile .mypy to standard Python")
|
|
223
|
+
trans_parser.add_argument("file", help="Path to custom dialect source file")
|
|
224
|
+
trans_parser.add_argument("-o", "--output", help="Optional output file path")
|
|
225
|
+
|
|
226
|
+
# 'repl' subcommand
|
|
227
|
+
repl_parser = subparsers.add_parser("repl", help="Start an interactive REPL shell")
|
|
228
|
+
repl_parser.add_argument(
|
|
229
|
+
"--mode",
|
|
230
|
+
choices=["pvm", "transpile"],
|
|
231
|
+
default="pvm",
|
|
232
|
+
help="REPL mode: 'pvm' (default) or 'transpile'",
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Extract --dialect and --mode flags if present anywhere in argv
|
|
236
|
+
dialect = "hinglish"
|
|
237
|
+
mode = "pvm"
|
|
238
|
+
cleaned = []
|
|
239
|
+
i = 0
|
|
240
|
+
while i < len(argv):
|
|
241
|
+
if argv[i] == "--dialect" and i + 1 < len(argv):
|
|
242
|
+
dialect = argv[i + 1]
|
|
243
|
+
i += 2
|
|
244
|
+
elif argv[i].startswith("--dialect="):
|
|
245
|
+
dialect = argv[i].split("=", 1)[1]
|
|
246
|
+
i += 1
|
|
247
|
+
elif argv[i] == "--mode" and i + 1 < len(argv):
|
|
248
|
+
mode = argv[i + 1]
|
|
249
|
+
i += 2
|
|
250
|
+
elif argv[i].startswith("--mode="):
|
|
251
|
+
mode = argv[i].split("=", 1)[1]
|
|
252
|
+
i += 1
|
|
253
|
+
else:
|
|
254
|
+
cleaned.append(argv[i])
|
|
255
|
+
i += 1
|
|
256
|
+
|
|
257
|
+
if dialect.lower() not in DIALECTS:
|
|
258
|
+
sys.stderr.write(f"Error: Unknown dialect '{dialect}'. Available: {', '.join(DIALECTS.keys())}\n")
|
|
259
|
+
sys.exit(2)
|
|
260
|
+
|
|
261
|
+
if cleaned and cleaned[0] not in ("run", "dis", "transpile", "repl", "-h", "--help"):
|
|
262
|
+
cleaned = ["run"] + cleaned
|
|
263
|
+
|
|
264
|
+
args = parser.parse_args(cleaned)
|
|
265
|
+
args.dialect = dialect.lower()
|
|
266
|
+
args.mode = mode.lower()
|
|
267
|
+
return args
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def interactive_menu():
|
|
271
|
+
"""Interactive launcher menu when no CLI arguments are supplied."""
|
|
272
|
+
while True:
|
|
273
|
+
print("\n" + "=" * 60)
|
|
274
|
+
print(" ๐ถ๏ธ Flavour: Custom-Keyword Python Dialect & Mini-PVM")
|
|
275
|
+
print("=" * 60)
|
|
276
|
+
print(" 1. Run an existing .mypy file")
|
|
277
|
+
print(" 2. Create and run a new .mypy file")
|
|
278
|
+
print(" 3. Launch Interactive REPL Shell")
|
|
279
|
+
print(" 4. Disassemble .mypy file into PVM Bytecode")
|
|
280
|
+
print(" 5. Exit")
|
|
281
|
+
print("=" * 60)
|
|
282
|
+
|
|
283
|
+
try:
|
|
284
|
+
choice = input("Enter choice [1-5]: ").strip()
|
|
285
|
+
except (KeyboardInterrupt, EOFError):
|
|
286
|
+
print("\nAlvida! (Exiting)")
|
|
287
|
+
break
|
|
288
|
+
|
|
289
|
+
if choice == "1":
|
|
290
|
+
filepath = input("Enter .mypy file path (e.g. examples/fizzbuzz.mypy): ").strip()
|
|
291
|
+
if filepath:
|
|
292
|
+
run_file(filepath, mode="pvm")
|
|
293
|
+
elif choice == "2":
|
|
294
|
+
filename = input("Enter file name [default: my_code.mypy]: ").strip() or "my_code.mypy"
|
|
295
|
+
print("\nEnter your custom code below. Type 'RUN' on a new line to execute:\n" + "-" * 50)
|
|
296
|
+
lines = []
|
|
297
|
+
while True:
|
|
298
|
+
try:
|
|
299
|
+
line = input()
|
|
300
|
+
if line.strip() == "RUN":
|
|
301
|
+
break
|
|
302
|
+
lines.append(line)
|
|
303
|
+
except (KeyboardInterrupt, EOFError):
|
|
304
|
+
break
|
|
305
|
+
code = "\n".join(lines)
|
|
306
|
+
with open(filename, "w", encoding="utf-8") as f:
|
|
307
|
+
f.write(code)
|
|
308
|
+
print(f"\n[Saved to '{filename}'] Executing on Mini-PVM:\n" + "-" * 50)
|
|
309
|
+
run_file(filename, mode="pvm")
|
|
310
|
+
elif choice == "3":
|
|
311
|
+
start_repl(mode="pvm")
|
|
312
|
+
elif choice == "4":
|
|
313
|
+
filepath = input("Enter .mypy file path to disassemble: ").strip()
|
|
314
|
+
if filepath:
|
|
315
|
+
disassemble_file(filepath)
|
|
316
|
+
elif choice in ("5", "q", "exit"):
|
|
317
|
+
print("Alvida! (Exiting)")
|
|
318
|
+
break
|
|
319
|
+
else:
|
|
320
|
+
print("Invalid choice. Please enter 1, 2, 3, 4, or 5.")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def main():
|
|
324
|
+
args = parse_cli_args()
|
|
325
|
+
|
|
326
|
+
if args.command == "run":
|
|
327
|
+
run_file(args.file, dialect=args.dialect, mode=args.mode)
|
|
328
|
+
elif args.command == "dis":
|
|
329
|
+
disassemble_file(args.file)
|
|
330
|
+
elif args.command == "transpile":
|
|
331
|
+
transpile_file(args.file, output_path=args.output, dialect=args.dialect)
|
|
332
|
+
elif args.command == "repl":
|
|
333
|
+
start_repl(dialect=args.dialect, mode=args.mode)
|
|
334
|
+
else:
|
|
335
|
+
interactive_menu()
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
if __name__ == "__main__":
|
|
339
|
+
main()
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flavour-pvm
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A custom vernacular Python dialect powered by a stack-based Mini-PVM
|
|
5
|
+
Author-email: Rahul Deb <your-email@example.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# ๐ถ๏ธ Flavour: Custom-Keyword Python Dialect & Virtual Machine (Mini-PVM)
|
|
13
|
+
|
|
14
|
+
> **A custom vernacular Python dialect featuring an authentic Stack-Based Virtual Machine (Mini-PVM), Bytecode Compiler with Jump Backpatching, Disassembler, and Source Transpiler.**
|
|
15
|
+
|
|
16
|
+
Flavour allows developers to write code using custom vernacular keywordsโsuch as **Hinglish** (`agar`, `warna`, `jabtak`, `likho`, `har`, `mein`) or **Gen-Z** (`lowkey`, `deadass`, `spin`, `spill`).
|
|
17
|
+
|
|
18
|
+
Unlike simple text-replacement tools, Flavour provides a **genuine Stack-Based Bytecode Virtual Machine (Mini-PVM)** that compiles source code into low-level bytecode instructions and executes them on an evaluation stackโmirroring how CPython's `ceval.c` works.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## ๐๏ธ System Architecture
|
|
23
|
+
|
|
24
|
+
```mermaid
|
|
25
|
+
flowchart TD
|
|
26
|
+
A[".mypy Source Code (Hinglish / Gen-Z)"] --> B["Lexer (Tokenizer)"]
|
|
27
|
+
B --> C["Recursive Descent Parser (AST)"]
|
|
28
|
+
C --> D["Bytecode Compiler (Jump Backpatching)"]
|
|
29
|
+
D --> E["Bytecode Instructions (Opcodes + Args)"]
|
|
30
|
+
|
|
31
|
+
subgraph PVM ["Mini-PVM (Stack-Based Virtual Machine)"]
|
|
32
|
+
F["Instruction Pointer (IP)"]
|
|
33
|
+
G["Operand Stack"]
|
|
34
|
+
H["Frame Environment (Symbol Table)"]
|
|
35
|
+
E --> F
|
|
36
|
+
F --> I["Fetch -> Decode -> Execute Loop"]
|
|
37
|
+
I <--> G
|
|
38
|
+
I <--> H
|
|
39
|
+
I --> J["Console Output"]
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
E --> K["Bytecode Disassembler ('dis')"]
|
|
43
|
+
A -.-> L["Transpiler Mode (Optional exec)"]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## โก Quick Start
|
|
49
|
+
|
|
50
|
+
Zero external dependenciesโuses 100% standard Python 3!
|
|
51
|
+
|
|
52
|
+
### 1. Execute Directly on the Mini-PVM
|
|
53
|
+
```bash
|
|
54
|
+
python flavour.py examples/loop.mypy
|
|
55
|
+
```
|
|
56
|
+
```bash
|
|
57
|
+
python flavour.py examples/fizzbuzz.mypy
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 2. Disassemble and View Bytecode (The PVM Inspector)
|
|
61
|
+
Shows the compiled instruction stream, opcodes, and jump target addresses:
|
|
62
|
+
```bash
|
|
63
|
+
python flavour.py dis examples/loop.mypy
|
|
64
|
+
```
|
|
65
|
+
```text
|
|
66
|
+
ADDR OPCODE ARGUMENT / TARGET
|
|
67
|
+
-------------------------------------------------------
|
|
68
|
+
0000 LOAD_CONST '=== Mini-PVM While Loop Demo ==='
|
|
69
|
+
0001 PRINT_VALUE
|
|
70
|
+
0002 LOAD_CONST 1
|
|
71
|
+
0003 STORE_NAME 'ginti'
|
|
72
|
+
0004 LOAD_CONST 0
|
|
73
|
+
0005 STORE_NAME 'kul_jod'
|
|
74
|
+
0006 LOAD_NAME 'ginti'
|
|
75
|
+
0007 LOAD_CONST 5
|
|
76
|
+
0008 COMPARE_OP '<='
|
|
77
|
+
0009 POP_JUMP_IF_FALSE to 0029
|
|
78
|
+
...
|
|
79
|
+
0028 JUMP_ABSOLUTE to 0006
|
|
80
|
+
0029 LOAD_CONST '--- Loop Completed ---'
|
|
81
|
+
0030 PRINT_VALUE
|
|
82
|
+
0036 HALT
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 3. Launch the Interactive REPL on Mini-PVM
|
|
86
|
+
```bash
|
|
87
|
+
python flavour.py repl
|
|
88
|
+
```
|
|
89
|
+
```python
|
|
90
|
+
>>> x = 10
|
|
91
|
+
>>> agar x > 5:
|
|
92
|
+
... likho("Sab badiya!")
|
|
93
|
+
...
|
|
94
|
+
Sab badiya!
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 4. Transpile Mode (Source-to-Source)
|
|
98
|
+
Inspect the transpiled standard Python code:
|
|
99
|
+
```bash
|
|
100
|
+
python flavour.py transpile examples/fizzbuzz.mypy
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## โ๏ธ Mini-PVM Instruction Set (Opcodes)
|
|
106
|
+
|
|
107
|
+
| Opcode | Argument | Description | Stack Effect |
|
|
108
|
+
| :--- | :--- | :--- | :--- |
|
|
109
|
+
| `LOAD_CONST` | `value` | Push constant onto operand stack | `[] -> [value]` |
|
|
110
|
+
| `LOAD_NAME` | `var_name` | Load variable value from environment | `[] -> [val]` |
|
|
111
|
+
| `STORE_NAME` | `var_name` | Pop top of stack and store in variable | `[val] -> []` |
|
|
112
|
+
| `BINARY_ADD` | - | Pop two operands, add them, push result | `[a, b] -> [a + b]` |
|
|
113
|
+
| `BINARY_SUB` | - | Pop two operands, subtract, push result | `[a, b] -> [a - b]` |
|
|
114
|
+
| `BINARY_MUL` | - | Pop two operands, multiply, push result | `[a, b] -> [a * b]` |
|
|
115
|
+
| `BINARY_DIV` | - | Pop two operands, divide, push result | `[a, b] -> [a / b]` |
|
|
116
|
+
| `BINARY_MOD` | - | Pop two operands, modulo, push result | `[a, b] -> [a % b]` |
|
|
117
|
+
| `COMPARE_OP` | `operator` | Pop two operands, compare (`<`, `>`, `==`, etc.) | `[a, b] -> [bool]` |
|
|
118
|
+
| `POP_JUMP_IF_FALSE`| `target_ip` | Pop top; if `False`, jump instruction pointer to `target_ip` | `[cond] -> []` |
|
|
119
|
+
| `JUMP_ABSOLUTE` | `target_ip` | Unconditionally jump `IP` to `target_ip` | `[] -> []` |
|
|
120
|
+
| `CALL_BUILTIN` | `(func, count)`| Call built-in helper (`str`, `int`, `len`, etc.) | `[args...] -> [res]` |
|
|
121
|
+
| `PRINT_VALUE` | - | Pop top of stack and print to console | `[val] -> []` |
|
|
122
|
+
| `HALT` | - | Terminate virtual machine execution | - |
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## ๐ Keyword Cheat Sheet
|
|
127
|
+
|
|
128
|
+
| Hinglish Keyword | Standard Python | Meaning / Usage |
|
|
129
|
+
| :--- | :--- | :--- |
|
|
130
|
+
| `agar` | `if` | Conditional branch |
|
|
131
|
+
| `warna_agar` | `elif` | Else-if branch |
|
|
132
|
+
| `warna` | `else` | Else fallback |
|
|
133
|
+
| `jabtak` | `while` | While loop |
|
|
134
|
+
| `har` $\dots$ `mein` | `for` $\dots$ `in` | For loop over iterable |
|
|
135
|
+
| `ginte` / `ginti` | `range` | Range generator |
|
|
136
|
+
| `likho` / `batao` | `print` | Output print statement |
|
|
137
|
+
| `sahi` | `True` | Boolean true |
|
|
138
|
+
| `galat` | `False` | Boolean false |
|
|
139
|
+
| `shunya` | `None` | Null / None |
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## ๐ Project Structure
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
flavour/
|
|
147
|
+
โโโ pvm/
|
|
148
|
+
โ โโโ opcodes.py # Opcode definitions and Instruction data classes
|
|
149
|
+
โ โโโ lexer.py # Tokenizer converting source to typed tokens
|
|
150
|
+
โ โโโ parser.py # Recursive descent AST parser
|
|
151
|
+
โ โโโ compiler.py # Bytecode generator with jump backpatching
|
|
152
|
+
โ โโโ vm.py # Stack-based Mini-PVM execution engine
|
|
153
|
+
โ โโโ disassembler.py # Bytecode formatter (like Python's 'dis' module)
|
|
154
|
+
โโโ flavour.py # Unified CLI (run, dis, transpile, repl)
|
|
155
|
+
โโโ dialects.py # Keyword dictionaries (Hinglish, Gen-Z)
|
|
156
|
+
โโโ test_pvm.py # Unit tests for the Virtual Machine & Compiler
|
|
157
|
+
โโโ test_flavour.py # Unit tests for the Transpiler
|
|
158
|
+
โโโ README.md # Documentation & presentation guide
|
|
159
|
+
โโโ examples/
|
|
160
|
+
โโโ loop.mypy # While-loop accumulator on Mini-PVM
|
|
161
|
+
โโโ branch.mypy # Multi-branch conditionals (agar/warna_agar/warna)
|
|
162
|
+
โโโ calc.mypy # Arithmetic calculator and expressions
|
|
163
|
+
โโโ fizzbuzz.mypy # Range-based loops and modulo logic
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## ๐งช Running the Tests
|
|
169
|
+
|
|
170
|
+
To verify both the Virtual Machine and Transpiler suites:
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
python3 test_pvm.py -v && python3 test_flavour.py -v
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
All 18 tests verify tokenization, AST generation, jump address calculation, stack arithmetic, loop execution, and disassembly.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
dialects.py,sha256=cSpWb6wa8BgM5del3rMIU2HFD0DDqqx_viW6zH-3QEc,2242
|
|
2
|
+
flavour.py,sha256=gMAtRRmZozTmtS48-YuGf4gF1k6rwGRWKYtOmdOk-KU,11693
|
|
3
|
+
pvm/__init__.py,sha256=-trjhTbc_nuYhp-fZ8L2h7YKnd0aMdO27AnqV6ZkbIU,27
|
|
4
|
+
pvm/compiler.py,sha256=SKqynjC-CL0o3VUpw1tAP0XzULf2Zz4VOREWMoYWMUU,7523
|
|
5
|
+
pvm/disassembler.py,sha256=Ttt49FEakheFN847zloig5PT34Gf1sriJd8O7z-bt_s,1310
|
|
6
|
+
pvm/lexer.py,sha256=rMrYh0X1sVASXgjBM4iWvCgooQy9Dk7WW1tbnK_MYVo,4008
|
|
7
|
+
pvm/opcodes.py,sha256=MVaVz5kKOYGE0Q01ZLTtjMDa45AvuHZSGpytyRZYg6U,1582
|
|
8
|
+
pvm/parser.py,sha256=19H55hOxYuWCclpAJ-4lQcs-gbtztiSJgDoXkalCO24,9251
|
|
9
|
+
pvm/vm.py,sha256=okbtEBfgz_ungBqCoF8XJPA2uLa3_cdU2SMnqVcr2Ck,5423
|
|
10
|
+
flavour_pvm-1.0.0.dist-info/METADATA,sha256=-e0uTh0jRp_S3-s0UkM_F83noRid8f_LwY5Jl4XEvyg,6552
|
|
11
|
+
flavour_pvm-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
flavour_pvm-1.0.0.dist-info/entry_points.txt,sha256=beukKMIZ-INcN1w3_iVgytQZ8ye3Nj3WOqMWEK6iWyg,41
|
|
13
|
+
flavour_pvm-1.0.0.dist-info/top_level.txt,sha256=vjwi4jjoMtMMlhkBzm6wuh5aKR2G2E02GRcAAMinQ4U,21
|
|
14
|
+
flavour_pvm-1.0.0.dist-info/RECORD,,
|
pvm/__init__.py
ADDED