-
Notifications
You must be signed in to change notification settings - Fork 120
/
EOrust.java
285 lines (274 loc) 路 9.48 KB
/
EOrust.java
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2024 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* @checkstyle PackageNameCheck (8 lines)
*/
package EOorg.EOeolang;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.eolang.AtFree;
import org.eolang.Atom;
import org.eolang.Data;
import org.eolang.ExFailure;
import org.eolang.ExNative;
import org.eolang.PhDefault;
import org.eolang.Phi;
import org.eolang.Universe;
import org.eolang.UniverseDefault;
import org.eolang.UniverseSafe;
import org.eolang.Versionized;
import org.eolang.XmirObject;
/**
* Rust.
*
* @since 0.29
* @checkstyle MethodNameCheck (100 lines)
* @checkstyle LineLengthCheck (100 lines)
* @checkstyle TypeNameCheck (5 lines)
*/
@Versionized
@XmirObject(oname = "rust")
public final class EOrust extends PhDefault implements Atom {
/**
* Map with location of the `code` attribute as the key
* and native method as the value.
*/
private static final ConcurrentHashMap<String, String> NAMES;
/**
* All phis indexed while executing of native method.
*/
private final Map<Integer, Phi> phis = new HashMap<>();
/**
* Error that possibly was thrown while the native function execution.
*/
private final AtomicReference<Throwable> error = new AtomicReference<>();
static {
try {
NAMES = load("target/names");
} catch (final IOException exc) {
throw new ExFailure(
"Cannot read the file target/eo-test/names",
exc
);
}
final String lib;
final String system = System.getProperty("os.name").toLowerCase();
if (system.contains("win")) {
lib = "common.dll";
} else if (system.contains("nix") || system.contains("nux") || system.contains("aix")) {
lib = "libcommon.so";
} else if (system.contains("mac")) {
lib = "libcommon.dylib";
} else {
throw new UnsupportedOperationException(
String.format(
"Rust inserts are not supported by %s os. Only windows, linux and macos are allowed.",
System.getProperty("os.name")
)
);
}
final File libs = Paths.get("target")
.resolve("eo-test")
.resolve("Lib").toFile();
if (libs.isDirectory()) {
for (final File subdir : libs.listFiles()) {
final Path path = subdir.toPath()
.resolve("target")
.resolve("debug")
.resolve(lib)
.toAbsolutePath();
if (path.toFile().exists()) {
System.load(path.toString());
}
}
}
}
/**
* Ctor.
* @param sigma Sigma
*/
public EOrust(final Phi sigma) {
super(sigma);
this.add("code", new AtFree());
this.add("portal", new AtFree());
this.add("params", new AtFree());
}
@Override
public Phi lambda() throws Exception {
final String name = NAMES.get(
this.attr("code").get().locator().split(":")[0]
);
final Method method = Class.forName(
String.format(
"EOrust.natives.%s",
name
)
).getDeclaredMethod(name, Universe.class);
if (method.getReturnType() != byte[].class) {
throw new ExFailure(
"Return type of %s is %s, required %s",
method,
method.getReturnType(),
byte[].class
);
}
final Phi portal = this.attr("portal").get();
return this.translate(
(byte[]) method.invoke(
null,
new UniverseSafe(
new UniverseDefault(
portal, this.phis
),
this.error
)
),
this.attr("code").get().locator()
);
}
/**
* Loads names map.
* @param src Where to load from.
* @return Names map.
* @throws IOException If any issues with IO.
*/
private static ConcurrentHashMap<String, String> load(final String src) throws IOException {
try (ObjectInputStream map = new ObjectInputStream(
new ByteArrayInputStream(
Base64.getDecoder().decode(
Files.readAllBytes(Paths.get(src))
)
)
)) {
final Object result = map.readObject();
if (result.getClass() != ConcurrentHashMap.class) {
throw new ClassCastException(
String.format(
"Object inside %s has wrong class %s, a ConcurrentHashMap was expected",
src,
result.getClass()
)
);
}
return (ConcurrentHashMap<String, String>) result;
} catch (final ClassNotFoundException exc) {
throw new IllegalArgumentException(
String.format(
"File %s contains invalid data, a ConcurrentHashMap objects was expected",
src
),
exc
);
}
}
/**
* Translates byte message from rust side to Phi object.
* @param message Message that native method returns.
* @param insert Location of the rust insert.
* @return Phi object.
*/
private Phi translate(final byte[] message, final String insert) {
final byte determinant = message[0];
final byte[] content = Arrays.copyOfRange(message, 1, message.length);
final Phi ret;
final ByteBuffer buffer;
switch (determinant) {
case 0:
buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.put(content);
buffer.flip();
final int vertex = buffer.getInt();
ret = this.phis.get(vertex);
if (ret == null) {
throw new ExFailure(
String.format(
"Returned phi with vertex %d (%s in bytes) was not indexed",
vertex,
Arrays.toString(content)
)
);
}
break;
case 1:
buffer = ByteBuffer.allocate(Double.BYTES);
buffer.put(content);
buffer.flip();
ret = new Data.ToPhi(buffer.getDouble());
break;
case 2:
buffer = ByteBuffer.allocate(Long.BYTES);
buffer.put(content);
buffer.flip();
ret = new Data.ToPhi(buffer.getLong());
break;
case 4:
ret = new Data.ToPhi(content);
break;
case 3:
ret = new Data.ToPhi(
new String(content, StandardCharsets.UTF_8)
);
break;
case 5:
final String cause = new String(content, StandardCharsets.UTF_8);
if (this.error.get() == null) {
throw new ExNative(
"Rust insert failed in %s with message '%s'",
insert,
cause
);
} else {
throw new ExNative(
String.format(
"Rust insert failed in %s with message '%s'",
insert,
cause
),
this.error.get()
);
}
default:
throw new ExNative(
"Returning Strings and raw bytes is not implemented yet, insert %s",
insert
);
}
return ret;
}
}