-
Notifications
You must be signed in to change notification settings - Fork 28
/
ModuleLib.java
703 lines (591 loc) · 22 KB
/
ModuleLib.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/*
* Copyright 2016 Miroslav Janíček
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* --
* Portions of this file are licensed under the Lua license. For Lua
* licensing details, please visit
*
* http://www.lua.org/license.html
*
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* 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 NONINFRINGEMENT.
* 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.
*/
package net.sandius.rembulan.lib;
import net.sandius.rembulan.ByteString;
import net.sandius.rembulan.ByteStringBuilder;
import net.sandius.rembulan.Conversions;
import net.sandius.rembulan.LuaRuntimeException;
import net.sandius.rembulan.StateContext;
import net.sandius.rembulan.Table;
import net.sandius.rembulan.env.RuntimeEnvironment;
import net.sandius.rembulan.impl.UnimplementedFunction;
import net.sandius.rembulan.load.ChunkLoader;
import net.sandius.rembulan.load.LoaderException;
import net.sandius.rembulan.runtime.Dispatch;
import net.sandius.rembulan.runtime.ExecutionContext;
import net.sandius.rembulan.runtime.LuaFunction;
import net.sandius.rembulan.runtime.ResolvedControlThrowable;
import net.sandius.rembulan.runtime.UnresolvedControlThrowable;
import net.sandius.rembulan.util.ByteIterator;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
/**
* The package library provides basic facilities for loading modules in Lua. It exports
* one function directly in the global environment: {@code require}.
* Everything else is exported in a {@code table} package.
*/
public final class ModuleLib {
static final byte PATH_SEPARATOR = (byte) ';';
static final byte PATH_TEMPLATE_PLACEHOLDER = (byte) '?';
static final byte WIN_DIRECTORY_PLACEHOLDER = (byte) '!'; // FIXME: not used in Rembulan
static final byte LUAOPEN_IGNORE = (byte) '-'; // FIXME: not used in Rembulan!
/**
* Returns a function {@code package.searchpath} that uses {@code fileSystem}.
*
* <p>The following is the corresponding entry from the Lua Reference Manual:</p>
*
* <blockquote>
* {@code package.searchpath (name, path [, sep [, rep]])}
*
* <p>Searches for the given name in the given path.</p>
*
* <p>A path is a string containing a sequence of templates separated by semicolons.
* For each template, the function replaces each interrogation mark (if any) in the template
* with a copy of name wherein all occurrences of {@code sep} (a dot, by default) were
* replaced by {@code rep} (the system's directory separator, by default), and then tries
* to open the resulting file name.</p>
*
* <p>For instance, if the path is the string</p>
* <pre>
* "./?.lua;./?.lc;/usr/local/?/init.lua"
* </pre>
* <p>the search for the name {@code foo.a} will try to open the files {@code ./foo/a.lua},
* {@code ./foo/a.lc}, and {@code /usr/local/foo/a/init.lua}, in that order.</p>
*
* <p>Returns the resulting name of the first file that it can open in read mode (after closing
* the file), or <b>nil</b> plus an error message if none succeeds. (This error message
* lists all file names it tried to open.)</p>
* </blockquote>
*
* @param fileSystem the filesystem, must not be {@code null}
* @return the function {@code package.searchpath}
*
* @throws NullPointerException if {@code fileSystem} is {@code null}
*
* @see <a href="http://www.lua.org/manual/5.3/manual.html#pdf-coroutine.yield">
* the Lua 5.3 Reference Manual entry for <code>coroutine.yield</code></a>
*/
public static LuaFunction searchpath(FileSystem fileSystem) {
return new SearchPath(fileSystem);
}
// TODO: publish require
private ModuleLib() {
// not to be instantiated
}
/**
* Installs the package library to the global environment {@code env} in the state
* context {@code context}. The package functions will use the runtime environment
* {@code runtimeEnvironment}, and load modules using {@code chunkLoader} (for Lua
* scripts), and {@code classLoader} (for Java libraries).
*
* <p>The nullity of {@code runtimeEnvironment}, {@code runtimeEnvironment.fileSystem()},
* {@code chunkLoader} and {@code classLoader} determines the configuration in which
* the package library will be installed:</p>
* <ul>
* <li>if {@code runtimeEnvironment == null || runtimeEnvironment.fileSystem() == null},
* then no {@code package.config}, {@code package.path} and {@code package.searchpath}
* will be provided, and the searchers will not include any searchers or loaders
* that require access to a filesystem;</li>
* <li>if {@code chunkLoader == null}, then no searchers and loaders that load
* Lua chunks will be installed;</li>
* <li>if {@code classLoader == null}, then no searchers and loaders that load
* Java modules by examining the classpath of the virtual machine will be installed.</li>
* </ul>
*
* <p>For instance, if {@code runtimeEnvironment}, {@code chunkLoader}
* and {@code classLoader} are all {@code null}, then the only way for a module to be
* installed using the {@code require} function will be by adding a loader to
* {@code package.preload}.</p>
*
* <p>Installs {@code env} and the module library table to {@code env.package.loaded}
* with the keys {@code "_G"} and {@code "package"}, respectively.</p>
*
* @param context the state context, must not be {@code null}
* @param env the global environment, must not be {@code null}
* @param runtimeEnvironment the runtime environment, may be {@code null}
* @param chunkLoader the chunk loader, may be {@code null}
* @param classLoader the class loader for Java modules, may be {@code null}
*
* @throws NullPointerException if {@code context} or {@code env} is {@code null}
*/
public static void installInto(StateContext context, Table env, RuntimeEnvironment runtimeEnvironment, ChunkLoader chunkLoader, ClassLoader classLoader) {
Objects.requireNonNull(context);
Objects.requireNonNull(env);
FileSystem fileSystem = runtimeEnvironment != null ? runtimeEnvironment.fileSystem() : null;
Table t = context.newTable();
final ByteString config;
Table loaded = context.newTable();
Table preload = context.newTable();
final ByteString path;
Table searchers = context.newTable();
LuaFunction require = new Require(t, loaded);
// package.config
{
if (fileSystem != null) {
ByteStringBuilder builder = new ByteStringBuilder();
builder.append(fileSystem.getSeparator()).append((byte) '\n');
builder.append(PATH_SEPARATOR).append((byte) '\n');
builder.append(PATH_TEMPLATE_PLACEHOLDER).append((byte) '\n');
builder.append(WIN_DIRECTORY_PLACEHOLDER).append((byte) '\n');
builder.append(LUAOPEN_IGNORE).append((byte) '\n');
config = builder.toByteString();
}
else {
config = null;
}
}
// package.loaded
{
loaded.rawset("_G", env);
loaded.rawset("package", t);
}
// package.path
{
if (runtimeEnvironment != null) {
String envPath = runtimeEnvironment.getEnv("LUA_PATH_5_3");
if (envPath == null) {
envPath = runtimeEnvironment.getEnv("LUA_PATH");
}
path = getPath(envPath, defaultPath(runtimeEnvironment.fileSystem()));
}
else {
path = null;
}
}
// package.searchers
{
addSearcher(searchers, new PreloadSearcher(preload));
if (chunkLoader != null) {
addSearcher(searchers, new ChunkLoadPathSearcher(fileSystem, t, chunkLoader, env));
}
if (classLoader != null) {
addSearcher(searchers, new LoaderProviderServiceLoaderSearcher(runtimeEnvironment, env, classLoader));
}
}
t.rawset("config", config);
t.rawset("loaded", loaded);
t.rawset("loadlib", new UnimplementedFunction("package.loadlib"));
t.rawset("preload", preload);
t.rawset("searchers", searchers);
if (fileSystem != null) t.rawset("searchpath", searchpath(fileSystem));
t.rawset("path", path);
// install into the global environment
env.rawset("package", t);
env.rawset("require", require);
}
static void addSearcher(Table searchers, LuaFunction fn) {
searchers.rawset(searchers.rawlen() + 1, fn);
}
static void addToLoaded(Table env, String modName, Object value) {
Object pkg = env.rawget("package");
if (pkg instanceof Table) {
Object loaded = ((Table) pkg).rawget("loaded");
if (loaded instanceof Table) {
((Table) loaded).rawset(modName, value);
}
}
}
static void addToPreLoad(Table env, String modName, LuaFunction loader) {
Object pkg = env.rawget("package");
if (pkg instanceof Table) {
Object preload = ((Table) pkg).rawget("preload");
if (preload instanceof Table) {
((Table) preload).rawset(modName, loader);
}
}
}
static void install(Table env, String modName, Object value) {
env.rawset(modName, value);
addToLoaded(env, modName, value);
}
static Table searchers(Table libTable) {
Object o = libTable.rawget("searchers");
return o instanceof Table ? (Table) o : null;
}
static ByteString defaultPath(FileSystem fileSystem) {
// TODO: make this depend on the platform
return ByteString.of("/usr/local/share/lua/5.3/?.lua;/usr/local/share/lua/5.3/?/init.lua;/usr/local/lib/lua/5.3/?.lua;/usr/local/lib/lua/5.3/?/init.lua;./?.lua;./?/init.lua");
}
static ByteString getPath(String envPath, ByteString defaultPath) {
if (envPath != null) {
return ByteString.of(envPath).replace(ByteString.of(";;"), defaultPath);
}
else {
return defaultPath;
}
}
static class Require extends AbstractLibFunction {
private final Table libTable;
private final Table loaded;
private static class Require_SuspendedState {
private final int state;
private final ByteString error;
private final ByteString modName;
private final Table searchers;
private final long idx;
private Require_SuspendedState(int state, ByteString error, ByteString modName, Table searchers, long idx) {
this.state = state;
this.error = error;
this.modName = modName;
this.searchers = searchers;
this.idx = idx;
}
}
public Require(Table libTable, Table loaded) {
this.libTable = Objects.requireNonNull(libTable);
this.loaded = Objects.requireNonNull(loaded);
}
@Override
protected String name() {
return "require";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ByteString modName = args.nextString();
Object mod = loaded.rawget(modName);
if (mod != null) {
// already loaded
context.getReturnBuffer().setTo(mod);
}
else {
// get package.searchers
Table searchers = searchers(libTable);
if (searchers == null) {
throw new IllegalStateException("'package.searchers' must be a table");
}
search(context, 0, ByteString.empty(), modName, searchers, 1);
}
}
private void search(ExecutionContext context, int state, ByteString error, ByteString modName, Table searchers, long idx)
throws ResolvedControlThrowable {
final LuaFunction loader;
final Object origin;
loop:
while (true) {
try {
switch (state) {
case 0:
Object o = searchers.rawget(idx++);
if (o == null) {
// reached the end of the list
throw new LuaRuntimeException("module '" + modName + "' not found:" + error);
}
state = 1;
Dispatch.call(context, o, modName);
case 1:
Object result = context.getReturnBuffer().get0();
if (result instanceof LuaFunction) {
// found it
loader = (LuaFunction) result;
origin = context.getReturnBuffer().get1();
break loop;
}
else {
// not a loader
// append error string
ByteString s = Conversions.stringValueOf(result);
if (s != null) {
error = error.concat(s);
}
state = 0; // continue with the next iteration
break;
}
default:
throw new IllegalStateException("Invalid state: " + state);
}
}
catch (UnresolvedControlThrowable ct) {
throw ct.resolve(this, new Require_SuspendedState(state, error, modName, searchers, idx));
}
}
load(context, modName, loader, origin);
}
private void load(ExecutionContext context, ByteString modName, LuaFunction loader, Object origin)
throws ResolvedControlThrowable {
try {
Dispatch.call(context, loader, modName, origin);
}
catch (UnresolvedControlThrowable ct) {
throw ct.resolve(this, modName);
}
resumeLoad(context, modName);
}
private void resumeLoad(ExecutionContext context, ByteString modName) {
Object loadResult = context.getReturnBuffer().get0();
Object requireResult = loadResult != null ? loadResult : true;
loaded.rawset(modName, requireResult);
context.getReturnBuffer().setTo(requireResult);
}
@Override
public void resume(ExecutionContext context, Object suspendedState) throws ResolvedControlThrowable {
if (suspendedState instanceof Require_SuspendedState) {
Require_SuspendedState ss = (Require_SuspendedState) suspendedState;
search(context, ss.state, ss.error, ss.modName, ss.searchers, ss.idx);
}
else {
resumeLoad(context, (ByteString) suspendedState);
}
}
}
static class PreloadSearcher extends AbstractLibFunction {
private final Table preload;
PreloadSearcher(Table preload) {
this.preload = Objects.requireNonNull(preload);
}
@Override
protected String name() {
return "(preload searcher)";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ByteString modName = args.nextString();
Object entry = preload.rawget(modName);
if (entry != null) {
context.getReturnBuffer().setTo(entry);
}
else {
String error = "\n\tno field package.preload['" + modName + "']";
context.getReturnBuffer().setTo(error);
}
}
}
static class ChunkLoadPathSearcher extends AbstractLibFunction {
private final Table libTable;
private final FileSystem fileSystem;
private final ChunkLoader loader;
private final Object env;
ChunkLoadPathSearcher(FileSystem fileSystem, Table libTable, ChunkLoader loader, Object env) {
this.fileSystem = Objects.requireNonNull(fileSystem);
this.libTable = Objects.requireNonNull(libTable);
this.loader = Objects.requireNonNull(loader);
this.env = env;
}
@Override
protected String name() {
return "(path searcher)";
}
private LuaFunction loaderForPath(ByteString path) throws LoaderException {
return BasicLib.loadTextChunkFromFile(fileSystem, loader, path.toString(), BasicLib.Load.DEFAULT_MODE, env);
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ByteString modName = args.nextString();
// FIXME: it might be easier and more modular to just call package.searchpath and loadfile
ByteString path = Conversions.stringValueOf(libTable.rawget("path"));
if (path == null) {
throw new IllegalStateException("'package.path' must be a string");
}
List<ByteString> paths = SearchPath.getPaths(modName, path, SearchPath.DEFAULT_SEP, ByteString.of(fileSystem.getSeparator()));
ByteStringBuilder msgBuilder = new ByteStringBuilder();
for (ByteString s : paths) {
Path p = fileSystem.getPath(s.toString());
if (Files.isReadable(p)) {
final LuaFunction fn;
try {
fn = loaderForPath(s);
}
catch (LoaderException ex) {
throw new LuaRuntimeException("error loading module '" + modName + "' from file '" + s + "'"
+ "\n\t" + ex.getLuaStyleErrorMessage());
}
context.getReturnBuffer().setTo(fn, s);
return;
}
else {
msgBuilder.append("\n\tno file '").append(s).append((byte) '\'');
}
}
context.getReturnBuffer().setTo(msgBuilder.toByteString());
}
}
/**
* An abstract searcher function that uses a {@link ServiceLoader} to discover
* loader services.
*
* @param <T> the type of the loader service
*/
static abstract class AbstractServiceLoaderSearcher<T> extends AbstractLibFunction {
private final Class<T> serviceClass;
private final ServiceLoader<T> serviceLoader;
protected AbstractServiceLoaderSearcher(Class<T> serviceClass, ClassLoader classLoader) {
this.serviceClass = Objects.requireNonNull(serviceClass);
this.serviceLoader = ServiceLoader.load(serviceClass, classLoader);
}
@Override
protected String name() {
return "(" + serviceClass.getName() + " ServiceLoader searcher)";
}
private LuaFunction findLoader(String modName) {
try {
for (T service : serviceLoader) {
if (matches(modName, service)) {
LuaFunction loader = getLoader(service);
if (loader != null) {
return loader;
}
}
}
}
catch (ServiceConfigurationError error) {
// TODO: maybe we should just let the VM crash?
throw new LuaRuntimeException(error);
}
// not found
return null;
}
/**
* Returns {@code} true if the given service {@code service} provides a module with
* the name {@code moduleName}.
*
* @param moduleName module name
* @param service a service to be examined
*
* @return {@code true} if the {@code service} provides a module with the name
* {@code moduleName}
*/
protected abstract boolean matches(String moduleName, T service);
/**
* Returns the loader provided by a given service.
*
* <p>May return {@code null} to indicate that {@code service} does not provide
* a loader.</p>
*
* @param service the service to get the loader from
* @return the loader function
*/
protected abstract LuaFunction getLoader(T service);
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ByteString modName = args.nextString();
LuaFunction loader = findLoader(modName.toString());
if (loader != null) {
context.getReturnBuffer().setTo(loader);
}
else {
String error = "\n\tno " + serviceClass.getName() + " for '" + modName + "'";
context.getReturnBuffer().setTo(error);
}
}
}
static class LoaderProviderServiceLoaderSearcher extends AbstractServiceLoaderSearcher<LoaderProvider> {
private final RuntimeEnvironment runtimeEnvironment;
private final Table env;
public LoaderProviderServiceLoaderSearcher(RuntimeEnvironment runtimeEnvironment, Table env, ClassLoader classLoader) {
super(LoaderProvider.class, classLoader);
this.runtimeEnvironment = Objects.requireNonNull(runtimeEnvironment);
this.env = Objects.requireNonNull(env);
}
@Override
protected boolean matches(String modName, LoaderProvider service) {
return service.name().equals(modName);
}
@Override
protected LuaFunction getLoader(LoaderProvider service) {
return service.newLoader(runtimeEnvironment, env);
}
}
static class SearchPath extends AbstractLibFunction {
private static final ByteString DEFAULT_SEP = ByteString.constOf(".");
private final FileSystem fileSystem;
private final ByteString defaultDirSeparator;
SearchPath(FileSystem fileSystem) {
this.fileSystem = Objects.requireNonNull(fileSystem);
defaultDirSeparator = ByteString.of(fileSystem.getSeparator());
}
@Override
protected String name() {
return "searchpath";
}
static List<ByteString> getPaths(ByteString name, ByteString path, ByteString sep, ByteString rep) {
List<ByteString> result = new ArrayList<>();
name = name.replace(sep, rep);
ByteStringBuilder builder = new ByteStringBuilder();
ByteIterator it = path.byteIterator();
while (it.hasNext()) {
byte b = it.nextByte();
switch (b) {
case PATH_TEMPLATE_PLACEHOLDER:
builder.append(name);
break;
case PATH_SEPARATOR:
result.add(builder.toByteString());
builder.setLength(0);
break;
default:
builder.append(b);
break;
}
}
if (builder.length() > 0) {
result.add(builder.toByteString());
}
return result;
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ByteString name = args.nextString();
ByteString path = args.nextString();
ByteString sep = args.nextOptionalString(DEFAULT_SEP);
ByteString rep = args.nextOptionalString(defaultDirSeparator);
ByteStringBuilder msgBuilder = new ByteStringBuilder();
for (ByteString s : getPaths(name, path, sep, rep)) {
Path p = fileSystem.getPath(s.toString());
if (Files.isReadable(p)) {
context.getReturnBuffer().setTo(s);
return;
}
else {
msgBuilder.append("\n\tno file '").append(s).append((byte) '\'');
}
}
// no readable file found
context.getReturnBuffer().setTo(null, msgBuilder.toString());
}
}
}