Repository navigation
Expand file tree
/
Copy pathTranslator.cs
More file actions
125 lines (113 loc) · 3.55 KB
/
Copy pathTranslator.cs
File metadata and controls
125 lines (113 loc) · 3.55 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
using System.Web;
using Axion.Core.Processing.Lexical.Tokens;
using Axion.Core.Processing.Syntactic.Expressions;
using Axion.Core.Processing.Syntactic.Expressions.Definitions;
using Axion.Core.Processing.Syntactic.Expressions.Statements;
using Axion.Core.Processing.Syntactic.Expressions.TypeNames;
using Axion.Core.Processing.Translation;
namespace Axion.Emitter.Python;
public class Translator : INodeTranslator {
public string OutputFileExtension => ".py";
public bool Translate(CodeWriter w, ITranslatableNode node) {
switch (node) {
case CommentToken e: {
w.Write("#", e.Content);
break;
}
case StringToken e: {
if (e.HasPrefix("f")) {
w.Write("f");
}
if (e.HasPrefix("r")) {
w.Write("r");
}
w.Write(e.IsMultiline ? "\"\"\"" : "\"");
w.Write(HttpUtility.JavaScriptStringEncode(e.Content));
if (!e.IsUnclosed) {
w.Write(e.IsMultiline ? "\"\"\"" : "\"");
}
break;
}
case ClassDef e: {
w.Write("class ", e.Name);
if (e.Bases.Count > 0) {
w.Write("(");
w.AddJoin(", ", e.Bases);
w.Write(")");
}
w.Write(e.Scope);
break;
}
case FunctionDef e: {
w.Write("def ", e.Name, "(");
w.AddJoin(", ", e.Parameters);
w.Write(")");
if (e.InferredType != null) {
w.Write(" -> ", e.InferredType);
}
w.Write(e.Scope);
break;
}
case ModuleDef e: {
w.AddJoin("", e.Scope.Items, true);
break;
}
case NameDef e: {
w.Write(e.Name);
if (e.InferredType != null) {
w.Write(": ", e.InferredType);
}
if (e.Value != null) {
w.Write(" = ", e.Value);
}
break;
}
case EmptyExpr: {
w.Write("pass");
break;
}
case WhileExpr e: {
w.Write("while ", e.Condition, e.Scope);
break;
}
case ArrayTypeName e: {
w.Write("List[", e.ElementType, "]");
break;
}
case FuncTypeName e: {
w.Write(
"Callable[[",
e.ArgsType,
"], ",
e.ReturnType,
"]"
);
break;
}
case DecoratedExpr e: {
foreach (var decorator in e.Decorators) {
w.WriteLine("@", decorator);
}
w.Write(e.Target);
break;
}
case Ast e: {
w.AddJoin("", e.Items, true);
break;
}
case ScopeExpr e: {
w.Write(":");
w.IndentLevel++;
w.WriteLine();
w.AddJoin("", e.Items, true);
w.IndentLevel--;
w.MaybeWriteLine();
break;
}
default: {
return false;
}
}
return true;
}
}