-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFunctionAst.java
More file actions
126 lines (111 loc) · 2.49 KB
/
FunctionAst.java
File metadata and controls
126 lines (111 loc) · 2.49 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
package org.piccode.ast;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.piccode.piccodescript.TargetEnvironment;
import org.piccode.rt.Context;
import org.piccode.rt.PiccodeClosure;
import org.piccode.rt.PiccodeValue;
/**
*
* @author hexaredecimal
*/
public class FunctionAst extends Ast {
public String name;
public List<Arg> arg;
public Ast body;
public FunctionAst(String name, List<Arg> arg, Ast body) {
this.name = name;
this.arg = arg;
this.body = body;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb
.append(name)
.append(" :: (");
if (arg != null) {
sb.append(formatArgs());
}
sb.append(") = ...");
return sb.toString();
}
private String formatArgs() {
var sb = new StringBuilder();
var size = arg.size();
for (int i = 0; i < size; i++) {
var top_arg = arg.get(i);
sb.append(top_arg);
if (i < size - 1) {
sb.append(", ");
}
}
return sb.toString();
}
@Override
public PiccodeValue execute(Integer frame) {
var ctx = frame == null
? Context.top
: Context.getContextAt(frame);
Map<String, PiccodeValue> newArgs = new HashMap<>();
var cl = new PiccodeClosure(arg, newArgs, 0, body);
cl.creator = this;
cl.frame = frame;
cl.callSite = new Ast.Location(line, column);
cl.callSiteFile = file;
cl.file = file;
cl.column = column;
cl.line = line;
ctx.putLocal(name, cl);
return cl;
}
@Override
public String codeGen(TargetEnvironment target) {
return switch (target) {
case JS ->
codeGenJSFunction(target);
default ->
"todo";
};
}
private String codeGenJSFunction(TargetEnvironment env) {
var sb = new StringBuilder()
.append("function ");
if (arg.isEmpty()) {
sb
.append(name)
.append("() { \n")
.append("return ")
.append(body.codeGen(env))
.append(";\n}");
return sb.toString();
}
sb
.append(name);
for (int i = 0; i < arg.size(); i++) {
var ar = arg.get(i);
if (i == 0) {
sb
.append("(")
.append(ar.name)
.append(") { \n return ");
continue;
}
var fn = String.format("inner_%sl%dc%d", name, ar.line, ar.column);
sb
.append("function ")
.append(fn)
.append("(")
.append(ar.name)
.append(") { \n return ");
}
var done = "}".repeat(arg.size());
sb
.append(body.codeGen(env).indent(4))
.append(done)
.append("\n");
return sb.toString();
}
}