codegen-2 2.1.4__py3-none-any.whl → 2.5.2__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.
codegen/models/ast.py CHANGED
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass, field
4
- from typing import TYPE_CHECKING, Any, Callable, Optional
4
+ from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence
5
5
 
6
6
  from codegen.models.expr import ExceptionExpr, Expr
7
7
  from codegen.models.statement import (
@@ -9,7 +9,9 @@ from codegen.models.statement import (
9
9
  BlockStatement,
10
10
  Comment,
11
11
  DefClassStatement,
12
+ DefClassVarStatement,
12
13
  DefFuncStatement,
14
+ DefInterfaceStatement,
13
15
  ElseStatement,
14
16
  ExceptionStatement,
15
17
  ForLoopStatement,
@@ -41,10 +43,16 @@ class AST:
41
43
 
42
44
  @staticmethod
43
45
  def root(prog: Program):
44
- return AST(tuple(), prog, BlockStatement())
46
+ return AST(tuple(), prog, BlockStatement(has_owned_env=False))
47
+
48
+ def is_root(self) -> bool:
49
+ """Check if this is the root AST"""
50
+ return len(self.id) == 0
45
51
 
46
52
  def __call__(
47
- self, *args: Callable[[AST], Any] | Statement, return_self: bool = False
53
+ self,
54
+ *args: Callable[[AST], Any] | Optional[Statement],
55
+ return_self: bool = False,
48
56
  ) -> Optional[AST]:
49
57
  """Allow to build the graph hierarchically"""
50
58
  assert isinstance(return_self, bool)
@@ -54,9 +62,10 @@ class AST:
54
62
  for fn in args:
55
63
  if isinstance(fn, Statement):
56
64
  self._add_stmt(fn)
57
- else:
58
- assert callable(fn)
65
+ elif callable(fn):
59
66
  return_val = fn(self)
67
+ else:
68
+ assert fn is None
60
69
 
61
70
  if return_self:
62
71
  assert return_val is None, "Trying to return multiple asts at the same time"
@@ -68,8 +77,8 @@ class AST:
68
77
  for child in self.children:
69
78
  child.freeze()
70
79
 
71
- def import_(self, module: str, is_import_attr: bool):
72
- self._add_stmt(ImportStatement(module, is_import_attr))
80
+ def import_(self, module: str, is_import_attr: bool, alias: Optional[str] = None):
81
+ self._add_stmt(ImportStatement(module, is_import_attr, alias))
73
82
 
74
83
  def return_(self, expr: Expr):
75
84
  self._add_stmt(ReturnStatement(expr))
@@ -83,18 +92,52 @@ class AST:
83
92
  def comment(self, comment: str):
84
93
  self._add_stmt(Comment(comment))
85
94
 
86
- def func(self, name: str, vars: list[DeferredVar]):
95
+ def func(
96
+ self,
97
+ name: str,
98
+ vars: Sequence[DeferredVar | tuple[DeferredVar, Expr]],
99
+ return_type: Optional[Expr] = None,
100
+ is_async: bool = False,
101
+ is_static: bool = False,
102
+ comment: str = "",
103
+ ):
87
104
  """Define a function. The input variables are deferred vars as they are created for this function (i.e., must not be predefined prior to this function)"""
88
105
  grandchild_id = self.next_grandchild_id()
89
- for var in vars:
106
+ for vararg in vars:
107
+ if isinstance(vararg, tuple):
108
+ var = vararg[0]
109
+ else:
110
+ var = vararg
90
111
  var.set_var(
91
- self.prog.create_var(var.name, var.key, grandchild_id, var.force_name)
112
+ self.prog.create_var(
113
+ var.name, var.key, grandchild_id, var.force_name, var.type
114
+ )
115
+ )
116
+ return self._add_stmt(
117
+ DefFuncStatement(
118
+ name,
119
+ [
120
+ (
121
+ (var[0].get_var(), var[1])
122
+ if isinstance(var, tuple)
123
+ else var.get_var()
124
+ )
125
+ for var in vars
126
+ ],
127
+ return_type,
128
+ is_async,
129
+ is_static,
130
+ comment,
92
131
  )
93
- return self._add_stmt(DefFuncStatement(name, [var.get_var() for var in vars]))
132
+ )
133
+
134
+ def class_(self, name: str, parents: Optional[Sequence[Expr]] = None):
135
+ """Define a class."""
136
+ return self._add_stmt(DefClassStatement(name, parents or []))
94
137
 
95
- def class_(self, name: str):
138
+ def interface(self, name: str, parents: Optional[Sequence[Expr]] = None):
96
139
  """Define a class."""
97
- return self._add_stmt(DefClassStatement(name))
140
+ return self._add_stmt(DefInterfaceStatement(name, parents or []))
98
141
 
99
142
  def expr(self, expr: Expr):
100
143
  return self._add_stmt(SingleExprStatement(expr))
@@ -154,16 +197,6 @@ class AST:
154
197
  ast, context, stop = fn(ast, context)
155
198
  return ast
156
199
 
157
- def to_python(self, level: int = 0):
158
- """Convert the AST to python code"""
159
- if isinstance(self.stmt, BlockStatement):
160
- # there is no direct statement and the level does not increase after this statement
161
- return "\n".join([child.to_python(level) for child in self.children])
162
-
163
- prog = ["\t" * level + self.stmt.to_python()]
164
- prog.extend((child.to_python(level + 1) for child in self.children))
165
- return "\n".join(prog)
166
-
167
200
  def has_statement_between_ast(self, stmtcls: type[Statement], end_ast_id: AST_ID):
168
201
  """Check if there is a statement of the given type the current AST and the end_ast (exclusive)"""
169
202
  for ast in self.children:
@@ -223,3 +256,42 @@ class AST:
223
256
  ast = AST(self.next_child_id(), self.prog, stmt)
224
257
  self.children.append(ast)
225
258
  return ast
259
+
260
+ def to_python(self, level: int = 0):
261
+ """Convert the AST to python code"""
262
+ if isinstance(self.stmt, BlockStatement):
263
+ # there is no direct statement and the level does not increase after this statement
264
+ return "\n".join([child.to_python(level) for child in self.children])
265
+
266
+ prog = ["\t" * level + line for line in self.stmt.to_python().split("\n")]
267
+ prog.extend((child.to_python(level + 1) for child in self.children))
268
+ return "\n".join(prog)
269
+
270
+ def to_typescript(self, level: int = 0):
271
+ """Convert the AST to typescript code"""
272
+ if isinstance(self.stmt, BlockStatement):
273
+ if not self.stmt.has_owned_env:
274
+ # the level does not increase after this statement because we do not need to create a new scope
275
+ content = "\n".join(
276
+ [child.to_typescript(level) for child in self.children]
277
+ )
278
+ if self.is_root():
279
+ return content.lstrip("\n")
280
+ return content
281
+
282
+ if len(self.children) == 0:
283
+ return ""
284
+
285
+ return (
286
+ ("\t" * level + "{")
287
+ + "\n".join([child.to_typescript(level + 1) for child in self.children])
288
+ + "\n"
289
+ + ("\t" * level + "}")
290
+ )
291
+
292
+ prog = ["\t" * level + line for line in self.stmt.to_typescript().split("\n")]
293
+ if len(self.children) > 0:
294
+ prog.append("\t" * level + "{")
295
+ prog.extend((child.to_typescript(level + 1) for child in self.children))
296
+ prog.append("\t" * level + "}")
297
+ return "\n".join(prog)
codegen/models/expr.py CHANGED
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  import json
4
4
  from abc import ABC, abstractmethod
5
5
  from dataclasses import dataclass
6
- from typing import Any, Optional, Sequence
6
+ from typing import Any, Callable, Optional, Sequence
7
7
 
8
8
  from codegen.models.var import Var
9
9
 
@@ -11,7 +11,10 @@ from codegen.models.var import Var
11
11
  class Expr(ABC):
12
12
  @abstractmethod
13
13
  def to_python(self):
14
- raise NotImplementedError()
14
+ raise NotImplementedError(self.__class__)
15
+
16
+ def to_typescript(self):
17
+ raise NotImplementedError(self.__class__)
15
18
 
16
19
  def to_wrapped_python(self):
17
20
  if isinstance(self, (ExprVar, ExprConstant)):
@@ -19,8 +22,16 @@ class Expr(ABC):
19
22
  return f"({self.to_python()})"
20
23
 
21
24
 
22
- class ExceptionExpr(Expr):
23
- pass
25
+ class ExceptionExpr(Expr): ...
26
+
27
+
28
+ @dataclass
29
+ class StandardExceptionExpr(ExceptionExpr):
30
+ cls: Expr
31
+ args: Sequence[Expr]
32
+
33
+ def to_python(self):
34
+ return f"{self.cls.to_python()}({', '.join([arg.to_python() for arg in self.args])})"
24
35
 
25
36
 
26
37
  @dataclass
@@ -30,8 +41,11 @@ class ExprConstant(Expr):
30
41
  def to_python(self):
31
42
  return ExprConstant.constant_to_python(self.constant)
32
43
 
44
+ def to_typescript(self):
45
+ return ExprConstant.constant_to_typescript(self.constant)
46
+
33
47
  @staticmethod
34
- def constant_to_python(val: Any):
48
+ def constant_to_python(val: Any) -> str:
35
49
  if isinstance(val, bool) or val is None:
36
50
  return str(val)
37
51
  if isinstance(val, (str, int, float)):
@@ -53,8 +67,46 @@ class ExprConstant(Expr):
53
67
  )
54
68
  if isinstance(val, set):
55
69
  return (
56
- "{" + ", ".join([ExprConstant.constant_to_python(v) for v in val]) + "}"
70
+ "{"
71
+ + ", ".join(sorted((ExprConstant.constant_to_python(v) for v in val)))
72
+ + "}"
57
73
  )
74
+ raise NotImplementedError()
75
+
76
+ @staticmethod
77
+ def constant_to_typescript(val: Any) -> str:
78
+ if isinstance(val, bool):
79
+ return str(val).lower()
80
+ if val == "undefined":
81
+ return "undefined"
82
+ if val is None:
83
+ return "null"
84
+ if isinstance(val, (str, int, float)):
85
+ return json.dumps(val)
86
+ if isinstance(val, list):
87
+ return (
88
+ "["
89
+ + ", ".join([ExprConstant.constant_to_typescript(v) for v in val])
90
+ + "]"
91
+ )
92
+ if isinstance(val, dict):
93
+ return (
94
+ "{"
95
+ + ", ".join(
96
+ [
97
+ f"{ExprConstant.constant_to_typescript(k)}: {ExprConstant.constant_to_typescript(v)}"
98
+ for k, v in val.items()
99
+ ]
100
+ )
101
+ + "}"
102
+ )
103
+ if isinstance(val, set):
104
+ return (
105
+ "new Set(["
106
+ + ", ".join([ExprConstant.constant_to_typescript(v) for v in val])
107
+ + "])"
108
+ )
109
+ raise NotImplementedError()
58
110
 
59
111
 
60
112
  @dataclass
@@ -64,6 +116,17 @@ class ExprIdent(Expr):
64
116
  def to_python(self):
65
117
  return self.ident
66
118
 
119
+ def to_typescript(self):
120
+ return self.ident
121
+
122
+
123
+ @dataclass
124
+ class ExprRawPython(Expr):
125
+ code: str
126
+
127
+ def to_python(self):
128
+ return self.code
129
+
67
130
 
68
131
  @dataclass
69
132
  class ExprVar(Expr): # a special identifier
@@ -76,23 +139,41 @@ class ExprVar(Expr): # a special identifier
76
139
  @dataclass
77
140
  class ExprFuncCall(Expr):
78
141
  func_name: Expr
79
- args: list[Expr]
142
+ args: Sequence[Expr]
80
143
 
81
144
  def to_python(self):
82
145
  return f"{self.func_name.to_python()}({', '.join([arg.to_python() for arg in self.args])})"
83
146
 
147
+ def to_typescript(self):
148
+ return f"{self.func_name.to_typescript()}({', '.join([arg.to_typescript() for arg in self.args])})"
149
+
150
+
151
+ @dataclass
152
+ class ExprNewInstance(Expr):
153
+ class_name: Expr
154
+ args: Sequence[Expr]
155
+
156
+ def to_python(self):
157
+ return f"{self.class_name.to_python()}({', '.join([arg.to_python() for arg in self.args])})"
158
+
159
+ def to_typescript(self):
160
+ return f"new {self.class_name.to_typescript()}({', '.join([arg.to_typescript() for arg in self.args])})"
161
+
84
162
 
85
163
  @dataclass
86
164
  class ExprMethodCall(Expr):
87
165
  object: Expr
88
166
  method: str
89
- args: list[Expr]
167
+ args: Sequence[Expr]
90
168
 
91
169
  def to_python(self):
92
170
  if self.method == "__contains__" and len(self.args) == 1:
93
171
  return f"{self.args[0].to_python()} in {self.object.to_python()}"
94
172
  return f"{self.object.to_python()}.{self.method}({', '.join([arg.to_python() for arg in self.args])})"
95
173
 
174
+ def to_typescript(self):
175
+ return f"{self.object.to_typescript()}.{self.method}({', '.join([arg.to_typescript() for arg in self.args])})"
176
+
96
177
 
97
178
  @dataclass
98
179
  class ExprNotEqual(Expr):
@@ -120,6 +201,18 @@ class ExprEqual(Expr):
120
201
  def to_python(self):
121
202
  return f"{self.left.to_python()} == {self.right.to_python()}"
122
203
 
204
+ def to_typescript(self):
205
+ return f"{self.left.to_typescript()} === {self.right.to_typescript()}"
206
+
207
+
208
+ @dataclass
209
+ class ExprIs(Expr):
210
+ left: Expr
211
+ right: Expr
212
+
213
+ def to_python(self):
214
+ return f"{self.left.to_python()} is {self.right.to_python()}"
215
+
123
216
 
124
217
  @dataclass
125
218
  class ExprNegation(Expr):
@@ -129,7 +222,23 @@ class ExprNegation(Expr):
129
222
  return f"not {self.expr.to_wrapped_python()}"
130
223
 
131
224
 
225
+ @dataclass
226
+ class ExprDivision(Expr):
227
+ left: Expr
228
+ right: Expr
229
+
230
+ def to_python(self):
231
+ return f"{self.left.to_python()} / {self.right.to_python()}"
232
+
233
+
132
234
  class PredefinedFn:
235
+ @dataclass
236
+ class is_null(Expr):
237
+ expr: Expr
238
+
239
+ def to_python(self):
240
+ return f"{self.expr.to_python()} is None"
241
+
133
242
  @dataclass
134
243
  class tuple(Expr):
135
244
  items: Sequence[Expr]
@@ -137,6 +246,64 @@ class PredefinedFn:
137
246
  def to_python(self):
138
247
  return f"({', '.join([item.to_python() for item in self.items])})"
139
248
 
249
+ @dataclass
250
+ class list(Expr):
251
+ items: Sequence[Expr]
252
+
253
+ def to_python(self):
254
+ return f"[{', '.join([item.to_python() for item in self.items])}]"
255
+
256
+ @dataclass
257
+ class dict(Expr):
258
+ items: Sequence[tuple[Expr, Expr]]
259
+
260
+ def to_python(self):
261
+ return (
262
+ "{"
263
+ + ", ".join(
264
+ [
265
+ f"{key.to_python()}: {value.to_python()}"
266
+ for key, value in self.items
267
+ ]
268
+ )
269
+ + "}"
270
+ )
271
+
272
+ def to_typescript(self):
273
+ return (
274
+ "{"
275
+ + ", ".join(
276
+ [
277
+ f"{key.to_typescript()}: {value.to_typescript()}"
278
+ for key, value in self.items
279
+ ]
280
+ )
281
+ + "}"
282
+ )
283
+
284
+ @dataclass
285
+ class attr_getter(Expr):
286
+ collection: Expr
287
+ attr: Expr
288
+
289
+ def to_python(self):
290
+ return f"{self.collection.to_python()}.{self.attr.to_python()}"
291
+
292
+ def to_typescript(self):
293
+ return f"{self.collection.to_typescript()}.{self.attr.to_typescript()}"
294
+
295
+ @dataclass
296
+ class attr_setter(Expr):
297
+ collection: Expr
298
+ attr: Expr
299
+ value: Expr
300
+
301
+ def to_python(self):
302
+ return f"{self.collection.to_python()}.{self.attr.to_python()} = {self.value.to_python()}"
303
+
304
+ def to_typescript(self):
305
+ return f"{self.collection.to_typescript()}.{self.attr.to_typescript()} = {self.value.to_typescript()};"
306
+
140
307
  @dataclass
141
308
  class item_getter(Expr):
142
309
  collection: Expr
@@ -161,6 +328,21 @@ class PredefinedFn:
161
328
  def to_python(self):
162
329
  return f"len({self.collection.to_python()})"
163
330
 
331
+ @dataclass(init=False)
332
+ class map_list(Expr):
333
+ collection: Expr
334
+ func: Expr
335
+
336
+ def __init__(self, collection: Expr, func: Callable[[ExprIdent], Expr]):
337
+ self.collection = collection
338
+ self.func = func(ExprIdent("_x"))
339
+
340
+ def to_python(self):
341
+ return f"[{self.func.to_python()} for _x in {self.collection.to_python()}]"
342
+
343
+ def to_typescript(self):
344
+ return f"{self.collection.to_typescript()}.map((_x: any) => {self.func.to_typescript()})"
345
+
164
346
  @dataclass
165
347
  class range(Expr):
166
348
  start: Expr
@@ -196,6 +378,14 @@ class PredefinedFn:
196
378
  def to_python(self):
197
379
  return f"{self.item.to_wrapped_python()} in {self.collection.to_wrapped_python()}"
198
380
 
381
+ @dataclass
382
+ class not_has_item(Expr):
383
+ collection: Expr
384
+ item: Expr
385
+
386
+ def to_python(self):
387
+ return f"{self.item.to_wrapped_python()} not in {self.collection.to_wrapped_python()}"
388
+
199
389
  @dataclass
200
390
  class base_error(ExceptionExpr):
201
391
  msg: str
@@ -209,3 +399,11 @@ class PredefinedFn:
209
399
 
210
400
  def to_python(self):
211
401
  return f"KeyError('{self.msg}')"
402
+
403
+ @dataclass
404
+ class keyword_assignment(Expr):
405
+ keyword: str
406
+ value: Expr
407
+
408
+ def to_python(self):
409
+ return f"{self.keyword}={self.value.to_python()}"
codegen/models/program.py CHANGED
@@ -5,6 +5,7 @@ from dataclasses import dataclass, field
5
5
  from typing import Optional
6
6
 
7
7
  from codegen.models.ast import AST
8
+ from codegen.models.expr import ExprIdent # You may need to adjust this import path
8
9
  from codegen.models.statement import BlockStatement
9
10
  from codegen.models.types import AST_ID, KEY
10
11
  from codegen.models.var import Var, VarScope
@@ -15,14 +16,18 @@ class Program:
15
16
  root: AST
16
17
  vars: VarRegisters
17
18
  import_area: AST
19
+ imported_modules: set[str]
18
20
 
19
21
  def __init__(self):
20
22
  self.vars = VarRegisters(self)
21
23
  self.root = AST.root(self)
22
24
  self.import_area = self.root._add_stmt(BlockStatement(has_owned_env=False))
25
+ self.imported_modules = set()
23
26
 
24
- def import_(self, module: str, is_import_attr: bool):
25
- self.import_area.import_(module, is_import_attr)
27
+ def import_(self, module: str, is_import_attr: bool, alias: Optional[str] = None):
28
+ if module not in self.imported_modules:
29
+ self.import_area.import_(module, is_import_attr, alias)
30
+ self.imported_modules.add(module)
26
31
 
27
32
  def get_ast_by_id(self, id: AST_ID) -> AST:
28
33
  ast = self.root
@@ -48,15 +53,21 @@ class Program:
48
53
  )
