<commit_before>/*
 * Copyright 2016 <NAME>
 *
 * 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.
 */

package net.sandius.rembulan.lib.impl;

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.TableFactory;
import net.sandius.rembulan.env.RuntimeEnvironment;
import net.sandius.rembulan.env.RuntimeEnvironments;
import net.sandius.rembulan.impl.UnimplementedFunction;
import net.sandius.rembulan.lib.Lib;
import net.sandius.rembulan.lib.LoaderProvider;
import net.sandius.rembulan.lib.ModuleLib;
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;

public class DefaultModuleLib extends ModuleLib {

	private final StateContext context;
	private final Table env;

	private final Table libTable;
	private final Table loaded;
	private final Table preload;

	private final LuaFunction require;

	private final LuaFunction _loadlib;
	private final LuaFunction _searchpath;

	/**
	 * Constructs a new instance of the default module library.
	 *
	 * @param context  state context to use by the library, must not be {@code null}
	 * @param runtimeEnvironment  runtime environment passed to instantiated libraries, must not be {@code null}
	 * @param env  the global table passed to the instantiated libraries, must not be {@code null}
	 * @param classLoader  class loader used for instantiating libraries, must not be {@code null}
	 */
	public DefaultModuleLib(StateContext context, RuntimeEnvironment runtimeEnvironment, Table env, ClassLoader classLoader, ChunkLoader chunkLoader) {
		this.context = Objects.requireNonNull(context);
		this.env = Objects.requireNonNull(env);
		Objects.requireNonNull(runtimeEnvironment);
		Objects.requireNonNull(classLoader);

		this.libTable = context.newTable();
		this.loaded = context.newTable();
		this.preload = context.newTable();
		Table searchers = context.newTable();

		this._searchpath = new SearchPath(runtimeEnvironment.fileSystem());

		libTable.rawset("loaded", loaded);
		libTable.rawset("preload", preload);
		libTable.rawset("searchers", searchers);
		libTable.rawset("searchpath", _searchpath);

		// initialise searchers
		long idx = 1;
		searchers.rawset(idx++, new PreloadSearcher(preload));
		if (chunkLoader != null) {
			searchers.rawset(idx++, new ChunkLoadPathSearcher(runtimeEnvironment.fileSystem(), libTable, chunkLoader, env));
		}
		searchers.rawset(idx++, new LoaderProviderServiceLoaderSearcher(runtimeEnvironment, env, classLoader));

		this.require = new Require();

		this._loadlib = new UnimplementedFunction("package.loadlib");
	}

	/**
	 * Constructs a new instance of the default module library.
	 *
	 * <b>Deprecated:</b> breaks sandboxing, and does not provide chunk loading.
	 * Use {@link DefaultModuleLib#DefaultModuleLib(StateContext, RuntimeEnvironment, Table, ClassLoader, ChunkLoader)}
	 * instead.
	 *
	 * @param context  state context, must not be {@code null}
	 * @param env  the global table, must not be {@code null}
	 */
	@Deprecated
	public DefaultModuleLib(StateContext context, Table env) {
		this(context, RuntimeEnvironments.system(), env, ClassLoader.getSystemClassLoader(), null);
	}

	@Override
	public Table toTable(TableFactory tableFactory) {
		return libTable;
	}

	@Override
	public void postInstall(StateContext context, Table env, Table libTable) {
		loaded.rawset("_G", env);
		loaded.rawset(name(), libTable);
	}

	@Override
	public void install(Lib lib) {
		lib.preInstall(context, env);
		Table t = lib.toTable(context);
		if (t != null) {
			String name = lib.name();
			env.rawset(name, t);
			loaded.rawset(name, t);
		}
		lib.postInstall(context, env, t);
	}

	@Override
	public LuaFunction _require() {
		return require;
	}

	@Override
	public String _config() {
		return null;  // TODO
	}

	@Override
	public String _cpath() {
		return null;  // TODO
	}

	@Override
	public Table _loaded() {
		return loaded;
	}

	@Override
	public LuaFunction _loadlib() {
		return _loadlib;
	}

	@Override
	public String _path() {
		return null;  // TODO
	}

	@Override
	public Table _preload() {
		return preload;
	}

	@Override
	public Table _searchers() {
		Object o = libTable.rawget("searchers");
		return o instanceof Table ? (Table) o : null;
	}

	@Override
	public LuaFunction _searchpath() {
		return _searchpath;
	}

	private static class Require_SuspendedState {<commit_msg>Setting package.path at module construction time.<commit_after>/*
 * Copyright 2016 <NAME>
 *
 * 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.
 */

package net.sandius.rembulan.lib.impl;

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.TableFactory;
import net.sandius.rembulan.env.RuntimeEnvironment;
import net.sandius.rembulan.env.RuntimeEnvironments;
import net.sandius.rembulan.impl.UnimplementedFunction;
import net.sandius.rembulan.lib.Lib;
import net.sandius.rembulan.lib.LoaderProvider;
import net.sandius.rembulan.lib.ModuleLib;
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;

public class DefaultModuleLib extends ModuleLib {

