-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBootstrap_fail.montyp
More file actions
291 lines (250 loc) · 9.73 KB
/
Bootstrap_fail.montyp
File metadata and controls
291 lines (250 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
# Monthy (Montyp) Compiler v0.2 — indentation-free Monthyp → auto-indented Python
# Patched to avoid misinterpreting raw Python:
# - Monthyp 'if' matches colon-less only (Python 'if ...:' passes through)
# - Monthyp 'def' matches space-arg style only (not Python 'def name(args):')
# - Optional 'py:' prefix to force raw Python passthrough
#
# CLI:
# python montyp_compiler.py FILE.montyp -> writes FILE.py
# python montyp_compiler.py -c "say: Hi {2 plus 2}" -> prints Python
# python montyp_compiler.py FILE.montyp --run -> compiles and runs
# python montyp_compiler.py FILE.montyp --indent 2 -> 2-space indents
# python montyp_compiler.py FILE.montyp --tabs -> tab indents
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
from typing import List, Optional
import shlex
WORD_OPS = {
' plus ': ' + ',
' minus ': ' - ',
' times ': ' * ',
' over ': ' / ',
}
LITERALS = {
' true ': ' True ',
' false ': ' False ',
' null ': ' None ',
}
COMPARATORS = [
(r'\bis at least\b', '>='),
(r'\bis at most\b', '<='),
(r'\bis greater than\b', '>'),
(r'\bis less than\b', '<'),
(r'\bequals\b', '=='),
(r'\bnot equals\b', '!='),
]
KEYWORDS = {'if', 'def', 'return', 'repeat', 'say', 'end'}
def looks_like_expr(s: str) -> bool:
"""Heuristic: does string contain operators => treat as single expr arg."""
if re.search(r'[+\-*/]', s):
return True
return bool(re.search(r'\b(plus|minus|times|over)\b', s, flags=re.I))
class MonthyCompiler:
def __init__(self, indent_unit: str = ' '):
self.indent_unit = indent_unit
self.py_lines: List[str] = []
self.indent = 0
self.stack: List[str] = [] # track block types ('if','repeat','def')
def _emit(self, s: str = "") -> None:
self.py_lines.append(self.indent_unit * self.indent + s)
@staticmethod
def _strip_comment(line: str) -> str:
# Remove comments (# or //) if not inside quotes
dq = 0
sq = 0
out = []
i = 0
while i < len(line):
c = line[i]
if c == '"' and not sq:
dq ^= 1
elif c == "'" and not dq:
sq ^= 1
if not dq and not sq:
if c == '#':
break
if c == '/' and i + 1 < len(line) and line[i + 1] == '/':
break
out.append(c)
i += 1
return ''.join(out).rstrip()
def _tx_expr(self, expr: str) -> str:
s = f" {expr} "
# word operators
for w, op in WORD_OPS.items():
s = s.replace(w, op)
# comparators
for pat, repl in COMPARATORS:
s = re.sub(pat, repl, s, flags=re.I)
# literals
for w, lit in LITERALS.items():
s = s.replace(w, lit)
return s.strip()
def compile(self, source: str, *, filename: Optional[str] = None) -> str:
self.py_lines.clear()
self.indent = 0
self.stack.clear()
for idx, raw in enumerate(source.splitlines(), start=1):
try:
self._compile_line(raw)
except Exception as e:
where = f"{filename or '<string>'}:{idx}"
raise type(e)(f"{e} (at {where})")
if self.stack:
raise SyntaxError("Missing 'end' for: " + ' > '.join(self.stack))
return "\n".join(self.py_lines) + "\n"
def _compile_line(self, raw: str) -> None:
original = raw
line = raw.strip()
if not line:
return
line = self._strip_comment(line)
if not line:
return
low = line.lower()
# --- Raw Python passthrough with 'py:' prefix ---
m = re.match(r'^py:\s*(.*)$', line, flags=re.I)
if m:
self._emit(m.group(1))
return
# --- Block end ---
if re.fullmatch(r'end', low, flags=re.I):
if not self.stack:
self._emit("# ERROR: 'end' with no open block")
else:
self.stack.pop()
self.indent = max(0, self.indent - 1)
return
# --- say: (f-string) ---
m = re.match(r'^say:\s*(.*)$', line, flags=re.I)
if m:
inner = self._tx_expr(m.group(1))
esc = inner.replace('\\', r'\\').replace('"', r'\"')
self._emit(f'print(f"{esc}")')
return
# --- say <expr> ---
m = re.match(r'^say\s+(.+)$', line, flags=re.I)
if m:
expr = self._tx_expr(m.group(1))
self._emit(f"print({expr})")
return
# --- if ... then ... (single line) ---
m = re.match(r'^if\s+(.+?)\s+then\s+(.+)$', line, flags=re.I)
if m:
cond = self._tx_expr(m.group(1))
self._emit(f"if {cond}:")
self.indent += 1
self.stack.append('if')
self._compile_line(m.group(2).strip())
self.stack.pop()
self.indent -= 1
return
# --- Monthyp if header: colon-less only (Python 'if ...:' passes through) ---
m = re.match(r'^if\s+(.+?)\s*$', line, flags=re.I)
if m:
cond = self._tx_expr(m.group(1))
self._emit(f"if {cond}:")
self.indent += 1
self.stack.append('if')
return
# --- repeat N times [do|:] ---
m = re.match(r'^repeat\s+(.+?)\s+times(?:\s+do)?(?::\s*|\s*)$', line, flags=re.I)
if m:
n = self._tx_expr(m.group(1))
self._emit(f"for _ in range(int({n})):")
self.indent += 1
self.stack.append('repeat')
return
# --- Monthyp def header: space-separated args only (not Python def foo(bar):) ---
m = re.match(r'^def\s+([A-Za-z_][A-Za-z0-9_]*)\s*((?:[A-Za-z_][A-Za-z0-9_]*\s*)*)$', line, flags=re.I)
if m:
name = m.group(1)
arg_str = (m.group(2) or '').strip()
args = [a for a in arg_str.split() if a]
arglist = ", ".join(args)
self._emit(f"def {name}({arglist}):")
self.indent += 1
self.stack.append('def')
return
# --- return expr ---
m = re.match(r'^return\s+(.+)$', line, flags=re.I)
if m:
expr = self._tx_expr(m.group(1))
self._emit(f"return {expr}")
return
# --- assignment: name is expr ---
m = re.match(r'^([A-Za-z_][A-Za-z0-9_]*)\s+is\s+(.+)$', line, flags=re.I)
if m:
var = m.group(1)
expr = self._tx_expr(m.group(2))
self._emit(f"{var} = {expr}")
return
# --- function-call sugar: func arg1 arg2 ... (skip if already looks like Python call) ---
if '(' not in original:
m = re.match(r'^([A-Za-z_][A-Za-z0-9_]*)\s+(.+)$', line)
if m:
fname = m.group(1)
if fname.lower() not in KEYWORDS:
rest = m.group(2).strip()
if looks_like_expr(rest):
arg = self._tx_expr(rest)
self._emit(f"{fname}({arg})")
return
try:
parts = shlex.split(rest)
except ValueError:
parts = [rest]
args = ", ".join(self._tx_expr(p) for p in parts)
self._emit(f"{fname}({args})")
return
# --- Fallback: raw passthrough (advanced users can inject Python) ---
self._emit(original)
def compile_file(in_path: Path, *, indent_unit: str) -> str:
src = in_path.read_text(encoding='utf-8')
compiler = MonthyCompiler(indent_unit=indent_unit)
py = compiler.compile(src, filename=str(in_path))
out = in_path.with_suffix('.py')
out.write_text(py, encoding='utf-8')
return str(out)
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description='Monthyp (Monthy) v0.2 compiler (indentation-free source → Python)')
ap.add_argument('file', nargs='?', help='Input .montyp/.monthy file')
ap.add_argument('-c', '--code', help='Inline Montyp code string to compile and print Python')
ap.add_argument('--run', action='store_true', help='Execute the compiled Python after compiling')
ap.add_argument('-o', '--output', help='Write compiled Python to this path (default: alongside input)')
ap.add_argument('--indent', type=int, default=4, help='Spaces per indent level (default: 4)')
ap.add_argument('--tabs', action='store_true', help='Indent with tabs instead of spaces')
args = ap.parse_args(argv)
indent_unit = '\t' if args.tabs else (' ' * max(0, args.indent))
if args.code is not None:
compiler = MonthyCompiler(indent_unit=indent_unit)
py = compiler.compile(args.code, filename='<arg -c>')
sys.stdout.write(py)
if args.run:
ns = {}
exec(py, ns, ns)
return 0
if not args.file:
ap.error('Provide a .montyp/.monthy file or use -c to compile a string')
in_path = Path(args.file)
if not in_path.exists():
ap.error(f'File not found: {in_path}')
if args.output:
compiler = MonthyCompiler(indent_unit=indent_unit)
py = compiler.compile(in_path.read_text(encoding='utf-8'), filename=str(in_path))
Path(args.output).write_text(py, encoding='utf-8')
py_path = args.output
else:
py_path = compile_file(in_path, indent_unit=indent_unit)
print(py_path)
if args.run:
code = Path(py_path).read_text(encoding='utf-8')
ns = {}
exec(code, ns, ns)
return 0
if __name__ == '__main__':
raise SystemExit(main())