49
54
 
50
55
  def create_var(
51
- self, name: str, key: KEY, ast: AST_ID, force_name: Optional[str] = None
56
+ self,
57
+ name: str,
58
+ key: KEY,
59
+ ast: AST_ID,
60
+ force_name: Optional[str] = None,
61
+ type: Optional[ExprIdent] = None,
52
62
  ) -> Var:
53
- reg = self.vars.register(name, key, ast, force_name)
63
+ reg = self.vars.register(name, key, ast, force_name, type)
54
64
  return Var(
55
65
  name=name,
56
66
  key=key,
57
67
  register_id=reg.id,
58
68
  scope=reg.scope,
59
69
  force_name=force_name,
70
+ type=type,
60
71
  )
61
72
 
62
73
  def get_var(
@@ -69,7 +80,9 @@ class Program:
69
80
  reg = self.vars.find(key, at)
70
81
  if reg is None:
71
82
  raise KeyError(f"Variable with key {key} is not found in the current scope")
72
- return Var(reg.name, key, reg.id, reg.scope)
83
+ return Var(
84
+ name=reg.name, key=key, register_id=reg.id, scope=reg.scope, type=reg.type
85
+ )
73
86
 
74
87
 
75
88
  @dataclass
@@ -79,6 +92,7 @@ class VarRegister:
79
92
  key: KEY
80
93
  scope: VarScope
81
94
  force_name: Optional[str] = None
95
+ type: Optional[ExprIdent] = None
82
96
 
83
97
 
84
98
  @dataclass
@@ -88,7 +102,12 @@ class VarRegisters:
88
102
  key2registers: dict[KEY, list[int]] = field(default_factory=dict)
89
103
 
90
104
  def register(
91
- self, name: str, key: KEY, ast: AST_ID, force_name: Optional[str] = None
105
+ self,
106
+ name: str,
107
+ key: KEY,
108
+ ast: AST_ID,
109
+ force_name: Optional[str] = None,
110
+ type: Optional[ExprIdent] = None,
92
111
  ) -> VarRegister:
93
112
  """Register a new variable with the given name, key, then return the register id.
94
113
 
@@ -110,6 +129,7 @@ class VarRegisters:
110
129
  key=key,
111
130
  scope=VarScope.from_ast_id(ast),
112
131
  force_name=force_name,
132
+ type=type,
113
133
  )
114
134
  self.registers.append(reg)
115
135
  self.key2registers.setdefault(key, []).append(reg.id)
@@ -2,8 +2,10 @@ from __future__ import annotations
2
2
 
3
3
  from abc import ABC, abstractmethod
4
4
  from dataclasses import dataclass, field
5
+ from multiprocessing import Value
6
+ from typing import Optional, Sequence
5
7
 
6
- from codegen.models.expr import ExceptionExpr, Expr
8
+ from codegen.models.expr import ExceptionExpr, Expr, ExprFuncCall
7
9
  from codegen.models.var import Var
8
10
 
9
11
 
@@ -13,6 +15,9 @@ class Statement(ABC):
13
15
  def to_python(self):
14
16
  raise NotImplementedError()
15
17
 
18
+ def to_typescript(self):
19
+ raise NotImplementedError(self.__class__)
20
+
16
21
 
17
22
  class NoStatement(Statement):
18
23
  def __repr__(self):
@@ -21,6 +26,9 @@ class NoStatement(Statement):
21
26
  def to_python(self):
22
27
  return "pass"
23
28
 
29
+ def to_typescript(self):
30
+ return "{}"
31
+
24
32
 
25
33
  @dataclass
26
34
  class BlockStatement(Statement):
@@ -33,48 +41,182 @@ class BlockStatement(Statement):
33
41
  "BlockStatement doesn't have any direct statement. You can use it to create scope for variables."
34
42
  )
35
43
 
44
+ def to_typescript(self):
45
+ raise Exception(
46
+ "BlockStatement doesn't have any direct statement. You can use it to create scope for variables."
47
+ )
48
+
36
49
 
37
50
  class LineBreak(Statement):
38
51
  def to_python(self):
39
52
  return ""
40
53
 
54
+ def to_typescript(self):
55
+ return ""
56
+
41
57
 
42
58
  @dataclass
43
59
  class ImportStatement(Statement):
44
60
  module: str
45
61
  is_import_attr: bool
62
+ alias: Optional[str] = None
46
63
 
47
64
  def to_python(self):
48
65
  if self.module.find(".") != -1 and self.is_import_attr:
49
66
  module, attr = self.module.rsplit(".", 1)
50
- return f"from {module} import {attr}"
51
- return f"import {self.module}"
67
+ stmt = f"from {module} import {attr}"
68
+ else:
69
+ stmt = f"import {self.module}"
70
+
71
+ if self.alias is not None:
72
+ stmt += f" as {self.alias}"
73
+ return stmt
74
+
75
+ def to_typescript(self):
76
+ if self.module.find(".") != -1 and self.is_import_attr:
77
+ module, attr = self.module.rsplit(".", 1)
78
+ module = module.replace(".", "/")
79
+ if self.alias is not None:
80
+ return f"import {{ {attr} as {self.alias} }} from '{module}';"
81
+ return f"import {{ {attr} }} from '{module}';"
82
+ else:
83
+ raise NotImplementedError()
52
84
 
53
85
 
54
86
  @dataclass
55
87
  class DefFuncStatement(Statement):
56
88
  name: str
57
- args: list[Var] = field(default_factory=list)
89
+ args: Sequence[Var | tuple[Var, Expr]] = field(default_factory=list)
90
+ return_type: Optional[Expr] = None
91
+ is_async: bool = False
92
+ is_static: bool = False
93
+ comment: str = ""
58
94
 
59
95
  def to_python(self):
60
- return f"def {self.name}({', '.join([arg.get_name() for arg in self.args])}):"
96
+ sig = f"def {self.name}({', '.join([arg[0].to_python() + " = " + arg[1].to_python() if isinstance(arg, tuple) else arg.to_python() for arg in self.args])})"
97
+ if self.return_type is not None:
98
+ sig += f" -> {self.return_type.to_python()}"
99
+ if self.is_async:
100
+ sig = "async " + sig
101
+ sig = sig + ":"
102
+ if self.is_static:
103
+ sig = "static " + sig
104
+ if self.comment != "":
105
+ sig = (
106
+ sig
107
+ + "\n\t"
108
+ + '"""'
109
+ + "\n\t".join(self.comment.split("\n"))
110
+ + "\n\t"
111
+ + '"""'
112
+ )
113
+ return sig
114
+
115
+ def to_typescript(self):
116
+ if self.is_async:
117
+ keyword = "async "
118
+ else:
119
+ keyword = ""
120
+
121
+ if self.is_static:
122
+ keyword += "static "
123
+
124
+ sig = (
125
+ keyword
126
+ + f"{self.name}({', '.join([arg[0].to_typescript() + " = " + arg[1].to_typescript() if isinstance(arg, tuple) else arg.to_typescript() for arg in self.args])})"
127
+ )
128
+ if self.return_type is not None:
129
+ sig += f": {self.return_type.to_typescript()}"
130
+ if self.comment != "":
131
+ sig = (
132
+ "\n".join("/// " + line for line in self.comment.split("\n"))
133
+ + "\n"
134
+ + sig
135
+ )
136
+ return sig
61
137
 
