OILS / pea / mypy_shim.py View on Github | oils.pub

77 lines, 40 significant
1#!/usr/bin/env python3
2"""
3mypy_shim.py
4
5Convert stdlib ast nodes into MyPy nodes
6"""
7
8import os
9
10from typing import Any
11
12from mypy.nodes import (MypyFile, FuncDef, Argument, ReturnStmt, IntExpr,
13 Statement, Block, Var, ARG_POS)
14
15from mypy.types import Type, CallableType
16
17from mycpp.conversion_pass import Primitive
18
19from pea import header
20from pea.header import log
21from pea import parse
22
23
24def CreateMyPyFile(path: str) -> MypyFile:
25 """
26 Hacky function create MyPy AST!
27
28 Works for a trivial function
29 """
30 defs: list[Statement] = []
31 stub = MypyFile(defs, [])
32
33 func_name = 'main'
34
35 v = Var('argv')
36 s = ret_type = Primitive('builtins.str')
37 type_annotation = Primitive('builtins.list', args=[s])
38 initializer = None
39 kind = ARG_POS
40
41 arguments = [Argument(v, type_annotation, initializer, kind)]
42 body = Block([ReturnStmt(IntExpr(42))])
43
44 # Why are types duplicated?
45 arg_types: list[Type] = [type_annotation]
46 arg_kinds: list[Any] = [ARG_POS]
47 arg_names: list[str] = ['argv']
48 ret_type = Primitive('builtins.int')
49 fallback = Primitive('??? fallback') # WHAT is this for?
50 func_type = CallableType(arg_types, arg_kinds, arg_names, ret_type,
51 fallback)
52
53 func = FuncDef(func_name, arguments, body, typ=func_type)
54 func._fullname = func_name
55
56 #_ = func
57 defs.append(func)
58
59 # fullname is a property, backed by _fullname
60 #
61 # mycpp/examples/pea_hello.py -> mycpp
62
63 name = os.path.basename(path)
64 mod_name, _ = os.path.splitext(name)
65
66 stub._fullname = mod_name
67
68 prog = header.Program()
69 log('Pea begin')
70
71 if not parse.ParseFiles([path], prog):
72 raise AssertionError()
73
74 prog.PrintStats()
75 log('prog %s', prog)
76
77 return stub