	private final StateContext context;
	private final Table env;

	private final Table libTable;
	private final Table loaded;
	private final Table preload;

	private final LuaFunction require;

	private final LuaFunction _loadlib;
	private final LuaFunction _searchpath;

	/**
	 * Constructs a new instance of the default module library.
	 *
	 * @param context  state context to use by the library, must not be {@code null}
	 * @param runtimeEnvironment  runtime environment passed to instantiated libraries, must not be {@code null}
	 * @param env  the global table passed to the instantiated libraries, must not be {@code null}
	 * @param classLoader  class loader used for instantiating libraries, must not be {@code null}
	 */
	public DefaultModuleLib(StateContext context, RuntimeEnvironment runtimeEnvironment, Table env, ClassLoader classLoader, ChunkLoader chunkLoader) {
		this.context = Objects.requireNonNull(context);
		this.env = Objects.requireNonNull(env);
		Objects.requireNonNull(runtimeEnvironment);
		Objects.requireNonNull(classLoader);

		this.libTable = context.newTable();
		this.loaded = context.newTable();
		this.preload = context.newTable();
		Table searchers = context.newTable();

		this._searchpath = new SearchPath(runtimeEnvironment.fileSystem());

		libTable.rawset("loaded", loaded);
		libTable.rawset("preload", preload);
		libTable.rawset("searchers", searchers);
		libTable.rawset("searchpath", _searchpath);

		{
			String envPath = runtimeEnvironment.getEnv("LUA_PATH_5_3");
			if (envPath == null) {
				envPath = runtimeEnvironment.getEnv("LUA_PATH");
			}

			libTable.rawset("path", getPath(envPath, defaultPath(runtimeEnvironment.fileSystem())));
		}

		// initialise searchers
		long idx = 1;
		searchers.rawset(idx++, new PreloadSearcher(preload));
		if (chunkLoader != null) {
			searchers.rawset(idx++, new ChunkLoadPathSearcher(runtimeEnvironment.fileSystem(), libTable, chunkLoader, env));
		}
		searchers.rawset(idx++, new LoaderProviderServiceLoaderSearcher(runtimeEnvironment, env, classLoader));

		this.require = new Require();

		this._loadlib = new UnimplementedFunction("package.loadlib");
	}

	/**
	 * Constructs a new instance of the default module library.
	 *
	 * <b>Deprecated:</b> breaks sandboxing, and does not provide chunk loading.
	 * Use {@link DefaultModuleLib#DefaultModuleLib(StateContext, RuntimeEnvironment, Table, ClassLoader, ChunkLoader)}
	 * instead.
	 *
	 * @param context  state context, must not be {@code null}
	 * @param env  the global table, must not be {@code null}
	 */
	@Deprecated
	public DefaultModuleLib(StateContext context, Table env) {
		this(context, RuntimeEnvironments.system(), env, ClassLoader.getSystemClassLoader(), null);
	}

	@Override
	public Table toTable(TableFactory tableFactory) {
		return libTable;
	}

	@Override
	public void postInstall(StateContext context, Table env, Table libTable) {
		loaded.rawset("_G", env);
		loaded.rawset(name(), libTable);
	}

	@Override
	public void install(Lib lib) {
		lib.preInstall(context, env);
		Table t = lib.toTable(context);
		if (t != null) {
			String name = lib.name();
			env.rawset(name, t);
			loaded.rawset(name, t);
		}
		lib.postInstall(context, env, t);
	}

	@Override
	public LuaFunction _require() {
		return require;
	}

	@Override
	public String _config() {
		return null;  // TODO
	}

	@Override
	public String _cpath() {
		return null;  // TODO
	}

	@Override
	public Table _loaded() {
		return loaded;
	}

	@Override
	public LuaFunction _loadlib() {
		return _loadlib;
	}

	@Override
	public String _path() {
		return null;  // TODO
	}

	@Override
	public Table _preload() {
		return preload;
	}

	@Override
	public Table _searchers() {
		Object o = libTable.rawget("searchers");
		return o instanceof Table ? (Table) o : null;
	}

	@Override
	public LuaFunction _searchpath() {
		return _searchpath;
	}

	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;
		}
	}

	private static class Require_SuspendedState {
{'fraction_non_alphanumeric': 0.10499625904065175, 'fraction_numerical': 0.0023277080389059773, 'mean_word_length': 4.76978417266187, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4673492', 'n_tokens_mistral': 3874, 'n_tokens_neox': 3658, 'n_words': 996}