62
138
 
63
139
  @dataclass
64
140
  class DefClassStatement(Statement):
65
141
  name: str
142
+ parents: Sequence[Expr] = field(default_factory=list)
143
+
144
+ def to_python(self):
145
+ if len(self.parents) == 0:
146
+ return f"class {self.name}:"
147
+ return f"class {self.name}({', '.join(p.to_python() for p in self.parents)}):"
148
+
149
+ def to_typescript(self):
150
+ # export by default because we do not have way to make this class private yet.
151
+ if len(self.parents) > 0:
152
+ extend = f" extends {' '.join(p.to_typescript() for p in self.parents)}"
153
+ else:
154
+ extend = ""
155
+ return f"export class {self.name}" + extend
156
+
157
+
158
+ @dataclass
159
+ class DefInterfaceStatement(Statement):
160
+ name: str
161
+ parents: Sequence[Expr] = field(default_factory=list)
66
162
 
67
163
  def to_python(self):
68
- return f"class {self.name}:"
164
+ raise ValueError("Python does not have interfaces")
165
+
166
+ def to_typescript(self):
167
+ # export by default because we do not have way to make this class private yet.
168
+ if len(self.parents) > 0:
169
+ extend = f" extends {' '.join(p.to_typescript() for p in self.parents)}"
170
+ else:
171
+ extend = ""
172
+ return f"export interface {self.name}" + extend
173
+
174
+
175
+ @dataclass
176
+ class DefClassVarStatement(Statement):
177
+ """Statement to define a variable with type"""
178
+
179
+ # name of the variable
180
+ name: str
181
+ # type of the variable
182
+ type: Optional[str]
183
+ # value of the variable
184
+ value: Optional[Expr] = None
185
+
186
+ def to_python(self):
187
+ if self.type is None:
188
+ if self.value is None:
189
+ return f"{self.name}"
190
+ return f"{self.name} = {self.value.to_python()}"
191
+ if self.value is None:
192
+ return f"{self.name}: {self.type}"
193
+ return f"{self.name}: {self.type} = {self.value.to_python()}"
194
+
195
+ def to_typescript(self):
196
+ assert self.type is not None
197
+ if self.value is None:
198
+ return f"{self.name}: {self.type};"
199
+ return f"{self.name}: {self.type} = {self.value.to_typescript()};"
69
200
 
