Commit f2af5ebb authored by Megax's avatar Megax
Browse files

* KopiLua integralva lett a magba nem nem mukodik valamiert normalisan.

parent 153cecd9
No preview for this file type
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{E8DDBC21-EF74-4ABA-9C49-BFC702BE25D8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Lua</RootNamespace>
<AssemblyName>KopiLua</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;LUA_CORE;_WIN32;LUA_COMPAT_VARARG;LUA_COMPAT_MOD;LUA_COMPAT_GFIND;CATCH_EXCEPTIONS</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;LUA_CORE;_WIN32;LUA_COMPAT_VARARG;LUA_COMPAT_MOD;LUA_COMPAT_GFIND;CATCH_EXCEPTIONS</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo_KopiLua.cs" />
<Compile Include="lapi.cs" />
<Compile Include="lauxlib.cs" />
<Compile Include="lbaselib.cs" />
<Compile Include="lcode.cs" />
<Compile Include="ldblib.cs" />
<Compile Include="ldebug.cs" />
<Compile Include="ldo.cs" />
<Compile Include="ldump.cs" />
<Compile Include="lfunc.cs" />
<Compile Include="lgc.cs" />
<Compile Include="linit.cs" />
<Compile Include="liolib.cs" />
<Compile Include="llex.cs" />
<Compile Include="llimits.cs" />
<Compile Include="lmathlib.cs" />
<Compile Include="lmem.cs" />
<Compile Include="loadlib.cs" />
<Compile Include="lobject.cs" />
<Compile Include="lopcodes.cs" />
<Compile Include="loslib.cs" />
<Compile Include="lparser.cs" />
<Compile Include="lstate.cs" />
<Compile Include="lstring.cs" />
<Compile Include="lstrlib.cs" />
<Compile Include="ltable.cs" />
<Compile Include="ltablib.cs" />
<Compile Include="ltm.cs" />
<Compile Include="lua.cs" />
<Compile Include="luaconf.cs" />
<Compile Include="lualib.cs" />
<Compile Include="lundump.cs" />
<Compile Include="lvm.cs" />
<Compile Include="lzio.cs" />
<Compile Include="print.cs" />
<Compile Include="printf\Tools.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>Клиентский профиль .NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Установщик Windows 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KopiLua")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KopiLua")]
[assembly: AssemblyCopyright("Copyright © 2009 Mark Feldman")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1a9cd761-692f-40db-8566-c0217e5d3e0a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
This diff is collapsed.
This diff is collapsed.
/*
** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $
** Basic library
** See Copyright Notice in lua.h
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace KopiLua
{
using lua_Number = System.Double;
public partial class Lua
{
/*
** If your system does not support `stdout', you can just remove this function.
** If you need, you can define your own `print' function, following this
** model but changing `fputs' to put the strings at a proper place
** (a console window or a log file, for instance).
*/
private static int luaB_print (lua_State L) {
int n = lua_gettop(L); /* number of arguments */
int i;
lua_getglobal(L, "tostring");
for (i=1; i<=n; i++) {
CharPtr s;
lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1);
s = lua_tostring(L, -1); /* get result */
if (s == null)
return luaL_error(L, LUA_QL("tostring") + " must return a string to " +
LUA_QL("print"));
if (i > 1) fputs("\t", stdout);
fputs(s, stdout);
lua_pop(L, 1); /* pop result */
}
Console.Write("\n", stdout);
return 0;
}
private static int luaB_tonumber (lua_State L) {
int base_ = luaL_optint(L, 2, 10);
if (base_ == 10) { /* standard conversion */
luaL_checkany(L, 1);
if (lua_isnumber(L, 1) != 0) {
lua_pushnumber(L, lua_tonumber(L, 1));
return 1;
}
}
else {
CharPtr s1 = luaL_checkstring(L, 1);
CharPtr s2;
ulong n;
luaL_argcheck(L, 2 <= base_ && base_ <= 36, 2, "base out of range");
n = strtoul(s1, out s2, base_);
if (s1 != s2) { /* at least one valid digit? */
while (isspace((byte)(s2[0]))) s2 = s2.next(); /* skip trailing spaces */
if (s2[0] == '\0') { /* no invalid trailing characters? */
lua_pushnumber(L, (lua_Number)n);
return 1;
}
}
}
lua_pushnil(L); /* else not a number */
return 1;
}
private static int luaB_error (lua_State L) {
int level = luaL_optint(L, 2, 1);
lua_settop(L, 1);
if ((lua_isstring(L, 1)!=0) && (level > 0)) { /* add extra information? */
luaL_where(L, level);
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
return lua_error(L);
}
private static int luaB_getmetatable (lua_State L) {
luaL_checkany(L, 1);
if (lua_getmetatable(L, 1)==0) {
lua_pushnil(L);
return 1; /* no metatable */
}
luaL_getmetafield(L, 1, "__metatable");
return 1; /* returns either __metatable field (if present) or metatable */
}
private static int luaB_setmetatable (lua_State L) {
int t = lua_type(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
if (luaL_getmetafield(L, 1, "__metatable") != 0)
luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1;
}
private static void getfunc (lua_State L, int opt) {
if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
else {
lua_Debug ar = new lua_Debug();
int level = (opt != 0) ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1);
luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
if (lua_getstack(L, level, ar) == 0)
luaL_argerror(L, 1, "invalid level");
lua_getinfo(L, "f", ar);
if (lua_isnil(L, -1))
luaL_error(L, "no function environment for tail call at level %d",
level);
}
}
private static int luaB_getfenv (lua_State L) {
getfunc(L, 1);
if (lua_iscfunction(L, -1)) /* is a C function? */
lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */
else
lua_getfenv(L, -1);
return 1;
}
private static int luaB_setfenv (lua_State L) {
luaL_checktype(L, 2, LUA_TTABLE);
getfunc(L, 0);
lua_pushvalue(L, 2);
if ((lua_isnumber(L, 1)!=0) && (lua_tonumber(L, 1) == 0)) {
/* change environment of current thread */
lua_pushthread(L);
lua_insert(L, -2);
lua_setfenv(L, -2);
return 0;
}
else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
luaL_error(L,
LUA_QL("setfenv") + " cannot change environment of given object");
return 1;
}
private static int luaB_rawequal (lua_State L) {
luaL_checkany(L, 1);
luaL_checkany(L, 2);
lua_pushboolean(L, lua_rawequal(L, 1, 2));
return 1;
}
private static int luaB_rawget (lua_State L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_rawget(L, 1);
return 1;
}
private static int luaB_rawset (lua_State L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
luaL_checkany(L, 3);
lua_settop(L, 3);
lua_rawset(L, 1);
return 1;
}
private static int luaB_gcinfo (lua_State L) {
lua_pushinteger(L, lua_getgccount(L));
return 1;
}
public static readonly CharPtr[] opts = {"stop", "restart", "collect",
"count", "step", "setpause", "setstepmul", null};
public readonly static int[] optsnum = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL};
private static int luaB_collectgarbage (lua_State L) {
int o = luaL_checkoption(L, 1, "collect", opts);
int ex = luaL_optint(L, 2, 0);
int res = lua_gc(L, optsnum[o], ex);
switch (optsnum[o]) {
case LUA_GCCOUNT: {
int b = lua_gc(L, LUA_GCCOUNTB, 0);
lua_pushnumber(L, res + ((lua_Number)b/1024));
return 1;
}
case LUA_GCSTEP: {
lua_pushboolean(L, res);
return 1;
}
default: {
lua_pushnumber(L, res);
return 1;
}
}
}
private static int luaB_type (lua_State L) {
luaL_checkany(L, 1);
lua_pushstring(L, luaL_typename(L, 1));
return 1;
}
private static int luaB_next (lua_State L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
if (lua_next(L, 1) != 0)
return 2;
else {
lua_pushnil(L);
return 1;
}
}
private static int luaB_pairs (lua_State L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
lua_pushvalue(L, 1); /* state, */
lua_pushnil(L); /* and initial value */
return 3;
}
private static int ipairsaux (lua_State L) {
int i = luaL_checkint(L, 2);
luaL_checktype(L, 1, LUA_TTABLE);
i++; /* next value */
lua_pushinteger(L, i);
lua_rawgeti(L, 1, i);
return (lua_isnil(L, -1)) ? 0 : 2;
}
private static int luaB_ipairs (lua_State L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
lua_pushvalue(L, 1); /* state, */
lua_pushinteger(L, 0); /* and initial value */
return 3;
}
private static int load_aux (lua_State L, int status) {
if (status == 0) /* OK? */
return 1;
else {
lua_pushnil(L);
lua_insert(L, -2); /* put before error message */
return 2; /* return nil plus error message */
}
}
private static int luaB_loadstring (lua_State L) {
uint l;
CharPtr s = luaL_checklstring(L, 1, out l);
CharPtr chunkname = luaL_optstring(L, 2, s);
return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
}
private static int luaB_loadfile (lua_State L) {
CharPtr fname = luaL_optstring(L, 1, null);
return load_aux(L, luaL_loadfile(L, fname));
}
/*
** Reader for generic `load' function: `lua_load' uses the
** stack for internal stuff, so the reader cannot change the
** stack top. Instead, it keeps its resulting string in a
** reserved slot inside the stack.
*/
private static CharPtr generic_reader (lua_State L, object ud, out uint size) {
//(void)ud; /* to avoid warnings */
luaL_checkstack(L, 2, "too many nested functions");
lua_pushvalue(L, 1); /* get function */
lua_call(L, 0, 1); /* call it */
if (lua_isnil(L, -1)) {
size = 0;
return null;
}
else if (lua_isstring(L, -1) != 0)
{
lua_replace(L, 3); /* save string in a reserved stack slot */
return lua_tolstring(L, 3, out size);
}
else
{
size = 0;
luaL_error(L, "reader function must return a string");
}
return null; /* to avoid warnings */
}
private static int luaB_load (lua_State L) {
int status;
CharPtr cname = luaL_optstring(L, 2, "=(load)");
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, 3); /* function, eventual name, plus one reserved slot */
status = lua_load(L, generic_reader, null, cname);
return load_aux(L, status);
}
private static int luaB_dofile (lua_State L) {
CharPtr fname = luaL_optstring(L, 1, null);
int n = lua_gettop(L);
if (luaL_loadfile(L, fname) != 0) lua_error(L);
lua_call(L, 0, LUA_MULTRET);
return lua_gettop(L) - n;
}
private static int luaB_assert (lua_State L) {
luaL_checkany(L, 1);
if (lua_toboolean(L, 1)==0)
return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
return lua_gettop(L);
}
private static int luaB_unpack (lua_State L) {
int i, e, n;
luaL_checktype(L, 1, LUA_TTABLE);
i = luaL_optint(L, 2, 1);
e = luaL_opt_integer(L, luaL_checkint, 3, luaL_getn(L, 1));
if (i > e) return 0; /* empty range */
n = e - i + 1; /* number of elements */
if (n <= 0 || (lua_checkstack(L, n)==0)) /* n <= 0 means arith. overflow */
return luaL_error(L, "too many results to unpack");
lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */
while (i++ < e) /* push arg[i + 1...e] */
lua_rawgeti(L, 1, i);
return n;
}
private static int luaB_select (lua_State L) {
int n = lua_gettop(L);
if (lua_type(L, 1) == LUA_TSTRING && lua_tostring(L, 1)[0] == '#') {
lua_pushinteger(L, n-1);
return 1;
}
else {
int i = luaL_checkint(L, 1);
if (i < 0) i = n + i;
else if (i > n) i = n;
luaL_argcheck(L, 1 <= i, 1, "index out of range");
return n - i;
}
}
private static int luaB_pcall (lua_State L) {
int status;
luaL_checkany(L, 1);
status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
lua_pushboolean(L, (status == 0) ? 1 : 0);
lua_insert(L, 1);
return lua_gettop(L); /* return status + all results */
}
private static int luaB_xpcall (lua_State L) {
int status;
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_insert(L, 1); /* put error function under function to be called */
status = lua_pcall(L, 0, LUA_MULTRET, 1);
lua_pushboolean(L, (status == 0) ? 1 : 0);
lua_replace(L, 1);
return lua_gettop(L); /* return status + all results */
}
private static int luaB_tostring (lua_State L) {
luaL_checkany(L, 1);
if (luaL_callmeta(L, 1, "__tostring") != 0) /* is there a metafield? */
return 1; /* use its value */
switch (lua_type(L, 1)) {
case LUA_TNUMBER:
lua_pushstring(L, lua_tostring(L, 1));
break;
case LUA_TSTRING:
lua_pushvalue(L, 1);
break;
case LUA_TBOOLEAN:
lua_pushstring(L, (lua_toboolean(L, 1) != 0 ? "true" : "false"));
break;
case LUA_TNIL:
lua_pushliteral(L, "nil");
break;
default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
break;
}
return 1;
}
private static int luaB_newproxy (lua_State L) {
lua_settop(L, 1);
lua_newuserdata(L, 0); /* create proxy */
if (lua_toboolean(L, 1) == 0)
return 1; /* no metatable */
else if (lua_isboolean(L, 1)) {
lua_newtable(L); /* create a new metatable `m' ... */
lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
lua_pushboolean(L, 1);
lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
}
else {
int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
if (lua_getmetatable(L, 1) != 0) {
lua_rawget(L, lua_upvalueindex(1));
validproxy = lua_toboolean(L, -1);
lua_pop(L, 1); /* remove value */
}
luaL_argcheck(L, validproxy!=0, 1, "boolean or proxy expected");
lua_getmetatable(L, 1); /* metatable is valid; get it */
}
lua_setmetatable(L, 2);
return 1;
}
private readonly static luaL_Reg[] base_funcs = {
new luaL_Reg("assert", luaB_assert),
new luaL_Reg("collectgarbage", luaB_collectgarbage),
new luaL_Reg("dofile", luaB_dofile),
new luaL_Reg("error", luaB_error),
new luaL_Reg("gcinfo", luaB_gcinfo),
new luaL_Reg("getfenv", luaB_getfenv),
new luaL_Reg("getmetatable", luaB_getmetatable),
new luaL_Reg("loadfile", luaB_loadfile),
new luaL_Reg("load", luaB_load),
new luaL_Reg("loadstring", luaB_loadstring),
new luaL_Reg("next", luaB_next),
new luaL_Reg("pcall", luaB_pcall),
new luaL_Reg("print", luaB_print),
new luaL_Reg("rawequal", luaB_rawequal),
new luaL_Reg("rawget", luaB_rawget),
new luaL_Reg("rawset", luaB_rawset),
new luaL_Reg("select", luaB_select),
new luaL_Reg("setfenv", luaB_setfenv),
new luaL_Reg("setmetatable", luaB_setmetatable),
new luaL_Reg("tonumber", luaB_tonumber),
new luaL_Reg("tostring", luaB_tostring),
new luaL_Reg("type", luaB_type),
new luaL_Reg("unpack", luaB_unpack),
new luaL_Reg("xpcall", luaB_xpcall),
new luaL_Reg(null, null)
};
/*
** {======================================================
** Coroutine library
** =======================================================
*/
public const int CO_RUN = 0; /* running */
public const int CO_SUS = 1; /* suspended */
public const int CO_NOR = 2; /* 'normal' (it resumed another coroutine) */
public const int CO_DEAD = 3;
private static readonly string[] statnames =
{"running", "suspended", "normal", "dead"};
private static int costatus (lua_State L, lua_State co) {
if (L == co) return CO_RUN;
switch (lua_status(co)) {
case LUA_YIELD:
return CO_SUS;
case 0: {
lua_Debug ar = new lua_Debug();
if (lua_getstack(co, 0, ar) > 0) /* does it have frames? */
return CO_NOR; /* it is running */
else if (lua_gettop(co) == 0)
return CO_DEAD;
else
return CO_SUS; /* initial state */
}
default: /* some error occured */
return CO_DEAD;
}
}
private static int luaB_costatus (lua_State L) {
lua_State co = lua_tothread(L, 1);
luaL_argcheck(L, co!=null, 1, "coroutine expected");
lua_pushstring(L, statnames[costatus(L, co)]);
return 1;
}
private static int auxresume (lua_State L, lua_State co, int narg) {
int status = costatus(L, co);
if (lua_checkstack(co, narg)==0)
luaL_error(L, "too many arguments to resume");
if (status != CO_SUS) {
lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]);
return -1; /* error flag */
}
lua_xmove(L, co, narg);
lua_setlevel(L, co);
status = lua_resume(co, narg);
if (status == 0 || status == LUA_YIELD) {
int nres = lua_gettop(co);
if (lua_checkstack(L, nres + 1)==0)
luaL_error(L, "too many results to resume");
lua_xmove(co, L, nres); /* move yielded values */
return nres;
}
else {
lua_xmove(co, L, 1); /* move error message */
return -1; /* error flag */
}
}
private static int luaB_coresume (lua_State L) {
lua_State co = lua_tothread(L, 1);
int r;
luaL_argcheck(L, co!=null, 1, "coroutine expected");
r = auxresume(L, co, lua_gettop(L) - 1);
if (r < 0) {
lua_pushboolean(L, 0);
lua_insert(L, -2);
return 2; /* return false + error message */
}
else {
lua_pushboolean(L, 1);
lua_insert(L, -(r + 1));
return r + 1; /* return true + `resume' returns */
}
}
private static int luaB_auxwrap (lua_State L) {
lua_State co = lua_tothread(L, lua_upvalueindex(1));
int r = auxresume(L, co, lua_gettop(L));
if (r < 0) {
if (lua_isstring(L, -1) != 0) { /* error object is a string? */
luaL_where(L, 1); /* add extra info */
lua_insert(L, -2);
lua_concat(L, 2);
}
lua_error(L); /* propagate error */
}
return r;
}
private static int luaB_cocreate (lua_State L) {
lua_State NL = lua_newthread(L);
luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
"Lua function expected");
lua_pushvalue(L, 1); /* move function to top */
lua_xmove(L, NL, 1); /* move function from L to NL */
return 1;
}
private static int luaB_cowrap (lua_State L) {
luaB_cocreate(L);
lua_pushcclosure(L, luaB_auxwrap, 1);
return 1;
}
private static int luaB_yield (lua_State L) {
return lua_yield(L, lua_gettop(L));
}
private static int luaB_corunning (lua_State L) {
if (lua_pushthread(L) != 0)
lua_pushnil(L); /* main thread is not a coroutine */
return 1;
}
private readonly static luaL_Reg[] co_funcs = {
new luaL_Reg("create", luaB_cocreate),
new luaL_Reg("resume", luaB_coresume),
new luaL_Reg("running", luaB_corunning),
new luaL_Reg("status", luaB_costatus),
new luaL_Reg("wrap", luaB_cowrap),
new luaL_Reg("yield", luaB_yield),
new luaL_Reg(null, null)
};
/* }====================================================== */
private static void auxopen (lua_State L, CharPtr name,
lua_CFunction f, lua_CFunction u) {
lua_pushcfunction(L, u);
lua_pushcclosure(L, f, 1);
lua_setfield(L, -2, name);
}
private static void base_open (lua_State L) {
/* set global _G */
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_setglobal(L, "_G");
/* open lib into global table */
luaL_register(L, "_G", base_funcs);
lua_pushliteral(L, LUA_VERSION);
lua_setglobal(L, "_VERSION"); /* set global _VERSION */
/* `ipairs' and `pairs' need auxliliary functions as upvalues */
auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
auxopen(L, "pairs", luaB_pairs, luaB_next);
/* `newproxy' needs a weaktable as upvalue */
lua_createtable(L, 0, 1); /* new table `w' */
lua_pushvalue(L, -1); /* `w' will be its own metatable */
lua_setmetatable(L, -2);
lua_pushliteral(L, "kv");
lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
lua_pushcclosure(L, luaB_newproxy, 1);
lua_setglobal(L, "newproxy"); /* set global `newproxy' */
}
public static int luaopen_base (lua_State L) {
base_open(L);
luaL_register(L, LUA_COLIBNAME, co_funcs);
return 2;
}
}
}
This diff is collapsed.
/*
** $Id: ldblib.c,v 1.104.1.3 2008/01/21 13:11:21 roberto Exp $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace KopiLua
{
public partial class Lua
{
private static int db_getregistry (lua_State L) {
lua_pushvalue(L, LUA_REGISTRYINDEX);
return 1;
}
private static int db_getmetatable (lua_State L) {
luaL_checkany(L, 1);
if (lua_getmetatable(L, 1) == 0) {
lua_pushnil(L); /* no metatable */
}
return 1;
}
private static int db_setmetatable (lua_State L) {
int t = lua_type(L, 2);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
lua_settop(L, 2);
lua_pushboolean(L, lua_setmetatable(L, 1));
return 1;
}
private static int db_getfenv (lua_State L) {
lua_getfenv(L, 1);
return 1;
}
private static int db_setfenv (lua_State L) {
luaL_checktype(L, 2, LUA_TTABLE);
lua_settop(L, 2);
if (lua_setfenv(L, 1) == 0)
luaL_error(L, LUA_QL("setfenv") +
" cannot change environment of given object");
return 1;
}
private static void settabss (lua_State L, CharPtr i, CharPtr v) {
lua_pushstring(L, v);
lua_setfield(L, -2, i);
}
private static void settabsi (lua_State L, CharPtr i, int v) {
lua_pushinteger(L, v);
lua_setfield(L, -2, i);
}
private static lua_State getthread (lua_State L, out int arg) {
if (lua_isthread(L, 1)) {
arg = 1;
return lua_tothread(L, 1);
}
else {
arg = 0;
return L;
}
}
private static void treatstackoption (lua_State L, lua_State L1, CharPtr fname) {
if (L == L1) {
lua_pushvalue(L, -2);
lua_remove(L, -3);
}
else
lua_xmove(L1, L, 1);
lua_setfield(L, -2, fname);
}
private static int db_getinfo (lua_State L) {
lua_Debug ar = new lua_Debug();
int arg;
lua_State L1 = getthread(L, out arg);
CharPtr options = luaL_optstring(L, arg+2, "flnSu");
if (lua_isnumber(L, arg+1) != 0) {
if (lua_getstack(L1, (int)lua_tointeger(L, arg+1), ar)==0) {
lua_pushnil(L); /* level out of range */
return 1;
}
}
else if (lua_isfunction(L, arg+1)) {
lua_pushfstring(L, ">%s", options);
options = lua_tostring(L, -1);
lua_pushvalue(L, arg+1);
lua_xmove(L, L1, 1);
}
else
return luaL_argerror(L, arg+1, "function or level expected");
if (lua_getinfo(L1, options, ar)==0)
return luaL_argerror(L, arg+2, "invalid option");
lua_createtable(L, 0, 2);
if (strchr(options, 'S') != null) {
settabss(L, "source", ar.source);
settabss(L, "short_src", ar.short_src);
settabsi(L, "linedefined", ar.linedefined);
settabsi(L, "lastlinedefined", ar.lastlinedefined);
settabss(L, "what", ar.what);
}
if (strchr(options, 'l') != null)
settabsi(L, "currentline", ar.currentline);
if (strchr(options, 'u') != null)
settabsi(L, "nups", ar.nups);
if (strchr(options, 'n') != null) {
settabss(L, "name", ar.name);
settabss(L, "namewhat", ar.namewhat);
}
if (strchr(options, 'L') != null)
treatstackoption(L, L1, "activelines");
if (strchr(options, 'f') != null)
treatstackoption(L, L1, "func");
return 1; /* return table */
}
private static int db_getlocal (lua_State L) {
int arg;
lua_State L1 = getthread(L, out arg);
lua_Debug ar = new lua_Debug();
CharPtr name;
if (lua_getstack(L1, luaL_checkint(L, arg+1), ar)==0) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
name = lua_getlocal(L1, ar, luaL_checkint(L, arg+2));
if (name != null) {
lua_xmove(L1, L, 1);
lua_pushstring(L, name);
lua_pushvalue(L, -2);
return 2;
}
else {
lua_pushnil(L);
return 1;
}
}
private static int db_setlocal (lua_State L) {
int arg;
lua_State L1 = getthread(L, out arg);
lua_Debug ar = new lua_Debug();
if (lua_getstack(L1, luaL_checkint(L, arg+1), ar)==0) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
luaL_checkany(L, arg+3);
lua_settop(L, arg+3);
lua_xmove(L, L1, 1);
lua_pushstring(L, lua_setlocal(L1, ar, luaL_checkint(L, arg+2)));
return 1;
}
private static int auxupvalue (lua_State L, int get) {
CharPtr name;
int n = luaL_checkint(L, 2);
luaL_checktype(L, 1, LUA_TFUNCTION);
if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */
name = (get!=0) ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
if (name == null) return 0;
lua_pushstring(L, name);
lua_insert(L, -(get+1));
return get + 1;
}
private static int db_getupvalue (lua_State L) {
return auxupvalue(L, 1);
}
private static int db_setupvalue (lua_State L) {
luaL_checkany(L, 3);
return auxupvalue(L, 0);
}
private const string KEY_HOOK = "h";
private static readonly string[] hooknames =
{"call", "return", "line", "count", "tail return"};
private static void hookf (lua_State L, lua_Debug ar) {
lua_pushlightuserdata(L, KEY_HOOK);
lua_rawget(L, LUA_REGISTRYINDEX);
lua_pushlightuserdata(L, L);
lua_rawget(L, -2);
if (lua_isfunction(L, -1)) {
lua_pushstring(L, hooknames[(int)ar.event_]);
if (ar.currentline >= 0)
lua_pushinteger(L, ar.currentline);
else lua_pushnil(L);
lua_assert(lua_getinfo(L, "lS", ar));
lua_call(L, 2, 0);
}
}
private static int makemask (CharPtr smask, int count) {
int mask = 0;
if (strchr(smask, 'c') != null) mask |= LUA_MASKCALL;
if (strchr(smask, 'r') != null) mask |= LUA_MASKRET;
if (strchr(smask, 'l') != null) mask |= LUA_MASKLINE;
if (count > 0) mask |= LUA_MASKCOUNT;
return mask;
}
private static CharPtr unmakemask (int mask, CharPtr smask) {
int i = 0;
if ((mask & LUA_MASKCALL) != 0) smask[i++] = 'c';
if ((mask & LUA_MASKRET) != 0) smask[i++] = 'r';
if ((mask & LUA_MASKLINE) != 0) smask[i++] = 'l';
smask[i] = '\0';
return smask;
}
private static void gethooktable (lua_State L) {
lua_pushlightuserdata(L, KEY_HOOK);
lua_rawget(L, LUA_REGISTRYINDEX);
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_createtable(L, 0, 1);
lua_pushlightuserdata(L, KEY_HOOK);
lua_pushvalue(L, -2);
lua_rawset(L, LUA_REGISTRYINDEX);
}
}
private static int db_sethook (lua_State L) {
int arg, mask, count;
lua_Hook func;
lua_State L1 = getthread(L, out arg);
if (lua_isnoneornil(L, arg+1)) {
lua_settop(L, arg+1);
func = null; mask = 0; count = 0; /* turn off hooks */
}
else {
CharPtr smask = luaL_checkstring(L, arg+2);
luaL_checktype(L, arg+1, LUA_TFUNCTION);
count = luaL_optint(L, arg+3, 0);
func = hookf; mask = makemask(smask, count);
}
gethooktable(L);
lua_pushlightuserdata(L, L1);
lua_pushvalue(L, arg+1);
lua_rawset(L, -3); /* set new hook */
lua_pop(L, 1); /* remove hook table */
lua_sethook(L1, func, mask, count); /* set hooks */
return 0;
}
private static int db_gethook (lua_State L) {
int arg;
lua_State L1 = getthread(L, out arg);
CharPtr buff = new char[5];
int mask = lua_gethookmask(L1);
lua_Hook hook = lua_gethook(L1);
if (hook != null && hook != hookf) /* external hook? */
lua_pushliteral(L, "external hook");
else {
gethooktable(L);
lua_pushlightuserdata(L, L1);
lua_rawget(L, -2); /* get hook */
lua_remove(L, -2); /* remove hook table */
}
lua_pushstring(L, unmakemask(mask, buff));
lua_pushinteger(L, lua_gethookcount(L1));
return 3;
}
private static int db_debug (lua_State L) {
for (;;) {
CharPtr buffer = new char[250];
fputs("lua_debug> ", stderr);
if (fgets(buffer, stdin) == null ||
strcmp(buffer, "cont\n") == 0)
return 0;
if (luaL_loadbuffer(L, buffer, (uint)strlen(buffer), "=(debug command)")!=0 ||
lua_pcall(L, 0, 0, 0)!=0) {
fputs(lua_tostring(L, -1), stderr);
fputs("\n", stderr);
}
lua_settop(L, 0); /* remove eventual returns */
}
}
public const int LEVELS1 = 12; /* size of the first part of the stack */
public const int LEVELS2 = 10; /* size of the second part of the stack */
private static int db_errorfb (lua_State L) {
int level;
bool firstpart = true; /* still before eventual `...' */
int arg;
lua_State L1 = getthread(L, out arg);
lua_Debug ar = new lua_Debug();
if (lua_isnumber(L, arg+2) != 0) {
level = (int)lua_tointeger(L, arg+2);
lua_pop(L, 1);
}
else
level = (L == L1) ? 1 : 0; /* level 0 may be this own function */
if (lua_gettop(L) == arg)
lua_pushliteral(L, "");
else if (lua_isstring(L, arg+1)==0) return 1; /* message is not a string */
else lua_pushliteral(L, "\n");
lua_pushliteral(L, "stack traceback:");
while (lua_getstack(L1, level++, ar) != 0) {
if (level > LEVELS1 && firstpart) {
/* no more than `LEVELS2' more levels? */
if (lua_getstack(L1, level+LEVELS2, ar)==0)
level--; /* keep going */
else {
lua_pushliteral(L, "\n\t..."); /* too many levels */
while (lua_getstack(L1, level+LEVELS2, ar) != 0) /* find last levels */
level++;
}
firstpart = false;
continue;
}
lua_pushliteral(L, "\n\t");
lua_getinfo(L1, "Snl", ar);
lua_pushfstring(L, "%s:", ar.short_src);
if (ar.currentline > 0)
lua_pushfstring(L, "%d:", ar.currentline);
if (ar.namewhat != '\0') /* is there a name? */
lua_pushfstring(L, " in function " + LUA_QS, ar.name);
else {
if (ar.what == 'm') /* main? */
lua_pushfstring(L, " in main chunk");
else if (ar.what == 'C' || ar.what == 't')
lua_pushliteral(L, " ?"); /* C function or tail call */
else
lua_pushfstring(L, " in function <%s:%d>",
ar.short_src, ar.linedefined);
}
lua_concat(L, lua_gettop(L) - arg);
}
lua_concat(L, lua_gettop(L) - arg);
return 1;
}
private readonly static luaL_Reg[] dblib = {
new luaL_Reg("debug", db_debug),
new luaL_Reg("getfenv", db_getfenv),
new luaL_Reg("gethook", db_gethook),
new luaL_Reg("getinfo", db_getinfo),
new luaL_Reg("getlocal", db_getlocal),
new luaL_Reg("getregistry", db_getregistry),
new luaL_Reg("getmetatable", db_getmetatable),
new luaL_Reg("getupvalue", db_getupvalue),
new luaL_Reg("setfenv", db_setfenv),
new luaL_Reg("sethook", db_sethook),
new luaL_Reg("setlocal", db_setlocal),
new luaL_Reg("setmetatable", db_setmetatable),
new luaL_Reg("setupvalue", db_setupvalue),
new luaL_Reg("traceback", db_errorfb),
new luaL_Reg(null, null)
};
public static int luaopen_debug (lua_State L) {
luaL_register(L, LUA_DBLIBNAME, dblib);
return 1;
}
}
}
/*
** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $
** Debug Interface
** See Copyright Notice in lua.h
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace KopiLua
{
using TValue = Lua.lua_TValue;
using StkId = Lua.lua_TValue;
using Instruction = System.UInt32;
public partial class Lua
{
public static int pcRel(InstructionPtr pc, Proto p)
{
Debug.Assert(pc.codes == p.code);
return pc.pc - 1;
}
public static int getline(Proto f, int pc) { return (f.lineinfo != null) ? f.lineinfo[pc] : 0; }
public static void resethookcount(lua_State L) { L.hookcount = L.basehookcount; }
private static int currentpc (lua_State L, CallInfo ci) {
if (!isLua(ci)) return -1; /* function is not a Lua function? */
if (ci == L.ci)
ci.savedpc = InstructionPtr.Assign(L.savedpc);
return pcRel(ci.savedpc, ci_func(ci).l.p);
}
private static int currentline (lua_State L, CallInfo ci) {
int pc = currentpc(L, ci);
if (pc < 0)
return -1; /* only active lua functions have current-line information */
else
return getline(ci_func(ci).l.p, pc);
}
/*
** this function can be called asynchronous (e.g. during a signal)
*/
public static int lua_sethook (lua_State L, lua_Hook func, int mask, int count) {
if (func == null || mask == 0) { /* turn off hooks? */
mask = 0;
func = null;
}
L.hook = func;
L.basehookcount = count;
resethookcount(L);
L.hookmask = cast_byte(mask);
return 1;
}
public static lua_Hook lua_gethook (lua_State L) {
return L.hook;
}
public static int lua_gethookmask (lua_State L) {
return L.hookmask;
}
public static int lua_gethookcount (lua_State L) {
return L.basehookcount;
}
public static int lua_getstack (lua_State L, int level, lua_Debug ar) {
int status;
CallInfo ci;
lua_lock(L);
for (ci = L.ci; level > 0 && ci > L.base_ci[0]; CallInfo.dec(ref ci)) {
level--;
if (f_isLua(ci)) /* Lua function? */
level -= ci.tailcalls; /* skip lost tail calls */
}
if (level == 0 && ci > L.base_ci[0]) { /* level found? */
status = 1;
ar.i_ci = ci - L.base_ci[0];
}
else if (level < 0) { /* level is of a lost tail call? */
status = 1;
ar.i_ci = 0;
}
else status = 0; /* no such level */
lua_unlock(L);
return status;
}
private static Proto getluaproto (CallInfo ci) {
return (isLua(ci) ? ci_func(ci).l.p : null);
}
private static CharPtr findlocal (lua_State L, CallInfo ci, int n) {
CharPtr name;
Proto fp = getluaproto(ci);
if ((fp!=null) && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != null)
return name; /* is a local variable in a Lua function */
else {
StkId limit = (ci == L.ci) ? L.top : (ci+1).func;
if (limit - ci.base_ >= n && n > 0) /* is 'n' inside 'ci' stack? */
return "(*temporary)";
else
return null;
}
}
public static CharPtr lua_getlocal (lua_State L, lua_Debug ar, int n) {
CallInfo ci = L.base_ci[ar.i_ci];
CharPtr name = findlocal(L, ci, n);
lua_lock(L);
if (name != null)
luaA_pushobject(L, ci.base_[n - 1]);
lua_unlock(L);
return name;
}
public static CharPtr lua_setlocal (lua_State L, lua_Debug ar, int n) {
CallInfo ci = L.base_ci[ar.i_ci];
CharPtr name = findlocal(L, ci, n);
lua_lock(L);
if (name != null)
setobjs2s(L, ci.base_[n - 1], L.top-1);
StkId.dec(ref L.top); /* pop value */
lua_unlock(L);
return name;
}
private static void funcinfo (lua_Debug ar, Closure cl) {
if (cl.c.isC != 0) {
ar.source = "=[C]";
ar.linedefined = -1;
ar.lastlinedefined = -1;
ar.what = "C";
}
else {
ar.source = getstr(cl.l.p.source);
ar.linedefined = cl.l.p.linedefined;
ar.lastlinedefined = cl.l.p.lastlinedefined;
ar.what = (ar.linedefined == 0) ? "main" : "Lua";
}
luaO_chunkid(ar.short_src, ar.source, LUA_IDSIZE);
}
private static void info_tailcall (lua_Debug ar) {
ar.name = ar.namewhat = "";
ar.what = "tail";
ar.lastlinedefined = ar.linedefined = ar.currentline = -1;
ar.source = "=(tail call)";
luaO_chunkid(ar.short_src, ar.source, LUA_IDSIZE);
ar.nups = 0;
}
private static void collectvalidlines (lua_State L, Closure f) {
if (f == null || (f.c.isC!=0)) {
setnilvalue(L.top);
}
else {
Table t = luaH_new(L, 0, 0);
int[] lineinfo = f.l.p.lineinfo;
int i;
for (i=0; i<f.l.p.sizelineinfo; i++)
setbvalue(luaH_setnum(L, t, lineinfo[i]), 1);
sethvalue(L, L.top, t);
}
incr_top(L);
}
private static int auxgetinfo (lua_State L, CharPtr what, lua_Debug ar,
Closure f, CallInfo ci) {
int status = 1;
if (f == null) {
info_tailcall(ar);
return status;
}
for (; what[0] != 0; what = what.next()) {
switch (what[0]) {
case 'S': {
funcinfo(ar, f);
break;
}
case 'l': {
ar.currentline = (ci != null) ? currentline(L, ci) : -1;
break;
}
case 'u': {
ar.nups = f.c.nupvalues;
break;
}
case 'n': {
ar.namewhat = (ci!=null) ? getfuncname(L, ci, ref ar.name) : null;
if (ar.namewhat == null) {
ar.namewhat = ""; /* not found */
ar.name = null;
}
break;
}
case 'L':
case 'f': /* handled by lua_getinfo */
break;
default: status = 0; break;/* invalid option */
}
}
return status;
}
public static int lua_getinfo (lua_State L, CharPtr what, lua_Debug ar) {
int status;
Closure f = null;
CallInfo ci = null;
lua_lock(L);
if (what == '>') {
StkId func = L.top - 1;
luai_apicheck(L, ttisfunction(func));
what = what.next(); /* skip the '>' */
f = clvalue(func);
StkId.dec(ref L.top); /* pop function */
}
else if (ar.i_ci != 0) { /* no tail call? */
ci = L.base_ci[ar.i_ci];
lua_assert(ttisfunction(ci.func));
f = clvalue(ci.func);
}
status = auxgetinfo(L, what, ar, f, ci);
if (strchr(what, 'f') != null) {
if (f == null) setnilvalue(L.top);
else setclvalue(L, L.top, f);
incr_top(L);
}
if (strchr(what, 'L') != null)
collectvalidlines(L, f);
lua_unlock(L);
return status;
}
/*
** {======================================================
** Symbolic Execution and code checker
** =======================================================
*/
private static int checkjump(Proto pt, int pc) { if (!(0 <= pc && pc < pt.sizecode)) return 0; return 1; }
private static int checkreg(Proto pt, int reg) { if (!((reg) < (pt).maxstacksize)) return 0; return 1; }
private static int precheck (Proto pt) {
if (!(pt.maxstacksize <= MAXSTACK)) return 0;
if (!(pt.numparams+(pt.is_vararg & VARARG_HASARG) <= pt.maxstacksize)) return 0;
if (!(((pt.is_vararg & VARARG_NEEDSARG)==0) ||
((pt.is_vararg & VARARG_HASARG)!=0))) return 0;
if (!(pt.sizeupvalues <= pt.nups)) return 0;
if (!(pt.sizelineinfo == pt.sizecode || pt.sizelineinfo == 0)) return 0;
if (!(pt.sizecode > 0 && GET_OPCODE(pt.code[pt.sizecode - 1]) == OpCode.OP_RETURN)) return 0;
return 1;
}
public static int checkopenop(Proto pt, int pc) { return luaG_checkopenop(pt.code[pc + 1]); }
public static int luaG_checkopenop (Instruction i) {
switch (GET_OPCODE(i)) {
case OpCode.OP_CALL:
case OpCode.OP_TAILCALL:
case OpCode.OP_RETURN:
case OpCode.OP_SETLIST: {
if (!(GETARG_B(i) == 0)) return 0;
return 1;
}
default: return 0; /* invalid instruction after an open call */
}
}
private static int checkArgMode (Proto pt, int r, OpArgMask mode) {
switch (mode) {
case OpArgMask.OpArgN: if (r!=0) return 0; break;
case OpArgMask.OpArgU: break;
case OpArgMask.OpArgR: checkreg(pt, r); break;
case OpArgMask.OpArgK:
if (!( (ISK(r) != 0) ? INDEXK(r) < pt.sizek : r < pt.maxstacksize)) return 0;
break;
}
return 1;
}
private static Instruction symbexec (Proto pt, int lastpc, int reg) {
int pc;
int last; /* stores position of last instruction that changed `reg' */
int dest;
last = pt.sizecode-1; /* points to final return (a `neutral' instruction) */
if (precheck(pt)==0) return 0;
for (pc = 0; pc < lastpc; pc++) {
Instruction i = pt.code[pc];
OpCode op = GET_OPCODE(i);
int a = GETARG_A(i);
int b = 0;
int c = 0;
if (!((int)op < NUM_OPCODES)) return 0;
checkreg(pt, a);
switch (getOpMode(op)) {
case OpMode.iABC: {
b = GETARG_B(i);
c = GETARG_C(i);
if (checkArgMode(pt, b, getBMode(op))==0) return 0;
if (checkArgMode(pt, c, getCMode(op))==0) return 0;
break;
}
case OpMode.iABx: {
b = GETARG_Bx(i);
if (getBMode(op) == OpArgMask.OpArgK) if (!(b < pt.sizek)) return 0;
break;
}
case OpMode.iAsBx: {
b = GETARG_sBx(i);
if (getBMode(op) == OpArgMask.OpArgR) {
dest = pc+1+b;
if (!((0 <= dest && dest < pt.sizecode))) return 0;
if (dest > 0) {
int j;
/* check that it does not jump to a setlist count; this
is tricky, because the count from a previous setlist may
have the same value of an invalid setlist; so, we must
go all the way back to the first of them (if any) */
for (j = 0; j < dest; j++) {
Instruction d = pt.code[dest-1-j];
if (!(GET_OPCODE(d) == OpCode.OP_SETLIST && GETARG_C(d) == 0)) break;
}
/* if 'j' is even, previous value is not a setlist (even if
it looks like one) */
if ((j&1)!=0) return 0;
}
}
break;
}
}
if (testAMode(op) != 0) {
if (a == reg) last = pc; /* change register `a' */
}
if (testTMode(op) != 0) {
if (!(pc+2 < pt.sizecode)) return 0; /* check skip */
if (!(GET_OPCODE(pt.code[pc + 1]) == OpCode.OP_JMP)) return 0;
}
switch (op) {
case OpCode.OP_LOADBOOL: {
if (c == 1) { /* does it jump? */
if (!(pc+2 < pt.sizecode)) return 0; /* check its jump */
if (!(GET_OPCODE(pt.code[pc + 1]) != OpCode.OP_SETLIST ||
GETARG_C(pt.code[pc + 1]) != 0)) return 0;
}
break;
}
case OpCode.OP_LOADNIL: {
if (a <= reg && reg <= b)
last = pc; /* set registers from `a' to `b' */
break;
}
case OpCode.OP_GETUPVAL:
case OpCode.OP_SETUPVAL: {
if (!(b < pt.nups)) return 0;
break;
}
case OpCode.OP_GETGLOBAL:
case OpCode.OP_SETGLOBAL: {
if (!(ttisstring(pt.k[b]))) return 0;
break;
}
case OpCode.OP_SELF: {
checkreg(pt, a+1);
if (reg == a+1) last = pc;
break;
}
case OpCode.OP_CONCAT: {
if (!(b < c)) return 0; /* at least two operands */
break;
}
case OpCode.OP_TFORLOOP: {
if (!(c >= 1)) return 0; /* at least one result (control variable) */
checkreg(pt, a+2+c); /* space for results */
if (reg >= a+2) last = pc; /* affect all regs above its base */
break;
}
case OpCode.OP_FORLOOP:
case OpCode.OP_FORPREP:
checkreg(pt, a+3);
/* go through ...no, on second thoughts don't, because this is C# */
dest = pc + 1 + b;
/* not full check and jump is forward and do not skip `lastpc'? */
if (reg != NO_REG && pc < dest && dest <= lastpc)
pc += b; /* do the jump */
break;
case OpCode.OP_JMP: {
dest = pc+1+b;
/* not full check and jump is forward and do not skip `lastpc'? */
if (reg != NO_REG && pc < dest && dest <= lastpc)
pc += b; /* do the jump */
break;
}
case OpCode.OP_CALL:
case OpCode.OP_TAILCALL: {
if (b != 0) {
checkreg(pt, a+b-1);
}
c--; /* c = num. returns */
if (c == LUA_MULTRET) {
if (checkopenop(pt, pc)==0) return 0;
}
else if (c != 0)
checkreg(pt, a+c-1);
if (reg >= a) last = pc; /* affect all registers above base */
break;
}
case OpCode.OP_RETURN: {
b--; /* b = num. returns */
if (b > 0) checkreg(pt, a+b-1);
break;
}
case OpCode.OP_SETLIST: {
if (b > 0) checkreg(pt, a + b);
if (c == 0) {
pc++;
if (!(pc < pt.sizecode - 1)) return 0;
}
break;
}
case OpCode.OP_CLOSURE: {
int nup, j;
if (!(b < pt.sizep)) return 0;
nup = pt.p[b].nups;
if (!(pc + nup < pt.sizecode)) return 0;
for (j = 1; j <= nup; j++) {
OpCode op1 = GET_OPCODE(pt.code[pc + j]);
if (!(op1 == OpCode.OP_GETUPVAL || op1 == OpCode.OP_MOVE)) return 0;
}
if (reg != NO_REG) /* tracing? */
pc += nup; /* do not 'execute' these pseudo-instructions */
break;
}
case OpCode.OP_VARARG: {
if (!( (pt.is_vararg & VARARG_ISVARARG)!=0 &&
(pt.is_vararg & VARARG_NEEDSARG)==0 )) return 0;
b--;
if (b == LUA_MULTRET) if (checkopenop(pt, pc)==0) return 0;
checkreg(pt, a+b-1);
break;
}
default:
break;
}
}
return pt.code[last];
}
//#undef check
//#undef checkjump
//#undef checkreg
/* }====================================================== */
public static int luaG_checkcode (Proto pt) {
return (symbexec(pt, pt.sizecode, NO_REG) != 0) ? 1 : 0;
}
private static CharPtr kname (Proto p, int c) {
if (ISK(c)!=0 && ttisstring(p.k[INDEXK(c)]))
return svalue(p.k[INDEXK(c)]);
else
return "?";
}
private static CharPtr getobjname (lua_State L, CallInfo ci, int stackpos,
ref CharPtr name) {
if (isLua(ci)) { /* a Lua function? */
Proto p = ci_func(ci).l.p;
int pc = currentpc(L, ci);
Instruction i;
name = luaF_getlocalname(p, stackpos+1, pc);
if (name!=null) /* is a local? */
return "local";
i = symbexec(p, pc, stackpos); /* try symbolic execution */
lua_assert(pc != -1);
switch (GET_OPCODE(i)) {
case OpCode.OP_GETGLOBAL: {
int g = GETARG_Bx(i); /* global index */
lua_assert(ttisstring(p.k[g]));
name = svalue(p.k[g]);
return "global";
}
case OpCode.OP_MOVE: {
int a = GETARG_A(i);
int b = GETARG_B(i); /* move from `b' to `a' */
if (b < a)
return getobjname(L, ci, b, ref name); /* get name for `b' */
break;
}
case OpCode.OP_GETTABLE: {
int k = GETARG_C(i); /* key index */
name = kname(p, k);
return "field";
}
case OpCode.OP_GETUPVAL: {
int u = GETARG_B(i); /* upvalue index */
name = (p.upvalues!=null) ? getstr(p.upvalues[u]) : "?";
return "upvalue";
}
case OpCode.OP_SELF: {
int k = GETARG_C(i); /* key index */
name = kname(p, k);
return "method";
}
default: break;
}
}
return null; /* no useful name found */
}
private static CharPtr getfuncname (lua_State L, CallInfo ci, ref CharPtr name) {
Instruction i;
if ((isLua(ci) && ci.tailcalls > 0) || !isLua(ci - 1))
return null; /* calling function is not Lua (or is unknown) */
CallInfo.dec(ref ci); /* calling function */
i = ci_func(ci).l.p.code[currentpc(L, ci)];
if (GET_OPCODE(i) == OpCode.OP_CALL || GET_OPCODE(i) == OpCode.OP_TAILCALL ||
GET_OPCODE(i) == OpCode.OP_TFORLOOP)
return getobjname(L, ci, GETARG_A(i), ref name);
else
return null; /* no useful name can be found */
}
/* only ANSI way to check whether a pointer points to an array */
private static int isinstack (CallInfo ci, TValue o) {
StkId p;
for (p = ci.base_; p < ci.top; StkId.inc(ref p))
if (o == p) return 1;
return 0;
}
public static void luaG_typeerror (lua_State L, TValue o, CharPtr op) {
CharPtr name = null;
CharPtr t = luaT_typenames[ttype(o)];
CharPtr kind = (isinstack(L.ci, o)) != 0 ?
getobjname(L, L.ci, cast_int(o - L.base_), ref name) :
null;
if (kind != null)
luaG_runerror(L, "attempt to %s %s " + LUA_QS + " (a %s value)",
op, kind, name, t);
else
luaG_runerror(L, "attempt to %s a %s value", op, t);
}
public static void luaG_concaterror (lua_State L, StkId p1, StkId p2) {
if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
lua_assert(!ttisstring(p1) && !ttisnumber(p1));
luaG_typeerror(L, p1, "concatenate");
}
public static void luaG_aritherror (lua_State L, TValue p1, TValue p2) {
TValue temp = new TValue();
if (luaV_tonumber(p1, temp) == null)
p2 = p1; /* first operand is wrong */
luaG_typeerror(L, p2, "perform arithmetic on");
}
public static int luaG_ordererror (lua_State L, TValue p1, TValue p2) {
CharPtr t1 = luaT_typenames[ttype(p1)];
CharPtr t2 = luaT_typenames[ttype(p2)];
if (t1[2] == t2[2])
luaG_runerror(L, "attempt to compare two %s values", t1);
else
luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
return 0;
}
private static void addinfo (lua_State L, CharPtr msg) {
CallInfo ci = L.ci;
if (isLua(ci)) { /* is Lua code? */
CharPtr buff = new CharPtr(new char[LUA_IDSIZE]); /* add file:line information */
int line = currentline(L, ci);
luaO_chunkid(buff, getstr(getluaproto(ci).source), LUA_IDSIZE);
luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
}
}
public static void luaG_errormsg (lua_State L) {
if (L.errfunc != 0) { /* is there an error handling function? */
StkId errfunc = restorestack(L, L.errfunc);
if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
setobjs2s(L, L.top, L.top - 1); /* move argument */
setobjs2s(L, L.top - 1, errfunc); /* push function */
incr_top(L);
luaD_call(L, L.top - 2, 1); /* call it */
}
luaD_throw(L, LUA_ERRRUN);
}
public static void luaG_runerror(lua_State L, CharPtr fmt, params object[] argp)
{
addinfo(L, luaO_pushvfstring(L, fmt, argp));
luaG_errormsg(L);
}
}
}
This diff is collapsed.
/*
** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
** save precompiled Lua chunks
** See Copyright Notice in lua.h
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace KopiLua
{
using lua_Number = System.Double;
using TValue = Lua.lua_TValue;
public partial class Lua
{
public class DumpState {
public lua_State L;
public lua_Writer writer;
public object data;
public int strip;
public int status;
};
public static void DumpMem(object b, DumpState D)
{
#if XBOX || SILVERLIGHT
// todo: implement this - mjf
Debug.Assert(false);
#else
int size = Marshal.SizeOf(b);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(b, ptr, false);
byte[] bytes = new byte[size];
Marshal.Copy(ptr, bytes, 0, size);
char[] ch = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
ch[i] = (char)bytes[i];
CharPtr str = ch;
DumpBlock(str, (uint)str.chars.Length, D);
Marshal.Release(ptr);
#endif
}
public static void DumpMem(object b, int n, DumpState D)
{
Array array = b as Array;
Debug.Assert(array.Length == n);
for (int i = 0; i < n; i++)
DumpMem(array.GetValue(i), D);
}
public static void DumpVar(object x, DumpState D)
{
DumpMem(x, D);
}
private static void DumpBlock(CharPtr b, uint size, DumpState D)
{
if (D.status==0)
{
lua_unlock(D.L);
D.status=D.writer(D.L,b,size,D.data);
lua_lock(D.L);
}
}
private static void DumpChar(int y, DumpState D)
{
char x=(char)y;
DumpVar(x,D);
}
private static void DumpInt(int x, DumpState D)
{
DumpVar(x,D);
}
private static void DumpNumber(lua_Number x, DumpState D)
{
DumpVar(x,D);
}
static void DumpVector(object b, int n, DumpState D)
{
DumpInt(n,D);
DumpMem(b, n, D);
}
private static void DumpString(TString s, DumpState D)
{
if (s==null || getstr(s)==null)
{
uint size=0;
DumpVar(size,D);
}
else
{
uint size=s.tsv.len+1; /* include trailing '\0' */
DumpVar(size,D);
DumpBlock(getstr(s),size,D);
}
}
private static void DumpCode(Proto f,DumpState D)
{
DumpVector(f.code, f.sizecode, D);
}
private static void DumpConstants(Proto f, DumpState D)
{
int i,n=f.sizek;
DumpInt(n,D);
for (i=0; i<n; i++)
{
/*const*/ TValue o=f.k[i];
DumpChar(ttype(o),D);
switch (ttype(o))
{
case LUA_TNIL:
break;
case LUA_TBOOLEAN:
DumpChar(bvalue(o),D);
break;
case LUA_TNUMBER:
DumpNumber(nvalue(o),D);
break;
case LUA_TSTRING:
DumpString(rawtsvalue(o),D);
break;
default:
lua_assert(0); /* cannot happen */
break;
}
}
n=f.sizep;
DumpInt(n,D);
for (i=0; i<n; i++) DumpFunction(f.p[i],f.source,D);
}
private static void DumpDebug(Proto f, DumpState D)
{
int i,n;
n= (D.strip != 0) ? 0 : f.sizelineinfo;
DumpVector(f.lineinfo, n, D);
n= (D.strip != 0) ? 0 : f.sizelocvars;
DumpInt(n,D);
for (i=0; i<n; i++)
{
DumpString(f.locvars[i].varname,D);
DumpInt(f.locvars[i].startpc,D);
DumpInt(f.locvars[i].endpc,D);
}
n= (D.strip != 0) ? 0 : f.sizeupvalues;
DumpInt(n,D);
for (i=0; i<n; i++) DumpString(f.upvalues[i],D);
}
private static void DumpFunction(Proto f, TString p, DumpState D)
{
DumpString( ((f.source==p) || (D.strip!=0)) ? null : f.source, D);
DumpInt(f.linedefined,D);
DumpInt(f.lastlinedefined,D);
DumpChar(f.nups,D);
DumpChar(f.numparams,D);
DumpChar(f.is_vararg,D);
DumpChar(f.maxstacksize,D);
DumpCode(f,D);
DumpConstants(f,D);
DumpDebug(f,D);
}
private static void DumpHeader(DumpState D)
{
CharPtr h = new char[LUAC_HEADERSIZE];
luaU_header(h);
DumpBlock(h,LUAC_HEADERSIZE,D);
}
/*
** dump Lua function as precompiled chunk
*/
public static int luaU_dump (lua_State L, Proto f, lua_Writer w, object data, int strip)
{
DumpState D = new DumpState();
D.L=L;
D.writer=w;
D.data=data;
D.strip=strip;
D.status=0;
DumpHeader(D);
DumpFunction(f,null,D);
return D.status;
}
}
}
This diff is collapsed.
This diff is collapsed.
/*
** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $
** Initialization of libraries for lua.c
** See Copyright Notice in lua.h
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace KopiLua
{
public partial class Lua
{
private readonly static luaL_Reg[] lualibs = {
new luaL_Reg("", luaopen_base),
new luaL_Reg(LUA_LOADLIBNAME, luaopen_package),
new luaL_Reg(LUA_TABLIBNAME, luaopen_table),
new luaL_Reg(LUA_IOLIBNAME, luaopen_io),
new luaL_Reg(LUA_OSLIBNAME, luaopen_os),
new luaL_Reg(LUA_STRLIBNAME, luaopen_string),
new luaL_Reg(LUA_MATHLIBNAME, luaopen_math),
new luaL_Reg(LUA_DBLIBNAME, luaopen_debug),
new luaL_Reg(null, null)
};
public static void luaL_openlibs (lua_State L) {
for (int i=0; i<lualibs.Length-1; i++)
{
luaL_Reg lib = lualibs[i];
lua_pushcfunction(L, lib.func);
lua_pushstring(L, lib.name);
lua_call(L, 1, 0);
}
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment