echidnae-javascript 0.3.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,473 @@
1
+ """Binding-aware front end for the experimental python-browser/1 profile."""
2
+
3
+ import ast
4
+ from dataclasses import dataclass
5
+ import hashlib
6
+ import symtable
7
+ from typing import Literal
8
+
9
+
10
+ ValueType = Literal['statement', 'python-value', 'python-none', 'python-bool',
11
+ 'python-int', 'python-str', 'python-tuple', 'python-exception',
12
+ 'python-type', 'callable', 'javascript-type', 'javascript-array',
13
+ 'javascript-number', 'javascript-callable', 'async-callable',
14
+ 'python-coroutine', 'python-promise']
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SourceSpan:
19
+ filename: str
20
+ line: int
21
+ column: int
22
+ end_line: int
23
+ end_column: int
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Diagnostic:
28
+ code: str
29
+ message: str
30
+ span: SourceSpan
31
+ phase: Literal['parse', 'bind', 'validate'] = 'validate'
32
+
33
+
34
+ class CompileError(ValueError):
35
+ def __init__(self, diagnostic: Diagnostic):
36
+ self.diagnostic = diagnostic
37
+ span = diagnostic.span
38
+ super().__init__(f'{span.filename}:{span.line}:{span.column}: {diagnostic.code}: {diagnostic.message}')
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Binding:
43
+ id: str
44
+ name: str
45
+ scope: str
46
+ kind: Literal['constant', 'function', 'parameter', 'local', 'javascript', 'builtin', 'source']
47
+ target: str | None = None
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class IRNode:
52
+ kind: str
53
+ value_type: ValueType
54
+ span: SourceSpan
55
+ fields: tuple[tuple[str, object], ...] = ()
56
+
57
+ def field(self, name, default=None):
58
+ return dict(self.fields).get(name, default)
59
+
60
+ def to_dict(self):
61
+ def encode(value):
62
+ if isinstance(value, IRNode):
63
+ return value.to_dict()
64
+ if isinstance(value, tuple):
65
+ return [encode(item) for item in value]
66
+ return value
67
+ return {'kind': self.kind, 'value_type': self.value_type,
68
+ 'span': dict(vars(self.span)),
69
+ 'fields': {key: encode(value) for key, value in self.fields}}
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ModuleIR:
74
+ filename: str
75
+ source_sha256: str
76
+ bindings: tuple[Binding, ...]
77
+ body: tuple[IRNode, ...]
78
+ profile: str = 'python-browser/1'
79
+ schema_version: int = 1
80
+
81
+ def to_dict(self):
82
+ return {'profile': self.profile, 'schema_version': self.schema_version,
83
+ 'filename': self.filename, 'source_sha256': self.source_sha256,
84
+ 'bindings': [dict(vars(binding)) for binding in self.bindings],
85
+ 'body': [node.to_dict() for node in self.body]}
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class SourceImport:
90
+ name: str
91
+ module: str
92
+ export: str
93
+ value_type: ValueType
94
+
95
+
96
+ _BROWSER_APIS = {'read_text': 1, 'write_text': 2, 'on_click': 2, 'unsubscribe': 1, 'fetch_text': 1}
97
+
98
+
99
+ _BUILTINS = {'len', 'print', 'isinstance', 'str', 'int', 'bool', 'tuple', 'TypeError'}
100
+ _TYPES = {'str', 'int', 'bool', 'tuple'}
101
+ _BINARY = {ast.Add: '+', ast.Sub: '-', ast.Mult: '*', ast.FloorDiv: '//', ast.Mod: '%'}
102
+ _COMPARE = {ast.Eq: '==', ast.NotEq: '!=', ast.Lt: '<', ast.LtE: '<=', ast.Gt: '>',
103
+ ast.GtE: '>=', ast.Is: 'is', ast.IsNot: 'is not', ast.In: 'in', ast.NotIn: 'not in'}
104
+
105
+
106
+ def _literal_type(value):
107
+ if value is None:
108
+ return 'python-none'
109
+ return {bool: 'python-bool', int: 'python-int', str: 'python-str', tuple: 'python-tuple'}.get(type(value))
110
+
111
+
112
+ def _immutable(node):
113
+ try:
114
+ value = ast.literal_eval(node)
115
+ except (ValueError, TypeError, SyntaxError):
116
+ return False
117
+ def accepted(value):
118
+ return _literal_type(value) is not None and (not isinstance(value, tuple) or all(accepted(item) for item in value))
119
+ return accepted(value)
120
+
121
+
122
+ class _FrontEnd:
123
+ def __init__(self, source, filename, source_imports=None, *, async_enabled=False, browser_enabled=False):
124
+ self.filename = filename
125
+ self.lines = source.splitlines() or ['']
126
+ self.bindings = {}
127
+ self.root = {}
128
+ self.locals = {}
129
+ self.types = {}
130
+ self.source_imports = source_imports or {}
131
+ self.async_enabled = async_enabled
132
+ self.browser_enabled = browser_enabled
133
+ self.async_scopes = set()
134
+ try:
135
+ self.tree = ast.parse(source, filename=filename)
136
+ self.table = symtable.symtable(source, filename, 'exec')
137
+ except SyntaxError as error:
138
+ span = SourceSpan(filename, error.lineno or 1, error.offset or 1,
139
+ error.end_lineno or error.lineno or 1,
140
+ error.end_offset or error.offset or 1)
141
+ raise CompileError(Diagnostic('PJS100', error.msg, span, 'parse')) from None
142
+ self._declare_module()
143
+
144
+ def span(self, node):
145
+ def column(line, offset):
146
+ text = self.lines[line - 1] if 0 < line <= len(self.lines) else ''
147
+ return len(text.encode('utf-8')[:offset].decode('utf-8')) + 1
148
+ line, end_line = node.lineno, node.end_lineno or node.lineno
149
+ return SourceSpan(self.filename, line, column(line, node.col_offset),
150
+ end_line, column(end_line, node.end_col_offset or node.col_offset))
151
+
152
+ def fail(self, code, message, node):
153
+ raise CompileError(Diagnostic(code, message, self.span(node), 'bind' if code == 'PJS110' else 'validate'))
154
+
155
+ def node(self, original, kind, value_type='statement', **fields):
156
+ return IRNode(kind, value_type, self.span(original), tuple(fields.items()))
157
+
158
+ def declare(self, name, scope, kind, target=None):
159
+ binding = Binding(scope + ':' + name, name, scope, kind, target)
160
+ self.bindings[binding.id] = binding
161
+ return binding
162
+
163
+ def _declare_module(self):
164
+ for node in self.tree.body:
165
+ imports = self.source_imports.get((node.lineno, node.col_offset))
166
+ if imports is not None:
167
+ for imported in imports:
168
+ if imported.name in self.root:
169
+ self.fail('PJS100', 'Module rebinding is outside the immutable profile.', node)
170
+ binding = self.declare(imported.name, 'module', 'source', imported.module + ':' + imported.export)
171
+ self.root[imported.name] = binding
172
+ self.types[binding.id] = imported.value_type
173
+ continue
174
+ if isinstance(node, ast.ImportFrom) and node.module == 'echidnae.javascript.browser' and self.browser_enabled:
175
+ if node.level or any(alias.name not in _BROWSER_APIS for alias in node.names):
176
+ self.fail('PJS110', 'Unsupported browser host import.', node)
177
+ for alias in node.names:
178
+ name = alias.asname or alias.name
179
+ if name in self.root:
180
+ self.fail('PJS100', 'Module rebinding is outside the immutable profile.', node)
181
+ self.root[name] = self.declare(name, 'module', 'javascript', 'echidnae.javascript.browser.' + alias.name)
182
+ continue
183
+ names = []
184
+ kind, target = 'constant', None
185
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
186
+ names, kind = [node.name], 'function'
187
+ if isinstance(node, ast.AsyncFunctionDef):
188
+ self.types['module:' + node.name] = 'async-callable'
189
+ self.async_scopes.add('function:' + node.name)
190
+ elif isinstance(node, ast.Assign):
191
+ if len(node.targets) != 1 or not isinstance(node.targets[0], ast.Name) or not _immutable(node.value):
192
+ self.fail('PJS100', 'Module bindings require single-name immutable literals.', node)
193
+ names = [node.targets[0].id]
194
+ self.types['module:' + names[0]] = _literal_type(ast.literal_eval(node.value))
195
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
196
+ kind = 'javascript'
197
+ if isinstance(node, ast.Import):
198
+ if len(node.names) != 1 or node.names[0].name != 'echidnae.javascript':
199
+ self.fail('PJS110', 'Only the approved echidnae.javascript registry may be imported.', node)
200
+ alias = node.names[0].asname
201
+ names, target = [alias or 'echidnae'], 'echidnae.javascript' if alias else 'echidnae'
202
+ else:
203
+ if node.level or node.module != 'echidnae.javascript' or len(node.names) != 1 or node.names[0].name not in ({'Array', 'Promise'} if self.async_enabled else {'Array'}):
204
+ self.fail('PJS110', 'Only the approved echidnae.javascript.Array binding may be imported.', node)
205
+ names, target = [node.names[0].asname or node.names[0].name], 'echidnae.javascript.' + node.names[0].name
206
+ for name in names:
207
+ if name in self.root:
208
+ self.fail('PJS100', 'Module rebinding is outside the immutable profile.', node)
209
+ self.root[name] = self.declare(name, 'module', kind, target)
210
+ for child in self.table.get_children():
211
+ if child.get_name() in self.root and self.root[child.get_name()].kind == 'function':
212
+ scope = 'function:' + child.get_name()
213
+ self.locals[scope] = {
214
+ symbol.get_name(): self.declare(symbol.get_name(), scope,
215
+ 'parameter' if symbol.is_parameter() else 'local')
216
+ for symbol in sorted(child.get_symbols(), key=lambda symbol: symbol.get_name())
217
+ if symbol.is_local()
218
+ }
219
+
220
+ def resolve(self, name, scope, node):
221
+ if scope and name in self.locals[scope]:
222
+ return self.locals[scope][name]
223
+ if name in self.root:
224
+ return self.root[name]
225
+ if name in _BUILTINS:
226
+ identifier = 'builtin:' + name
227
+ if identifier not in self.bindings:
228
+ self.declare(name, 'builtin', 'builtin', identifier)
229
+ return self.bindings[identifier]
230
+ self.fail('PJS110', 'Unresolved or unsupported binding: ' + name, node)
231
+
232
+ def expression(self, node, scope):
233
+ if isinstance(node, ast.Constant):
234
+ kind = _literal_type(node.value)
235
+ if kind is None:
236
+ self.fail('PJS100', 'Literal type is deferred in this profile.', node)
237
+ value = str(node.value) if type(node.value) is int else node.value
238
+ return self.node(node, 'constant', kind, value=value)
239
+ if isinstance(node, ast.Name):
240
+ binding = self.resolve(node.id, scope, node)
241
+ kind = self.types.get(binding.id, 'python-value')
242
+ target = binding.target
243
+ if binding.kind == 'function':
244
+ kind, target = self.types.get(binding.id, 'callable'), binding.id
245
+ elif binding.kind == 'javascript':
246
+ kind = 'javascript-callable' if (target or '').startswith('echidnae.javascript.browser.') else 'javascript-type'
247
+ elif binding.kind == 'builtin':
248
+ kind = 'python-type' if binding.name in _TYPES else 'callable'
249
+ elif binding.kind == 'source':
250
+ target = binding.id if kind in {'callable', 'async-callable'} else None
251
+ return self.node(node, 'name', kind, binding=binding.id, target=target)
252
+ if isinstance(node, ast.Await):
253
+ if not self.async_enabled or scope not in self.async_scopes:
254
+ self.fail('PJS100', 'Await requires an adopted async function.', node)
255
+ value = self.expression(node.value, scope)
256
+ if value.value_type not in {'python-coroutine', 'python-promise', 'python-value'}:
257
+ self.fail('PJS120', 'Await requires an adopted coroutine or Promise.', node)
258
+ return self.node(node, 'await', 'python-value', value=value)
259
+ if isinstance(node, ast.Tuple):
260
+ return self.node(node, 'tuple', 'python-tuple', values=tuple(self.expression(value, scope) for value in node.elts))
261
+ if isinstance(node, ast.Attribute):
262
+ value = self.expression(node.value, scope)
263
+ if self.async_enabled:
264
+ async_target = {('echidnae.javascript', 'Promise'): 'echidnae.javascript.Promise',
265
+ ('echidnae.javascript.Promise', 'resolve'): 'echidnae.javascript.Promise.resolve',
266
+ ('echidnae.javascript.Promise', 'reject'): 'echidnae.javascript.Promise.reject'}.get((value.field('target'), node.attr))
267
+ if value.value_type == 'python-promise' and node.attr == 'then':
268
+ async_target = 'Promise.then'
269
+ if async_target:
270
+ return self.node(node, 'async-attribute', 'javascript-type' if async_target == 'echidnae.javascript.Promise' else 'javascript-callable',
271
+ value=value, name=node.attr, target=async_target)
272
+ target = {('echidnae', 'javascript'): 'echidnae.javascript',
273
+ ( 'echidnae.javascript', 'Array'): 'echidnae.javascript.Array',
274
+ ('echidnae.javascript.Array', 'of'): 'echidnae.javascript.Array.of'}.get((value.field('target'), node.attr))
275
+ if target:
276
+ return self.node(node, 'attribute', 'javascript-callable' if target.endswith('.of') else 'javascript-type',
277
+ value=value, name=node.attr, target=target)
278
+ if value.value_type == 'javascript-array' and node.attr == 'length':
279
+ return self.node(node, 'attribute', 'javascript-number', value=value, name='length')
280
+ self.fail('PJS110' if (value.field('target') or '').startswith('echidnae.javascript') else 'PJS120',
281
+ 'Attribute is outside the approved echidnae.javascript API.', node)
282
+ if isinstance(node, ast.Call):
283
+ if node.keywords or any(isinstance(argument, ast.Starred) for argument in node.args):
284
+ self.fail('PJS100', 'Keyword and starred calls are deferred.', node)
285
+ function = self.expression(node.func, scope)
286
+ target = function.field('target')
287
+ allowed = {'builtin:len': ('python-int', 1), 'builtin:print': ('python-none', None),
288
+ 'builtin:isinstance': ('python-bool', 2), 'builtin:TypeError': ('python-exception', 1),
289
+ 'echidnae.javascript.Array.of': ('javascript-array', None)}
290
+ if self.browser_enabled:
291
+ allowed.update({'echidnae.javascript.browser.' + name: ('python-promise', count) for name, count in _BROWSER_APIS.items()})
292
+ if self.async_enabled:
293
+ allowed.update({'echidnae.javascript.Promise.resolve': ('python-promise', 1),
294
+ 'echidnae.javascript.Promise.reject': ('python-promise', 1),
295
+ 'Promise.then': ('python-promise', None)})
296
+ if target in allowed:
297
+ kind, count = allowed[target]
298
+ if count is not None and len(node.args) != count:
299
+ self.fail('PJS120', 'Unsupported argument count.', node)
300
+ elif target in self.bindings and self.bindings[target].kind in {'function', 'source'}:
301
+ kind = 'python-coroutine' if function.value_type == 'async-callable' else 'python-value'
302
+ else:
303
+ self.fail('PJS120', 'Call does not resolve to an approved direct callable.', node)
304
+ arguments = tuple(self.expression(argument, scope) for argument in node.args)
305
+ if any(argument.value_type == 'python-coroutine' for argument in arguments):
306
+ self.fail('PJS120', 'Coroutine arguments must be awaited first.', node)
307
+ if target == 'echidnae.javascript.browser.on_click' and arguments[1].value_type not in {'callable', 'async-callable'}:
308
+ self.fail('PJS120', 'on_click requires a known compiled Python callback.', node)
309
+ if target == 'Promise.then' and (len(arguments) > 2 or any(
310
+ argument.value_type not in {'callable', 'python-none'} for argument in arguments)):
311
+ self.fail('PJS120', 'then accepts up to two plain synchronous Python callbacks or None.', node)
312
+ if target == 'builtin:isinstance' and arguments[1].field('target') not in {'builtin:' + name for name in _TYPES}:
313
+ self.fail('PJS120', 'isinstance requires an approved builtin type binding.', node)
314
+ return self.node(node, 'call', kind, function=function, arguments=arguments, target=target)
315
+ if isinstance(node, ast.BinOp):
316
+ operator = _BINARY.get(type(node.op))
317
+ if operator is None:
318
+ self.fail('PJS100', 'Binary operator is deferred.', node)
319
+ left, right = self.expression(node.left, scope), self.expression(node.right, scope)
320
+ kinds = {left.value_type, right.value_type}
321
+ if kinds <= {'python-int', 'python-bool'}:
322
+ kind = 'python-int'
323
+ elif operator == '+' and kinds == {'python-str'}:
324
+ kind = 'python-str'
325
+ elif 'python-value' in kinds and kinds <= {'python-value', 'python-int', 'python-bool', 'python-str'}:
326
+ kind = 'python-value'
327
+ else:
328
+ self.fail('PJS120', 'Operand types require a separately adopted operation.', node)
329
+ return self.node(node, 'binary', kind, operator=operator, left=left, right=right)
330
+ if isinstance(node, ast.UnaryOp):
331
+ operator = {ast.Not: 'not', ast.UAdd: '+', ast.USub: '-'}.get(type(node.op))
332
+ if operator is None:
333
+ self.fail('PJS100', 'Unary operator is deferred.', node)
334
+ value = self.expression(node.operand, scope)
335
+ if operator != 'not' and value.value_type not in {'python-int', 'python-bool', 'python-value'}:
336
+ self.fail('PJS120', 'Unary numeric operation requires a Python integer.', node)
337
+ return self.node(node, 'unary', 'python-bool' if operator == 'not' else 'python-int', operator=operator, value=value)
338
+ if isinstance(node, ast.BoolOp):
339
+ values = tuple(self.expression(value, scope) for value in node.values)
340
+ kinds = {value.value_type for value in values}
341
+ return self.node(node, 'boolean', next(iter(kinds)) if len(kinds) == 1 else 'python-value',
342
+ operator='and' if isinstance(node.op, ast.And) else 'or', values=values)
343
+ if isinstance(node, ast.Compare):
344
+ operators = tuple(_COMPARE.get(type(operator)) for operator in node.ops)
345
+ if None in operators:
346
+ self.fail('PJS100', 'Comparison is deferred.', node)
347
+ values = tuple(self.expression(value, scope) for value in [node.left, *node.comparators])
348
+ for index, operator in enumerate(operators):
349
+ if operator in {'is', 'is not'}:
350
+ for value in values[index:index + 2]:
351
+ if value.value_type in {'python-int', 'python-str', 'javascript-number'} or (
352
+ value.kind == 'tuple'
353
+ ):
354
+ self.fail('PJS120', 'Literal interning identity is outside this profile.', node)
355
+ return self.node(node, 'compare', 'python-bool', operators=operators, values=values)
356
+ if isinstance(node, ast.Subscript):
357
+ if isinstance(node.slice, ast.Slice):
358
+ self.fail('PJS100', 'Slicing is deferred.', node)
359
+ value, index = self.expression(node.value, scope), self.expression(node.slice, scope)
360
+ if value.value_type not in {'python-str', 'python-tuple', 'python-value'} or index.value_type not in {'python-int', 'python-bool', 'python-value'}:
361
+ self.fail('PJS120', 'Indexing requires an adopted sequence and integer.', node)
362
+ return self.node(node, 'index', 'python-str' if value.value_type == 'python-str' else 'python-value', value=value, index=index)
363
+ self.fail('PJS100', 'Unsupported expression: ' + type(node).__name__, node)
364
+
365
+ def statements(self, nodes, scope=None, loop=0):
366
+ return tuple(self.statement(node, scope, loop) for node in nodes)
367
+
368
+ def statement(self, node, scope, loop):
369
+ if self.browser_enabled and scope is None and not isinstance(node, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.AsyncFunctionDef, ast.Assign, ast.Pass)):
370
+ if not (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)):
371
+ self.fail('PJS100', 'Browser module initialization requires imports, definitions or immutable constants.', node)
372
+ if isinstance(node, (ast.Import, ast.ImportFrom)) and scope is None:
373
+ if node not in self.tree.body:
374
+ self.fail('PJS100', 'Imports require unconditional module bindings.', node)
375
+ imports = self.source_imports.get((node.lineno, node.col_offset))
376
+ if imports is not None:
377
+ return self.node(node, 'source-import', module=imports[0].module,
378
+ bindings=tuple((self.root[imported.name].id, imported.export) for imported in imports))
379
+ names = [alias.asname or (alias.name.split('.')[0] if isinstance(node, ast.Import) else alias.name)
380
+ for alias in node.names]
381
+ return self.node(node, 'import', bindings=tuple(self.root[name].id for name in names))
382
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
383
+ asynchronous = isinstance(node, ast.AsyncFunctionDef)
384
+ if asynchronous and not self.async_enabled:
385
+ self.fail('PJS100', 'Async functions require the explicit async profile.', node)
386
+ if node not in self.tree.body or scope or node.decorator_list or node.type_params or node.returns or any(arg.annotation for arg in [*node.args.posonlyargs, *node.args.args]):
387
+ self.fail('PJS100', 'Nested, decorated, generic or annotated functions are deferred.', node)
388
+ if node.args.vararg or node.args.kwarg or node.args.kwonlyargs:
389
+ self.fail('PJS100', 'Variadic and keyword-only parameters are deferred.', node)
390
+ if not all(_immutable(default) for default in node.args.defaults):
391
+ self.fail('PJS100', 'Defaults must be immutable literals.', node)
392
+ function_scope = 'function:' + node.name
393
+ defaults = tuple(self.expression(default, None) for default in node.args.defaults)
394
+ original = self.types.copy()
395
+ body = self.statements(node.body, function_scope)
396
+ self.types = original
397
+ return self.node(node, 'function', binding=self.root[node.name].id,
398
+ parameters=tuple(self.locals[function_scope][arg.arg].id for arg in [*node.args.posonlyargs, *node.args.args]),
399
+ defaults=defaults, body=body, asynchronous=asynchronous)
400
+ if isinstance(node, ast.Assign):
401
+ if any(not isinstance(target, ast.Name) for target in node.targets):
402
+ self.fail('PJS100', 'Only simple-name assignment is supported.', node)
403
+ if scope is None and (node not in self.tree.body or not _immutable(node.value)):
404
+ self.fail('PJS100', 'Module bindings must be unconditional immutable literals.', node)
405
+ value = self.expression(node.value, scope)
406
+ targets = tuple(self.resolve(target.id, scope, target).id for target in node.targets)
407
+ for target in targets:
408
+ self.types[target] = value.value_type
409
+ return self.node(node, 'assign', targets=targets, value=value)
410
+ if isinstance(node, ast.Expr):
411
+ return self.node(node, 'expression', value=self.expression(node.value, scope))
412
+ if isinstance(node, ast.Return):
413
+ if scope is None:
414
+ self.fail('PJS100', 'Return requires a function.', node)
415
+ value = self.expression(node.value, scope) if node.value else None
416
+ if value and (value.value_type == 'python-coroutine' or
417
+ (scope in self.async_scopes and value.value_type == 'python-promise')):
418
+ self.fail('PJS120', 'Returning an unawaited coroutine or Promise is outside this profile.', node)
419
+ return self.node(node, 'return', value=value)
420
+ if isinstance(node, ast.If):
421
+ test = self.expression(node.test, scope)
422
+ original = self.types.copy()
423
+ body = self.statements(node.body, scope, loop)
424
+ left = self.types.copy()
425
+ self.types = original.copy()
426
+ otherwise = self.statements(node.orelse, scope, loop)
427
+ right = self.types
428
+ self.types = {key: left.get(key) if left.get(key) == right.get(key) else 'python-value'
429
+ for key in left.keys() | right.keys()}
430
+ return self.node(node, 'if', test=test, body=body, otherwise=otherwise)
431
+ if isinstance(node, ast.For):
432
+ if scope is None or node.orelse or not isinstance(node.target, ast.Name):
433
+ self.fail('PJS100', 'For requires a function, simple target and no else clause.', node)
434
+ value = self.expression(node.iter, scope)
435
+ if value.value_type not in {'python-str', 'python-tuple', 'python-value'}:
436
+ self.fail('PJS120', 'For requires an adopted iterable.', node)
437
+ target = self.resolve(node.target.id, scope, node.target).id
438
+ original = self.types.copy()
439
+ self.types[target] = 'python-str' if value.value_type == 'python-str' else 'python-value'
440
+ body = self.statements(node.body, scope, loop + 1)
441
+ self.types = {key: kind if kind == original.get(key) else 'python-value' for key, kind in (original | self.types).items()}
442
+ return self.node(node, 'for', target=target, value=value, body=body)
443
+ if isinstance(node, (ast.Break, ast.Continue)):
444
+ if not loop:
445
+ self.fail('PJS100', 'Loop control requires a loop.', node)
446
+ return self.node(node, 'break' if isinstance(node, ast.Break) else 'continue')
447
+ if isinstance(node, ast.Raise):
448
+ value = self.expression(node.exc, scope) if node.exc else None
449
+ if node.cause or value is None or value.value_type != 'python-exception':
450
+ self.fail('PJS120', 'Only explicit adopted builtin errors may be raised.', node)
451
+ return self.node(node, 'raise', value=value)
452
+ if isinstance(node, ast.Pass):
453
+ return self.node(node, 'pass')
454
+ self.fail('PJS100', 'Unsupported statement: ' + type(node).__name__, node)
455
+
456
+
457
+ def parse_source(source: str, *, filename: str = '<source>', async_enabled: bool = False) -> ModuleIR:
458
+ """Validate source and return immutable typed IR without executing target code."""
459
+ if not isinstance(source, str) or not isinstance(filename, str):
460
+ raise TypeError('source and filename must be strings')
461
+ try:
462
+ encoded = source.encode('utf-8')
463
+ except UnicodeEncodeError:
464
+ raise CompileError(Diagnostic('PJS100', 'Source must be valid UTF-8.', SourceSpan(filename, 1, 1, 1, 1), 'parse')) from None
465
+ if len(encoded) > 1_048_576:
466
+ raise CompileError(Diagnostic('PJS100', 'Source exceeds the 1 MiB profile limit.', SourceSpan(filename, 1, 1, 1, 1), 'parse'))
467
+ if type(async_enabled) is not bool:
468
+ raise TypeError('async_enabled must be bool')
469
+ frontend = _FrontEnd(source, filename, async_enabled=async_enabled)
470
+ body = frontend.statements(frontend.tree.body)
471
+ return ModuleIR(filename, hashlib.sha256(encoded).hexdigest(),
472
+ tuple(frontend.bindings[key] for key in sorted(frontend.bindings)), body,
473
+ profile='python-browser-async/1' if async_enabled else 'python-browser/1')