70
201
 
71
202
  @dataclass
72
203
  class AssignStatement(Statement):
73
- var: Var
204
+ var: Var | Expr
74
205
  expr: Expr
75
206
 
76
207
  def to_python(self):
77
- return f"{self.var.get_name()} = {self.expr.to_python()}"
208
+ if isinstance(self.var, Var):
209
+ return f"{self.var.get_name()} = {self.expr.to_python()}"
210
+ else:
211
+ assert isinstance(self.var, Expr)
212
+ return f"{self.var.to_python()} = {self.expr.to_python()}"
213
+
214
+ def to_typescript(self):
215
+ if isinstance(self.var, Var):
216
+ return f"{self.var.get_name()} = {self.expr.to_typescript()};"
217
+ else:
218
+ assert isinstance(self.var, Expr)
219
+ return f"{self.var.to_typescript()} = {self.expr.to_typescript()};"
78
220
 
79
221
 
80
222
  @dataclass
@@ -84,6 +226,9 @@ class SingleExprStatement(Statement):
84
226
  def to_python(self):
85
227
  return self.expr.to_python()
86
228
 
229
+ def to_typescript(self):
230
+ return self.expr.to_typescript()
231
+
87
232
 
88
233
  @dataclass
89
234
  class ExceptionStatement(Statement):
@@ -113,6 +258,9 @@ class BreakStatement(Statement):
113
258
  def to_python(self):
114
259
  return "break"
115
260
 
261
+ def to_typescript(self):
262
+ return "break;"
263
+
116
264
 
117
265
  @dataclass
118
266
  class ReturnStatement(Statement):
@@ -121,6 +269,9 @@ class ReturnStatement(Statement):
121
269
  def to_python(self):
122
270
  return f"return {self.expr.to_python()}"
123
271
 
272
+ def to_typescript(self):
273
+ return f"return {self.expr.to_typescript()};"
274
+
124
275
 
125
276
  @dataclass
126
277
  class IfStatement(Statement):
@@ -150,3 +301,24 @@ class PythonStatement(Statement):
150
301
 
151
302
  def to_python(self):
152
303
  return self.stmt
304
+
305
+
306
+ @dataclass
307
+ class TypescriptStatement(Statement):
308
+ stmt: str
309
+
310
+ def to_python(self):
311
+ raise NotImplementedError()
312
+
313
+ def to_typescript(self):
314
+ return self.stmt
315
+
316
+
317
+ @dataclass
318
+ class PythonDecoratorStatement(Statement):
319
+ decorator: ExprFuncCall
320
+
321
+ def to_python(self):
322
+ if len(self.decorator.args) == 0:
323
+ return f"@{self.decorator.func_name.to_python()}"
324
+ return f"@{self.decorator.to_python()}"
codegen/models/var.py CHANGED
@@ -1,10 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
- from typing import NamedTuple, Optional
4
+ from typing import TYPE_CHECKING, NamedTuple, Optional
5
5
 
6
6
  from codegen.models.types import AST_ID, KEY, NO_KEY
7
7
 
8
+ if TYPE_CHECKING:
9
+ from codegen.models.expr import ExprIdent
10
+
8
11
 
9
12
  class VarScope(NamedTuple):
10
13
  ast: AST_ID # the ast that has a child, which is an assign statement, that the first time the variable is defined
@@ -24,29 +27,51 @@ class VarScope(NamedTuple):
24
27
 
25
28
  @dataclass
26
29
  class Var: # variable
30
+ """To create the variable for the first time, use DeferredVar."""
31
+
27
32
  name: str
28
33
  key: KEY
29
34
  register_id: int
30
35
  scope: VarScope
31
36
  force_name: Optional[str] = None
37
+ # type of the variable
38
+ type: Optional[ExprIdent] = None
32
39
 
33
40
  def get_name(self) -> str:
34
41
  if self.force_name is None:
35
42
  return f"{self.name}_{self.register_id}"
36
43
  return self.force_name
37
44
 
45
+ def to_python(self):
46
+ """Get the python code to create the variable"""
47
+ if self.type is None:
48
+ return f"{self.get_name()}"
49
+ return f"{self.get_name()}: {self.type.to_python()}"
50
+
51
+ def to_typescript(self):
52
+ """Get the typescript code to create the variable"""
53
+ if self.type is None:
54
+ return f"{self.get_name()}"
55
+ return f"{self.get_name()}: {self.type.to_typescript()}"
56
+
38
57
 
39
58
  @dataclass
40
59
  class DeferredVar:
41
- """Containings the information to create a variable"""
60
+ """Containings the information to create a variable. This is the class to use to create variable."""
42
61
 
43
62
  name: str
44
63
  key: KEY = NO_KEY
45
64
  force_name: Optional[str] = None
65
+ type: Optional[ExprIdent] = None
46
66
 
47
67
  # the variable that we want to create --- this will be not None when the variable is actually created
48
68
  _var: Optional[Var] = None
49
69
 
70
+ @staticmethod
71
+ def simple(name: str, type: Optional[ExprIdent] = None) -> DeferredVar:
72
+ """Create a DeferredVar with the given name and type"""
73
+ return DeferredVar(name, (name,), name, type)
74
+
50
75
  def get_var(self) -> Var:
51
76
  if self._var is None:
52
77
  raise ValueError("The variable has not been created yet")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: codegen-2
3
- Version: 2.1.4
3
+ Version: 2.5.2
4
4
  Summary: Meta-programming
5
5
  License: MIT
6
6
  Author: Binh Vu
@@ -0,0 +1,12 @@
1
+ codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ codegen/models/__init__.py,sha256=j__FrDdGOILIo9jqEDElL3YP69h0xkL2SqrMxSqgpTc,457
3
+ codegen/models/ast.py,sha256=74cLjaZqrC_Cpo4WQqcXvuTZMcpfvNGYmvOqACeYD48,10366
4
+ codegen/models/expr.py,sha256=uFlJThzGSGFavC_9ExhTrLQ7Z5na7C6oXRFGIO_cas0,10576
5
+ codegen/models/program.py,sha256=mrvtOp9WpaZ6B5KOGpFFLBXMtSCo-BpuGCEgipUuBV8,5062
6
+ codegen/models/statement.py,sha256=50bl4-ahjHtBfds3gEMd_4KynheHa4i2EN0zvJ9PaiU,8450
7
+ codegen/models/types.py,sha256=Dl-wzGB1viA7EZj2CuTrZe1F133Q6ENVr_yRqxhde8M,178
8
+ codegen/models/var.py,sha256=sOzDrqJHkAgA2Tqhh6IelW3dDe2o7us6HPjaRBVKmCQ,2722
9
+ codegen_2-2.5.2.dist-info/LICENSE,sha256=Ea6itrykT9pvPGd0Kgl6FbrqdDwKswPZJmXMFVjUBqw,1064
10
+ codegen_2-2.5.2.dist-info/METADATA,sha256=NFWJKwFC5-1KMZ8-6Zb0TXHK-zIJFzEx7xssgBvwxHE,487
11
+ codegen_2-2.5.2.dist-info/WHEEL,sha256=fGIA9gx4Qxk2KDKeNJCbOEwSrmLtjWCwzBz351GyrPQ,88
12
+ codegen_2-2.5.2.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.1.1
2
+ Generator: poetry-core 2.1.2
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,12 +0,0 @@
1
- codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- codegen/models/__init__.py,sha256=j__FrDdGOILIo9jqEDElL3YP69h0xkL2SqrMxSqgpTc,457
3
- codegen/models/ast.py,sha256=rUb_LOKijxbjNDHycc4E_M1GeFs3CQ8MAbpuWNPJvuI,7892
4
- codegen/models/expr.py,sha256=bGc-ZTbgGLmepPs-Zef4VP07WMfvCQb2AFeM7JDPKHc,5032
5
- codegen/models/program.py,sha256=6ggzINtk1i9WeSFsiI8Qa6TiNJEafXbXwYqKoq4k_xA,4471
6
- codegen/models/statement.py,sha256=_H5PWCw-zUPIX0fCHQ5iDtR9WeeL9qPW6mMOfQJSvKY,3025
7
- codegen/models/types.py,sha256=Dl-wzGB1viA7EZj2CuTrZe1F133Q6ENVr_yRqxhde8M,178
8
- codegen/models/var.py,sha256=3T-GEv5z6T31HfAUOJ7TTjN3WF3ejY3rfRNvrIUfLP8,1771
9
- codegen_2-2.1.4.dist-info/LICENSE,sha256=Ea6itrykT9pvPGd0Kgl6FbrqdDwKswPZJmXMFVjUBqw,1064
10
- codegen_2-2.1.4.dist-info/METADATA,sha256=tq9u81WlHLs9WwlSI-S4TG-rCUhOIxJKf3PQKsPQdq4,487
11
- codegen_2-2.1.4.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88
12
- codegen_2-2.1.4.dist-info/RECORD,,