lua: updated from 5.3 work3 to 5.3.0

* improved the overall kernel Lua patch; fixed coercion
* updated lua/syslog
* updated luapmf and luasystm Makefiles
This commit is contained in:
lneto 2015-02-02 14:03:05 +00:00
parent 0090b13dae
commit 730082507e
69 changed files with 3968 additions and 2965 deletions

View File

@ -36,7 +36,7 @@ RM= rm -f
# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
# Convenience platforms targets.
PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
# What to install.
TO_BIN= lua luac

View File

@ -1,5 +1,5 @@
This is Lua 5.3.0 (work3), released on 19 Jul 2014.
This is Lua 5.3.0, released on 06 Jan 2015.
For installation instructions, license details, and
further information about Lua, see doc/readme.html.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -20,10 +20,6 @@ ul {
Lua 5.3 Reference Manual
</H1>
<P>
<IMG SRC="alert.png" ALIGN="absbottom">
<EM>All details may change in the final version.</EM>
<P>
The reference manual is the official definition of the Lua language.
For a complete introduction to Lua programming, see the book
@ -37,7 +33,7 @@ For a complete introduction to Lua programming, see the book
<A HREF="#index">index</A>
<HR>
<SMALL>
Copyright &copy; 2011&ndash;2014 Lua.org, PUC-Rio.
Copyright &copy; 2015 Lua.org, PUC-Rio.
Freely available under the terms of the
<A HREF="http://www.lua.org/license.html">Lua license</A>.
</SMALL>
@ -117,6 +113,7 @@ Freely available under the terms of the
<LI><A HREF="manual.html#6.4">6.4 &ndash; String Manipulation</A>
<UL>
<LI><A HREF="manual.html#6.4.1">6.4.1 &ndash; Patterns</A>
<LI><A HREF="manual.html#6.4.2">6.4.2 &ndash; Format Strings for Pack and Unpack</A>
</UL>
<LI><A HREF="manual.html#6.5">6.5 &ndash; UTF-8 Support</A>
<LI><A HREF="manual.html#6.6">6.6 &ndash; Table Manipulation</A>
@ -144,10 +141,10 @@ Freely available under the terms of the
<TD>
<H3><A NAME="functions">Lua functions</A></H3>
<P>
<A HREF="manual.html#6.1">basic</A><BR>
<A HREF="manual.html#pdf-_G">_G</A><BR>
<A HREF="manual.html#pdf-_VERSION">_VERSION</A><BR>
<P>
<A HREF="manual.html#pdf-assert">assert</A><BR>
<A HREF="manual.html#pdf-collectgarbage">collectgarbage</A><BR>
<A HREF="manual.html#pdf-dofile">dofile</A><BR>
@ -173,6 +170,7 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-xpcall">xpcall</A><BR>
<P>
<A HREF="manual.html#6.2">coroutine</A><BR>
<A HREF="manual.html#pdf-coroutine.create">coroutine.create</A><BR>
<A HREF="manual.html#pdf-coroutine.isyieldable">coroutine.isyieldable</A><BR>
<A HREF="manual.html#pdf-coroutine.resume">coroutine.resume</A><BR>
@ -182,8 +180,8 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-coroutine.yield">coroutine.yield</A><BR>
<P>
<A HREF="manual.html#6.10">debug</A><BR>
<A HREF="manual.html#pdf-debug.debug">debug.debug</A><BR>
<A HREF="manual.html#pdf-debug.Csize">debug.Csize</A><BR>
<A HREF="manual.html#pdf-debug.gethook">debug.gethook</A><BR>
<A HREF="manual.html#pdf-debug.getinfo">debug.getinfo</A><BR>
<A HREF="manual.html#pdf-debug.getlocal">debug.getlocal</A><BR>
@ -201,15 +199,7 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-debug.upvaluejoin">debug.upvaluejoin</A><BR>
<P>
<A HREF="manual.html#pdf-file:close">file:close</A><BR>
<A HREF="manual.html#pdf-file:flush">file:flush</A><BR>
<A HREF="manual.html#pdf-file:lines">file:lines</A><BR>
<A HREF="manual.html#pdf-file:read">file:read</A><BR>
<A HREF="manual.html#pdf-file:seek">file:seek</A><BR>
<A HREF="manual.html#pdf-file:setvbuf">file:setvbuf</A><BR>
<A HREF="manual.html#pdf-file:write">file:write</A><BR>
<P>
<A HREF="manual.html#6.8">io</A><BR>
<A HREF="manual.html#pdf-io.close">io.close</A><BR>
<A HREF="manual.html#pdf-io.flush">io.flush</A><BR>
<A HREF="manual.html#pdf-io.input">io.input</A><BR>
@ -225,11 +215,19 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-io.type">io.type</A><BR>
<A HREF="manual.html#pdf-io.write">io.write</A><BR>
<A HREF="manual.html#pdf-file:close">file:close</A><BR>
<A HREF="manual.html#pdf-file:flush">file:flush</A><BR>
<A HREF="manual.html#pdf-file:lines">file:lines</A><BR>
<A HREF="manual.html#pdf-file:read">file:read</A><BR>
<A HREF="manual.html#pdf-file:seek">file:seek</A><BR>
<A HREF="manual.html#pdf-file:setvbuf">file:setvbuf</A><BR>
<A HREF="manual.html#pdf-file:write">file:write</A><BR>
</TD>
<TD>
<H3>&nbsp;</H3>
<P>
<A HREF="manual.html#pdf-math">math</A><BR>
<A HREF="manual.html#6.7">math</A><BR>
<A HREF="manual.html#pdf-math.abs">math.abs</A><BR>
<A HREF="manual.html#pdf-math.acos">math.acos</A><BR>
<A HREF="manual.html#pdf-math.asin">math.asin</A><BR>
@ -237,10 +235,10 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-math.ceil">math.ceil</A><BR>
<A HREF="manual.html#pdf-math.cos">math.cos</A><BR>
<A HREF="manual.html#pdf-math.deg">math.deg</A><BR>
<A HREF="manual.html#pdf-math.exp">math.exp</A><BR>
<A HREF="manual.html#pdf-math.floor">math.floor</A><BR>
<A HREF="manual.html#pdf-math.fmod">math.fmod</A><BR>
<A HREF="manual.html#pdf-math.huge">math.huge</A><BR>
<A HREF="manual.html#pdf-math.ifloor">math.ifloor</A><BR>
<A HREF="manual.html#pdf-math.log">math.log</A><BR>
<A HREF="manual.html#pdf-math.max">math.max</A><BR>
<A HREF="manual.html#pdf-math.maxinteger">math.maxinteger</A><BR>
@ -254,9 +252,12 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-math.sin">math.sin</A><BR>
<A HREF="manual.html#pdf-math.sqrt">math.sqrt</A><BR>
<A HREF="manual.html#pdf-math.tan">math.tan</A><BR>
<A HREF="manual.html#pdf-math.tointeger">math.tointeger</A><BR>
<A HREF="manual.html#pdf-math.type">math.type</A><BR>
<A HREF="manual.html#pdf-math.ult">math.ult</A><BR>
<P>
<A HREF="manual.html#6.9">os</A><BR>
<A HREF="manual.html#pdf-os.clock">os.clock</A><BR>
<A HREF="manual.html#pdf-os.date">os.date</A><BR>
<A HREF="manual.html#pdf-os.difftime">os.difftime</A><BR>
@ -270,6 +271,7 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-os.tmpname">os.tmpname</A><BR>
<P>
<A HREF="manual.html#6.3">package</A><BR>
<A HREF="manual.html#pdf-package.config">package.config</A><BR>
<A HREF="manual.html#pdf-package.cpath">package.cpath</A><BR>
<A HREF="manual.html#pdf-package.loaded">package.loaded</A><BR>
@ -280,11 +282,10 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-package.searchpath">package.searchpath</A><BR>
<P>
<A HREF="manual.html#6.4">string</A><BR>
<A HREF="manual.html#pdf-string.byte">string.byte</A><BR>
<A HREF="manual.html#pdf-string.char">string.char</A><BR>
<A HREF="manual.html#pdf-string.dump">string.dump</A><BR>
<A HREF="manual.html#pdf-string.dumpfloat">string.dumpfloat</A><BR>
<A HREF="manual.html#pdf-string.dumpint">string.dumpint</A><BR>
<A HREF="manual.html#pdf-string.find">string.find</A><BR>
<A HREF="manual.html#pdf-string.format">string.format</A><BR>
<A HREF="manual.html#pdf-string.gmatch">string.gmatch</A><BR>
@ -292,38 +293,51 @@ Freely available under the terms of the
<A HREF="manual.html#pdf-string.len">string.len</A><BR>
<A HREF="manual.html#pdf-string.lower">string.lower</A><BR>
<A HREF="manual.html#pdf-string.match">string.match</A><BR>
<A HREF="manual.html#pdf-string.pack">string.pack</A><BR>
<A HREF="manual.html#pdf-string.packsize">string.packsize</A><BR>
<A HREF="manual.html#pdf-string.rep">string.rep</A><BR>
<A HREF="manual.html#pdf-string.reverse">string.reverse</A><BR>
<A HREF="manual.html#pdf-string.sub">string.sub</A><BR>
<A HREF="manual.html#pdf-string.undumpfloat">string.undumpfloat</A><BR>
<A HREF="manual.html#pdf-string.undumpint">string.undumpint</A><BR>
<A HREF="manual.html#pdf-string.unpack">string.unpack</A><BR>
<A HREF="manual.html#pdf-string.upper">string.upper</A><BR>
<P>
<A HREF="manual.html#6.6">table</A><BR>
<A HREF="manual.html#pdf-table.concat">table.concat</A><BR>
<A HREF="manual.html#pdf-table.insert">table.insert</A><BR>
<A HREF="manual.html#pdf-table.move">table.move</A><BR>
<A HREF="manual.html#pdf-table.pack">table.pack</A><BR>
<A HREF="manual.html#pdf-table.remove">table.remove</A><BR>
<A HREF="manual.html#pdf-table.sort">table.sort</A><BR>
<A HREF="manual.html#pdf-table.unpack">table.unpack</A><BR>
<P>
<A HREF="manual.html#6.5">utf8</A><BR>
<A HREF="manual.html#pdf-utf8.char">utf8.char</A><BR>
<A HREF="manual.html#pdf-utf8.charpatt">utf8.charpatt</A><BR>
<A HREF="manual.html#pdf-utf8.charpattern">utf8.charpattern</A><BR>
<A HREF="manual.html#pdf-utf8.codepoint">utf8.codepoint</A><BR>
<A HREF="manual.html#pdf-utf8.codes">utf8.codes</A><BR>
<A HREF="manual.html#pdf-utf8.len">utf8.len</A><BR>
<A HREF="manual.html#pdf-utf8.offset">utf8.offset</A><BR>
<H3><A NAME="env">environment<BR>variables</A></H3>
<A HREF="manual.html#pdf-LUA_CPATH">LUA_CPATH</A><BR>
<A HREF="manual.html#pdf-LUA_CPATH_5_3">LUA_CPATH_5_3</A><BR>
<A HREF="manual.html#pdf-LUA_INIT">LUA_INIT</A><BR>
<A HREF="manual.html#pdf-LUA_INIT_5_3">LUA_INIT_5_3</A><BR>
<A HREF="manual.html#pdf-LUA_PATH">LUA_PATH</A><BR>
<A HREF="manual.html#pdf-LUA_PATH_5_3">LUA_PATH_5_3</A><BR>
</TD>
<TD>
<H3>C API</H3>
<H3><A NAME="api">C API</A></H3>
<P>
<A HREF="manual.html#lua_Alloc">lua_Alloc</A><BR>
<A HREF="manual.html#lua_CFunction">lua_CFunction</A><BR>
<A HREF="manual.html#lua_Debug">lua_Debug</A><BR>
<A HREF="manual.html#lua_Hook">lua_Hook</A><BR>
<A HREF="manual.html#lua_Integer">lua_Integer</A><BR>
<A HREF="manual.html#lua_KContext">lua_KContext</A><BR>
<A HREF="manual.html#lua_KFunction">lua_KFunction</A><BR>
<A HREF="manual.html#lua_Number">lua_Number</A><BR>
<A HREF="manual.html#lua_Reader">lua_Reader</A><BR>
@ -347,11 +361,13 @@ Freely available under the terms of the
<A HREF="manual.html#lua_error">lua_error</A><BR>
<A HREF="manual.html#lua_gc">lua_gc</A><BR>
<A HREF="manual.html#lua_getallocf">lua_getallocf</A><BR>
<A HREF="manual.html#lua_getextraspace">lua_getextraspace</A><BR>
<A HREF="manual.html#lua_getfield">lua_getfield</A><BR>
<A HREF="manual.html#lua_getglobal">lua_getglobal</A><BR>
<A HREF="manual.html#lua_gethook">lua_gethook</A><BR>
<A HREF="manual.html#lua_gethookcount">lua_gethookcount</A><BR>
<A HREF="manual.html#lua_gethookmask">lua_gethookmask</A><BR>
<A HREF="manual.html#lua_geti">lua_geti</A><BR>
<A HREF="manual.html#lua_getinfo">lua_getinfo</A><BR>
<A HREF="manual.html#lua_getlocal">lua_getlocal</A><BR>
<A HREF="manual.html#lua_getmetatable">lua_getmetatable</A><BR>
@ -382,7 +398,7 @@ Freely available under the terms of the
<A HREF="manual.html#lua_newthread">lua_newthread</A><BR>
<A HREF="manual.html#lua_newuserdata">lua_newuserdata</A><BR>
<A HREF="manual.html#lua_next">lua_next</A><BR>
<A HREF="manual.html#lua_numtointeger">lua_numtointeger</A><BR>
<A HREF="manual.html#lua_numbertointeger">lua_numbertointeger</A><BR>
<A HREF="manual.html#lua_pcall">lua_pcall</A><BR>
<A HREF="manual.html#lua_pcallk">lua_pcallk</A><BR>
<A HREF="manual.html#lua_pop">lua_pop</A><BR>
@ -399,7 +415,6 @@ Freely available under the terms of the
<A HREF="manual.html#lua_pushnumber">lua_pushnumber</A><BR>
<A HREF="manual.html#lua_pushstring">lua_pushstring</A><BR>
<A HREF="manual.html#lua_pushthread">lua_pushthread</A><BR>
<A HREF="manual.html#lua_pushunsigned">lua_pushunsigned</A><BR>
<A HREF="manual.html#lua_pushvalue">lua_pushvalue</A><BR>
<A HREF="manual.html#lua_pushvfstring">lua_pushvfstring</A><BR>
<A HREF="manual.html#lua_rawequal">lua_rawequal</A><BR>
@ -419,6 +434,7 @@ Freely available under the terms of the
<A HREF="manual.html#lua_setfield">lua_setfield</A><BR>
<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
<A HREF="manual.html#lua_sethook">lua_sethook</A><BR>
<A HREF="manual.html#lua_seti">lua_seti</A><BR>
<A HREF="manual.html#lua_setlocal">lua_setlocal</A><BR>
<A HREF="manual.html#lua_setmetatable">lua_setmetatable</A><BR>
<A HREF="manual.html#lua_settable">lua_settable</A><BR>
@ -426,7 +442,7 @@ Freely available under the terms of the
<A HREF="manual.html#lua_setupvalue">lua_setupvalue</A><BR>
<A HREF="manual.html#lua_setuservalue">lua_setuservalue</A><BR>
<A HREF="manual.html#lua_status">lua_status</A><BR>
<A HREF="manual.html#lua_strtonum">lua_strtonum</A><BR>
<A HREF="manual.html#lua_stringtonumber">lua_stringtonumber</A><BR>
<A HREF="manual.html#lua_toboolean">lua_toboolean</A><BR>
<A HREF="manual.html#lua_tocfunction">lua_tocfunction</A><BR>
<A HREF="manual.html#lua_tointeger">lua_tointeger</A><BR>
@ -437,8 +453,6 @@ Freely available under the terms of the
<A HREF="manual.html#lua_topointer">lua_topointer</A><BR>
<A HREF="manual.html#lua_tostring">lua_tostring</A><BR>
<A HREF="manual.html#lua_tothread">lua_tothread</A><BR>
<A HREF="manual.html#lua_tounsigned">lua_tounsigned</A><BR>
<A HREF="manual.html#lua_tounsignedx">lua_tounsignedx</A><BR>
<A HREF="manual.html#lua_touserdata">lua_touserdata</A><BR>
<A HREF="manual.html#lua_type">lua_type</A><BR>
<A HREF="manual.html#lua_typename">lua_typename</A><BR>
@ -452,7 +466,7 @@ Freely available under the terms of the
</TD>
<TD>
<H3>auxiliary library</H3>
<H3><A NAME="auxlib">auxiliary library</A></H3>
<P>
<A HREF="manual.html#luaL_Buffer">luaL_Buffer</A><BR>
<A HREF="manual.html#luaL_Reg">luaL_Reg</A><BR>
@ -470,9 +484,7 @@ Freely available under the terms of the
<A HREF="manual.html#luaL_buffinitsize">luaL_buffinitsize</A><BR>
<A HREF="manual.html#luaL_callmeta">luaL_callmeta</A><BR>
<A HREF="manual.html#luaL_checkany">luaL_checkany</A><BR>
<A HREF="manual.html#luaL_checkint">luaL_checkint</A><BR>
<A HREF="manual.html#luaL_checkinteger">luaL_checkinteger</A><BR>
<A HREF="manual.html#luaL_checklong">luaL_checklong</A><BR>
<A HREF="manual.html#luaL_checklstring">luaL_checklstring</A><BR>
<A HREF="manual.html#luaL_checknumber">luaL_checknumber</A><BR>
<A HREF="manual.html#luaL_checkoption">luaL_checkoption</A><BR>
@ -480,7 +492,6 @@ Freely available under the terms of the
<A HREF="manual.html#luaL_checkstring">luaL_checkstring</A><BR>
<A HREF="manual.html#luaL_checktype">luaL_checktype</A><BR>
<A HREF="manual.html#luaL_checkudata">luaL_checkudata</A><BR>
<A HREF="manual.html#luaL_checkunsigned">luaL_checkunsigned</A><BR>
<A HREF="manual.html#luaL_checkversion">luaL_checkversion</A><BR>
<A HREF="manual.html#luaL_dofile">luaL_dofile</A><BR>
<A HREF="manual.html#luaL_dostring">luaL_dostring</A><BR>
@ -502,13 +513,10 @@ Freely available under the terms of the
<A HREF="manual.html#luaL_newmetatable">luaL_newmetatable</A><BR>
<A HREF="manual.html#luaL_newstate">luaL_newstate</A><BR>
<A HREF="manual.html#luaL_openlibs">luaL_openlibs</A><BR>
<A HREF="manual.html#luaL_optint">luaL_optint</A><BR>
<A HREF="manual.html#luaL_optinteger">luaL_optinteger</A><BR>
<A HREF="manual.html#luaL_optlong">luaL_optlong</A><BR>
<A HREF="manual.html#luaL_optlstring">luaL_optlstring</A><BR>
<A HREF="manual.html#luaL_optnumber">luaL_optnumber</A><BR>
<A HREF="manual.html#luaL_optstring">luaL_optstring</A><BR>
<A HREF="manual.html#luaL_optunsigned">luaL_optunsigned</A><BR>
<A HREF="manual.html#luaL_prepbuffer">luaL_prepbuffer</A><BR>
<A HREF="manual.html#luaL_prepbuffsize">luaL_prepbuffsize</A><BR>
<A HREF="manual.html#luaL_pushresult">luaL_pushresult</A><BR>
@ -524,6 +532,76 @@ Freely available under the terms of the
<A HREF="manual.html#luaL_unref">luaL_unref</A><BR>
<A HREF="manual.html#luaL_where">luaL_where</A><BR>
<H3><A NAME="library">standard library</A></H3>
<P>
<A HREF="manual.html#pdf-luaopen_base">luaopen_base</A><BR>
<A HREF="manual.html#pdf-luaopen_coroutine">luaopen_coroutine</A><BR>
<A HREF="manual.html#pdf-luaopen_debug">luaopen_debug</A><BR>
<A HREF="manual.html#pdf-luaopen_io">luaopen_io</A><BR>
<A HREF="manual.html#pdf-luaopen_math">luaopen_math</A><BR>
<A HREF="manual.html#pdf-luaopen_os">luaopen_os</A><BR>
<A HREF="manual.html#pdf-luaopen_package">luaopen_package</A><BR>
<A HREF="manual.html#pdf-luaopen_string">luaopen_string</A><BR>
<A HREF="manual.html#pdf-luaopen_table">luaopen_table</A><BR>
<A HREF="manual.html#pdf-luaopen_utf8">luaopen_utf8</A><BR>
<H3><A NAME="constants">constants</A></H3>
<A HREF="manual.html#pdf-LUA_ERRERR">LUA_ERRERR</A><BR>
<A HREF="manual.html#pdf-LUA_ERRFILE">LUA_ERRFILE</A><BR>
<A HREF="manual.html#pdf-LUA_ERRGCMM">LUA_ERRGCMM</A><BR>
<A HREF="manual.html#pdf-LUA_ERRMEM">LUA_ERRMEM</A><BR>
<A HREF="manual.html#pdf-LUA_ERRRUN">LUA_ERRRUN</A><BR>
<A HREF="manual.html#pdf-LUA_ERRSYNTAX">LUA_ERRSYNTAX</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKCALL">LUA_HOOKCALL</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKCOUNT">LUA_HOOKCOUNT</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKLINE">LUA_HOOKLINE</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKRET">LUA_HOOKRET</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKTAILCALL">LUA_HOOKTAILCALL</A><BR>
<A HREF="manual.html#pdf-LUA_MASKCALL">LUA_MASKCALL</A><BR>
<A HREF="manual.html#pdf-LUA_MASKCOUNT">LUA_MASKCOUNT</A><BR>
<A HREF="manual.html#pdf-LUA_MASKLINE">LUA_MASKLINE</A><BR>
<A HREF="manual.html#pdf-LUA_MASKRET">LUA_MASKRET</A><BR>
<A HREF="manual.html#pdf-LUA_MAXINTEGER">LUA_MAXINTEGER</A><BR>
<A HREF="manual.html#pdf-LUA_MININTEGER">LUA_MININTEGER</A><BR>
<A HREF="manual.html#pdf-LUA_MINSTACK">LUA_MINSTACK</A><BR>
<A HREF="manual.html#pdf-LUA_MULTRET">LUA_MULTRET</A><BR>
<A HREF="manual.html#pdf-LUA_NOREF">LUA_NOREF</A><BR>
<A HREF="manual.html#pdf-LUA_OK">LUA_OK</A><BR>
<A HREF="manual.html#pdf-LUA_OPADD">LUA_OPADD</A><BR>
<A HREF="manual.html#pdf-LUA_OPBAND">LUA_OPBAND</A><BR>
<A HREF="manual.html#pdf-LUA_OPBNOT">LUA_OPBNOT</A><BR>
<A HREF="manual.html#pdf-LUA_OPBOR">LUA_OPBOR</A><BR>
<A HREF="manual.html#pdf-LUA_OPBXOR">LUA_OPBXOR</A><BR>
<A HREF="manual.html#pdf-LUA_OPDIV">LUA_OPDIV</A><BR>
<A HREF="manual.html#pdf-LUA_OPEQ">LUA_OPEQ</A><BR>
<A HREF="manual.html#pdf-LUA_OPIDIV">LUA_OPIDIV</A><BR>
<A HREF="manual.html#pdf-LUA_OPLE">LUA_OPLE</A><BR>
<A HREF="manual.html#pdf-LUA_OPLT">LUA_OPLT</A><BR>
<A HREF="manual.html#pdf-LUA_OPMOD">LUA_OPMOD</A><BR>
<A HREF="manual.html#pdf-LUA_OPMUL">LUA_OPMUL</A><BR>
<A HREF="manual.html#pdf-LUA_OPPOW">LUA_OPPOW</A><BR>
<A HREF="manual.html#pdf-LUA_OPSHL">LUA_OPSHL</A><BR>
<A HREF="manual.html#pdf-LUA_OPSHR">LUA_OPSHR</A><BR>
<A HREF="manual.html#pdf-LUA_OPSUB">LUA_OPSUB</A><BR>
<A HREF="manual.html#pdf-LUA_OPUNM">LUA_OPUNM</A><BR>
<A HREF="manual.html#pdf-LUA_REFNIL">LUA_REFNIL</A><BR>
<A HREF="manual.html#pdf-LUA_REGISTRYINDEX">LUA_REGISTRYINDEX</A><BR>
<A HREF="manual.html#pdf-LUA_RIDX_GLOBALS">LUA_RIDX_GLOBALS</A><BR>
<A HREF="manual.html#pdf-LUA_RIDX_MAINTHREAD">LUA_RIDX_MAINTHREAD</A><BR>
<A HREF="manual.html#pdf-LUA_TBOOLEAN">LUA_TBOOLEAN</A><BR>
<A HREF="manual.html#pdf-LUA_TFUNCTION">LUA_TFUNCTION</A><BR>
<A HREF="manual.html#pdf-LUA_TLIGHTUSERDATA">LUA_TLIGHTUSERDATA</A><BR>
<A HREF="manual.html#pdf-LUA_TNIL">LUA_TNIL</A><BR>
<A HREF="manual.html#pdf-LUA_TNONE">LUA_TNONE</A><BR>
<A HREF="manual.html#pdf-LUA_TNUMBER">LUA_TNUMBER</A><BR>
<A HREF="manual.html#pdf-LUA_TSTRING">LUA_TSTRING</A><BR>
<A HREF="manual.html#pdf-LUA_TTABLE">LUA_TTABLE</A><BR>
<A HREF="manual.html#pdf-LUA_TTHREAD">LUA_TTHREAD</A><BR>
<A HREF="manual.html#pdf-LUA_TUSERDATA">LUA_TUSERDATA</A><BR>
<A HREF="manual.html#pdf-LUA_USE_APICHECK">LUA_USE_APICHECK</A><BR>
<A HREF="manual.html#pdf-LUA_YIELD">LUA_YIELD</A><BR>
<A HREF="manual.html#pdf-LUAL_BUFFERSIZE">LUAL_BUFFERSIZE</A><BR>
</TD>
</TR>
</TABLE>
@ -531,10 +609,10 @@ Freely available under the terms of the
<HR>
<SMALL CLASS="footer">
Last update:
Thu Jun 19 17:09:46 BRT 2014
Tue Dec 9 21:26:07 BRST 2014
</SMALL>
<!--
Last change: updated for Lua 5.3.0 (work3)
Last change: updated for Lua 5.3.0 (final)
-->
</BODY>

View File

@ -1,7 +1,6 @@
.\" $NetBSD: lua.1,v 1.2 2014/07/19 18:38:33 lneto Exp $
.\" $NetBSD: lua.1,v 1.3 2015/02/02 14:03:05 lneto Exp $
.\"
.\" $Id: lua.1,v 1.2 2014/07/19 18:38:33 lneto Exp $
.TH LUA 1 "$Date: 2014/07/19 18:38:33 $"
.TH LUA 1 "Date: 2014/12/10 15:55:45 "
.SH NAME
lua \- Lua interpreter
.SH SYNOPSIS
@ -52,22 +51,18 @@ In interactive mode,
prompts the user,
reads lines from the standard input,
and executes them as they are read.
If the line contains an expression or list of expressions,
then the line is evaluated and the results are printed.
If a line does not contain a complete statement,
then a secondary prompt is displayed and
lines are read until a complete statement is formed or
a syntax error is found.
If a line starts with
.BR '=' ,
then
.B lua
evaluates and displays
the values of the expressions in the remainder of the line.
.LP
At the very start,
before even handling the command line,
.B lua
checks the contents of the environment variables
.B LUA_INIT_5_2
.B LUA_INIT_5_3
or
.BR LUA_INIT ,
in that order.

View File

@ -53,12 +53,17 @@ a:visited {
a:link:hover, a:visited:hover {
color: #000080 ;
background-color: #D0D0FF ;
border-radius: 4px;
}
a:link:active, a:visited:active {
color: #FF0000 ;
}
h1 a img {
vertical-align: text-bottom ;
}
hr {
border: 0 ;
height: 1px ;
@ -86,11 +91,15 @@ table hr {
input[type=text] {
border: solid #a0a0a0 2px ;
border-radius: 2em ;
-moz-border-radius: 2em ;
background-image: url('images/search.png') ;
background-repeat: no-repeat;
background-repeat: no-repeat ;
background-position: 4px center ;
padding-left: 20px ;
height: 2em ;
}
pre.session {
background-color: #F8F8F8 ;
padding: 1em ;
border-radius: 8px ;
}

File diff suppressed because it is too large Load Diff

View File

@ -31,13 +31,9 @@ tt, kbd, code {
<HR>
<H1>
<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>
Welcome to Lua 5.3 (work3)
Welcome to Lua 5.3.0
</H1>
<P>
<IMG SRC="alert.png" ALIGN="absbottom">
<EM>All details may change in the final version.</EM>
<P>
<A HREF="#about">about</A>
&middot;
@ -114,7 +110,7 @@ Here are the details.
<OL>
<LI>
Open a terminal window and move to
the top-level directory, which is named <TT>lua-5.3.0-work3</TT>.
the top-level directory, which is named <TT>lua-5.3.0</TT>.
The <TT>Makefile</TT> there controls both the build process and the installation process.
<P>
<LI>
@ -122,14 +118,14 @@ The <TT>Makefile</TT> there controls both the build process and the installation
The platforms currently supported are:
<P>
<P CLASS="display">
aix ansi bsd freebsd generic linux macosx mingw posix solaris
aix bsd c89 freebsd generic linux macosx mingw posix solaris
</P>
<P>
If your platform is listed, just do "<KBD>make xxx</KBD>", where xxx
is your platform name.
<P>
If your platform is not listed, try the closest one or posix, generic,
ansi, in this order.
c89, in this order.
<P>
<LI>
The compilation takes only a few moments
@ -255,6 +251,7 @@ compiler:
be linked statically into the host program and its symbols exported for
dynamic linking; <TT>src/Makefile</TT> does this for the Lua interpreter.
For Windows, we recommend that the Lua library be a DLL.
In all cases, the compiler luac should be linked statically.
<P>
As mentioned above, you may edit <TT>src/luaconf.h</TT> to customize
@ -271,40 +268,50 @@ lists the
<H3>Main changes</H3>
<UL>
<LI> support for integers (64-bit by default)
<LI> better support for small architectures ("Small Lua" with 32-bit numbers)
<LI> integers (64-bit by default)
<LI> official support for 32-bit numbers
<LI> bitwise operators
<LI> basic utf-8 library
<LI> utf-8 escapes in literal strings
<LI> functions for packing/unpacking numbers
<LI> userdata can have any Lua value as uservalue
<LI> strip option in <CODE>lua_dump</CODE>/<CODE>string.dump</CODE>
<LI> basic utf-8 support
<LI> functions for packing and unpacking values
</UL>
Here are the other changes introduced in Lua 5.3:
<H3>Language</H3>
<UL>
<LI>
<LI> userdata can have any Lua value as uservalue
<LI> integer division
<LI> more flexible rules for some metamethods
</UL>
<H3>Libraries</H3>
<UL>
<LI>
<LI> <CODE>ipairs</CODE> and the table library respect metamethods
<LI> strip option in <CODE>string.dump</CODE>
<LI> table library respects metamethods
<LI> new function <CODE>table.move</CODE>
<LI> new function <CODE>string.pack</CODE>
<LI> new function <CODE>string.unpack</CODE>
<LI> new function <CODE>string.packsize</CODE>
</UL>
<H3>C API</H3>
<UL>
<LI>
</UL>
<H3>Implementation</H3>
<UL>
<LI>
<LI> simpler API for continuation functions in C
<LI> <CODE>lua_gettable</CODE> and similar functions return type of resulted value
<LI> strip option in <CODE>lua_dump</CODE>
<LI> new function: <CODE>lua_geti</CODE>
<LI> new function: <CODE>lua_seti</CODE>
<LI> new function: <CODE>lua_isyieldable</CODE>
<LI> new function: <CODE>lua_numbertointeger</CODE>
<LI> new function: <CODE>lua_rotate</CODE>
<LI> new function: <CODE>lua_stringtonumber</CODE>
</UL>
<H3>Lua standalone interpreter</H3>
<UL>
<LI> Can be used as calculator; no need to prefix with '='
<LI> can be used as calculator; no need to prefix with '='
<LI> <CODE>arg</CODE> table available to all code
</UL>
<H2><A NAME="license">License</A></H2>
@ -326,7 +333,7 @@ For details, see
<A HREF="http://www.lua.org/license.html">this</A>.
<BLOCKQUOTE STYLE="padding-bottom: 0em">
Copyright &copy; 1994&ndash;2014 Lua.org, PUC-Rio.
Copyright &copy; 1994&ndash;2015 Lua.org, PUC-Rio.
<P>
Permission is hereby granted, free of charge, to any person obtaining a copy
@ -354,10 +361,10 @@ THE SOFTWARE.
<HR>
<SMALL CLASS="footer">
Last update:
Wed Jun 11 22:54:18 BRT 2014
Fri Dec 12 09:58:42 BRST 2014
</SMALL>
<!--
Last change: updated for Lua 5.3.0 (work3)
Last change: updated for Lua 5.3.0 (final)
-->
</BODY>

View File

@ -6,8 +6,8 @@
# Your platform. See PLATS for possible values.
PLAT= none
CC= gcc
CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_ALL $(SYSCFLAGS) $(MYCFLAGS)
CC= gcc -std=gnu99
CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_5_2 $(SYSCFLAGS) $(MYCFLAGS)
LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
LIBS= -lm $(SYSLIBS) $(MYLIBS)
@ -26,7 +26,7 @@ MYOBJS=
# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
LUA_A= liblua.a
CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \
@ -91,12 +91,16 @@ none:
aix:
$(MAKE) $(ALL) CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl" SYSLDFLAGS="-brtl -bexpall"
ansi:
$(MAKE) $(ALL) SYSCFLAGS="-DLUA_ANSI"
bsd:
$(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E"
c89:
$(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_C89" CC="gcc -std=c89"
@echo ''
@echo '*** C89 does not guarantee 64-bit integers for Lua.'
@echo ''
freebsd:
$(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -lreadline"
@ -125,65 +129,69 @@ solaris:
# DO NOT DELETE
lapi.o: lapi.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \
lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h ltable.h lundump.h \
lvm.h
lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h
lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h
lbitlib.o: lbitlib.c lua.h luaconf.h lauxlib.h lualib.h
lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \
lstring.h ltable.h lvm.h
lcorolib.o: lcorolib.c lua.h luaconf.h lauxlib.h lualib.h
lctype.o: lctype.c lctype.h lua.h luaconf.h llimits.h
ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h
ldebug.o: ldebug.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \
ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h ldebug.h ldo.h \
lfunc.h lstring.h lgc.h ltable.h lvm.h
ldo.o: ldo.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \
lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h \
lstring.h ltable.h lundump.h lvm.h
ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \
lzio.h lmem.h lundump.h
lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h \
lstate.h ltm.h lzio.h lmem.h
lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h
liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h
llex.o: llex.c lua.h luaconf.h lctype.h llimits.h ldo.h lobject.h \
lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h ltable.h
lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h
lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
ltm.h lzio.h lmem.h ldo.h lgc.h
loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h
lobject.o: lobject.c lua.h luaconf.h lctype.h llimits.h ldebug.h lstate.h \
lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h lvm.h
lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h
loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h
lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lfunc.h \
lstring.h lgc.h ltable.h
lstate.o: lstate.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \
ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h lstring.h \
ltable.h
lstring.o: lstring.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h
ltm.o: ltm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h
lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h
luac.o: luac.c lua.h luaconf.h lauxlib.h lobject.h llimits.h lstate.h \
ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h
lutf8lib.o: lutf8lib.c lua.h luaconf.h lauxlib.h lualib.h
lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h
lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \
lzio.h
lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \
ltable.h lundump.h lvm.h
lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h
lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lbitlib.o: lbitlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
ldo.h lgc.h lstring.h ltable.h lvm.h
lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h
ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \
ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h
ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
lparser.h lstring.h ltable.h lundump.h lvm.h
ldump.o: ldump.c lprefix.h lua.h luaconf.h lobject.h llimits.h lstate.h \
ltm.h lzio.h lmem.h lundump.h
lfunc.o: lfunc.c lprefix.h lua.h luaconf.h lfunc.h lobject.h llimits.h \
lgc.h lstate.h ltm.h lzio.h lmem.h
lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h
liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldo.h \
lobject.h lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h \
ltable.h
lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h
loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \
ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \
lvm.h
lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h
loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
ldo.h lfunc.h lstring.h lgc.h ltable.h
lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \
lstring.h ltable.h
lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h
lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
luac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h lobject.h llimits.h \
lstate.h ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \
lundump.h
lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
lvm.o: lvm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \
ltable.h lvm.h
lzio.o: lzio.c lprefix.h lua.h luaconf.h llimits.h lmem.h lstate.h \
lobject.h ltm.h lzio.h
# (end of Makefile)

View File

@ -1,23 +1,22 @@
/* $NetBSD: lapi.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lapi.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lapi.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lapi.c,v 2.244 2014/12/26 14:43:45 roberto Exp
** Lua API
** See Copyright Notice in lua.h
*/
#define lapi_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <math.h>
#endif
#include <stdarg.h>
#ifndef _KERNEL
#include <string.h>
#endif
#define lapi_c
#define LUA_CORE
#include "lua.h"
#include "lapi.h"
@ -50,32 +49,35 @@ const char lua_ident[] =
/* test for pseudo index */
#define ispseudo(i) ((i) <= LUA_REGISTRYINDEX)
/* test for upvalue */
#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
/* test for valid but not pseudo index */
#define isstackindex(i, o) (isvalid(o) && !ispseudo(i))
#define api_checkvalidindex(L, o) api_check(L, isvalid(o), "invalid index")
#define api_checkvalidindex(o) api_check(isvalid(o), "invalid index")
#define api_checkstackindex(L, i, o) \
api_check(L, isstackindex(i, o), "index not in the stack")
#define api_checkstackindex(i, o) \
api_check(isstackindex(i, o), "index not in the stack")
static TValue *index2addr (lua_State *L, int idx) {
CallInfo *ci = L->ci;
if (idx > 0) {
TValue *o = ci->func + idx;
api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");
api_check(idx <= ci->top - (ci->func + 1), "unacceptable index");
if (o >= L->top) return NONVALIDVALUE;
else return o;
}
else if (!ispseudo(idx)) { /* negative index */
api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
api_check(idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
return L->top + idx;
}
else if (idx == LUA_REGISTRYINDEX)
return &G(L)->l_registry;
else { /* upvalues */
idx = LUA_REGISTRYINDEX - idx;
api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
api_check(idx <= MAXUPVAL + 1, "upvalue index too large");
if (ttislcf(ci->func)) /* light C function? */
return NONVALIDVALUE; /* it has no upvalues */
else {
@ -96,22 +98,22 @@ static void growstack (lua_State *L, void *ud) {
}
LUA_API int lua_checkstack (lua_State *L, int size) {
LUA_API int lua_checkstack (lua_State *L, int n) {
int res;
CallInfo *ci = L->ci;
lua_lock(L);
api_check(L, size >= 0, "negative 'size'");
if (L->stack_last - L->top > size) /* stack large enough? */
api_check(n >= 0, "negative 'n'");
if (L->stack_last - L->top > n) /* stack large enough? */
res = 1; /* yes; check is OK */
else { /* no; need to grow stack */
int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */
if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */
res = 0; /* no */
else /* try to grow stack */
res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK);
res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);
}
if (res && ci->top < L->top + size)
ci->top = L->top + size; /* adjust frame top */
if (res && ci->top < L->top + n)
ci->top = L->top + n; /* adjust frame top */
lua_unlock(L);
return res;
}
@ -122,8 +124,8 @@ LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
if (from == to) return;
lua_lock(to);
api_checknelems(from, n);
api_check(from, G(from) == G(to), "moving among independent states");
api_check(from, to->ci->top - to->top >= n, "not enough elements to move");
api_check(G(from) == G(to), "moving among independent states");
api_check(to->ci->top - to->top >= n, "not enough elements to move");
from->top -= n;
for (i = 0; i < n; i++) {
setobj2s(to, to->top++, from->top + i);
@ -174,14 +176,14 @@ LUA_API void lua_settop (lua_State *L, int idx) {
StkId func = L->ci->func;
lua_lock(L);
if (idx >= 0) {
api_check(L, idx <= L->stack_last - (func + 1), "new top too large");
api_check(idx <= L->stack_last - (func + 1), "new top too large");
while (L->top < (func + 1) + idx)
setnilvalue(L->top++);
L->top = (func + 1) + idx;
}
else {
api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
L->top += idx+1; /* `subtract' index (index is negative) */
api_check(-(idx+1) <= (L->top - (func + 1)), "invalid new top");
L->top += idx+1; /* 'subtract' index (index is negative) */
}
lua_unlock(L);
}
@ -189,7 +191,7 @@ LUA_API void lua_settop (lua_State *L, int idx) {
/*
** Reverse the stack segment from 'from' to 'to'
** (auxiliar to 'lua_rotate')
** (auxiliary to 'lua_rotate')
*/
static void reverse (lua_State *L, StkId from, StkId to) {
for (; from < to; from++, to--) {
@ -210,8 +212,8 @@ LUA_API void lua_rotate (lua_State *L, int idx, int n) {
lua_lock(L);
t = L->top - 1; /* end of stack segment being rotated */
p = index2addr(L, idx); /* start of segment */
api_checkstackindex(L, idx, p);
api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
api_checkstackindex(idx, p);
api_check((n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */
reverse(L, p, m); /* reverse the prefix with length 'n' */
reverse(L, m + 1, t); /* reverse the suffix */
@ -220,31 +222,17 @@ LUA_API void lua_rotate (lua_State *L, int idx, int n) {
}
static void moveto (lua_State *L, TValue *fr, int idx) {
TValue *to = index2addr(L, idx);
api_checkvalidindex(L, to);
LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
TValue *fr, *to;
lua_lock(L);
fr = index2addr(L, fromidx);
to = index2addr(L, toidx);
api_checkvalidindex(to);
setobj(L, to, fr);
if (idx < LUA_REGISTRYINDEX) /* function upvalue? */
if (isupvalue(toidx)) /* function upvalue? */
luaC_barrier(L, clCvalue(L->ci->func), fr);
/* LUA_REGISTRYINDEX does not need gc barrier
(collector revisits it before finishing collection) */
}
LUA_API void lua_replace (lua_State *L, int idx) {
lua_lock(L);
api_checknelems(L, 1);
moveto(L, L->top - 1, idx);
L->top--;
lua_unlock(L);
}
LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
TValue *fr;
lua_lock(L);
fr = index2addr(L, fromidx);
moveto(L, fr, toidx);
lua_unlock(L);
}
@ -271,6 +259,7 @@ LUA_API int lua_type (lua_State *L, int idx) {
LUA_API const char *lua_typename (lua_State *L, int t) {
UNUSED(L);
api_check(LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
return ttypename(t);
}
@ -287,21 +276,18 @@ LUA_API int lua_isinteger (lua_State *L, int idx) {
}
LUA_API int lua_isnumber (lua_State *L, int idx) {
#ifndef _KERNEL
LUA_API int lua_isnumber (lua_State *L, int idx) {
lua_Number n;
const TValue *o = index2addr(L, idx);
return tonumber(o, &n);
#else
StkId o = index2addr(L, idx);
return ttisinteger(o);
#endif
}
#endif
LUA_API int lua_isstring (lua_State *L, int idx) {
int t = lua_type(L, idx);
return (t == LUA_TSTRING || t == LUA_TNUMBER);
const TValue *o = index2addr(L, idx);
return (ttisstring(o) || cvt2str(o));
}
@ -345,7 +331,7 @@ LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
default: api_check(L, 0, "invalid option");
default: api_check(0, "invalid option");
}
}
lua_unlock(L);
@ -353,7 +339,7 @@ LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) {
}
LUA_API size_t lua_strtonum (lua_State *L, const char *s) {
LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
size_t sz = luaO_str2num(s, L->top);
if (sz != 0)
api_incr_top(L);
@ -361,6 +347,7 @@ LUA_API size_t lua_strtonum (lua_State *L, const char *s) {
}
#ifndef _KERNEL
LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
lua_Number n;
const TValue *o = index2addr(L, idx);
@ -370,6 +357,7 @@ LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
if (pisnum) *pisnum = isnum;
return n;
}
#endif
LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
@ -383,42 +371,6 @@ LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
}
LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *pisnum) {
lua_Unsigned res = 0;
const TValue *o = index2addr(L, idx);
int isnum = 0;
switch (ttype(o)) {
case LUA_TNUMINT: {
res = l_castS2U(ivalue(o));
isnum = 1;
break;
}
#ifndef _KERNEL
case LUA_TNUMFLT: { /* compute floor(n) % 2^(numbits in an integer) */
const lua_Number two2n = cast_num(LUA_MAXUNSIGNED) + cast_num(1);
lua_Number n = fltvalue(o); /* get value */
int neg = 0;
n = l_floor(n); /* get its floor */
if (n < 0) {
neg = 1;
n = -n; /* make 'n' positive, so that 'fmod' is the same as '%' */
}
n = l_mathop(fmod)(n, two2n); /* n = n % 2^(numbits in an integer) */
if (luai_numisnan(n)) /* not a number? */
break; /* not an integer, too */
res = cast(lua_Unsigned, n); /* 'n' now must fit in an unsigned */
if (neg) res = 0u - res; /* back to negative, if needed */
isnum = 1;
break;
}
#endif
default: break;
}
if (pisnum) *pisnum = isnum;
return res;
}
LUA_API int lua_toboolean (lua_State *L, int idx) {
const TValue *o = index2addr(L, idx);
return !l_isfalse(o);
@ -428,14 +380,14 @@ LUA_API int lua_toboolean (lua_State *L, int idx) {
LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
StkId o = index2addr(L, idx);
if (!ttisstring(o)) {
lua_lock(L); /* `luaV_tostring' may create a new string */
if (!luaV_tostring(L, o)) { /* conversion failed? */
if (!cvt2str(o)) { /* not convertible? */
if (len != NULL) *len = 0;
lua_unlock(L);
return NULL;
}
lua_lock(L); /* 'luaO_tostring' may create a new string */
luaC_checkGC(L);
o = index2addr(L, idx); /* previous call may reallocate the stack */
luaO_tostring(L, o);
lua_unlock(L);
}
if (len != NULL) *len = tsvalue(o)->len;
@ -466,7 +418,7 @@ LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
LUA_API void *lua_touserdata (lua_State *L, int idx) {
StkId o = index2addr(L, idx);
switch (ttnov(o)) {
case LUA_TUSERDATA: return (rawuvalue(o) + 1);
case LUA_TUSERDATA: return getudatamem(uvalue(o));
case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL;
}
@ -509,16 +461,14 @@ LUA_API void lua_pushnil (lua_State *L) {
}
#ifndef _KERNEL
LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
lua_lock(L);
#ifndef _KERNEL
setfltvalue(L->top, n);
#else
setivalue(L->top, n);
#endif
api_incr_top(L);
lua_unlock(L);
}
#endif
LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
@ -529,14 +479,6 @@ LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
}
LUA_API void lua_pushunsigned (lua_State *L, lua_Unsigned u) {
lua_lock(L);
setivalue(L->top, l_castU2S(u));
api_incr_top(L);
lua_unlock(L);
}
LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
TString *ts;
lua_lock(L);
@ -599,7 +541,7 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
else {
CClosure *cl;
api_checknelems(L, n);
api_check(L, n <= MAXUPVAL, "upvalue index too large");
api_check(n <= MAXUPVAL, "upvalue index too large");
luaC_checkGC(L);
cl = luaF_newCclosure(L, n);
cl->f = fn;
@ -646,12 +588,12 @@ LUA_API int lua_pushthread (lua_State *L) {
*/
LUA_API int lua_getglobal (lua_State *L, const char *var) {
LUA_API int lua_getglobal (lua_State *L, const char *name) {
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt; /* global table */
lua_lock(L);
gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
setsvalue2s(L, L->top++, luaS_new(L, var));
setsvalue2s(L, L->top++, luaS_new(L, name));
luaV_gettable(L, gt, L->top - 1, L->top - 1);
lua_unlock(L);
return ttnov(L->top - 1);
@ -680,11 +622,23 @@ LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
}
LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
StkId t;
lua_lock(L);
t = index2addr(L, idx);
setivalue(L->top, n);
api_incr_top(L);
luaV_gettable(L, t, L->top - 1, L->top - 1);
lua_unlock(L);
return ttnov(L->top - 1);
}
LUA_API int lua_rawget (lua_State *L, int idx) {
StkId t;
lua_lock(L);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
api_check(ttistable(t), "table expected");
setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
lua_unlock(L);
return ttnov(L->top - 1);
@ -695,7 +649,7 @@ LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
StkId t;
lua_lock(L);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
api_check(ttistable(t), "table expected");
setobj2s(L, L->top, luaH_getint(hvalue(t), n));
api_incr_top(L);
lua_unlock(L);
@ -708,7 +662,7 @@ LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
TValue k;
lua_lock(L);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
api_check(ttistable(t), "table expected");
setpvalue(&k, cast(void *, p));
setobj2s(L, L->top, luaH_get(hvalue(t), &k));
api_incr_top(L);
@ -732,8 +686,8 @@ LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
LUA_API int lua_getmetatable (lua_State *L, int objindex) {
const TValue *obj;
Table *mt = NULL;
int res;
Table *mt;
int res = 0;
lua_lock(L);
obj = index2addr(L, objindex);
switch (ttnov(obj)) {
@ -747,9 +701,7 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) {
mt = G(L)->mt[ttnov(obj)];
break;
}
if (mt == NULL)
res = 0;
else {
if (mt != NULL) {
sethvalue(L, L->top, mt);
api_incr_top(L);
res = 1;
@ -763,8 +715,8 @@ LUA_API int lua_getuservalue (lua_State *L, int idx) {
StkId o;
lua_lock(L);
o = index2addr(L, idx);
api_check(L, ttisfulluserdata(o), "full userdata expected");
getuservalue(L, rawuvalue(o), L->top);
api_check(ttisfulluserdata(o), "full userdata expected");
getuservalue(L, uvalue(o), L->top);
api_incr_top(L);
lua_unlock(L);
return ttnov(L->top - 1);
@ -776,13 +728,13 @@ LUA_API int lua_getuservalue (lua_State *L, int idx) {
*/
LUA_API void lua_setglobal (lua_State *L, const char *var) {
LUA_API void lua_setglobal (lua_State *L, const char *name) {
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt; /* global table */
lua_lock(L);
api_checknelems(L, 1);
gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
setsvalue2s(L, L->top++, luaS_new(L, var));
setsvalue2s(L, L->top++, luaS_new(L, name));
luaV_settable(L, gt, L->top - 1, L->top - 2);
L->top -= 2; /* pop value and key */
lua_unlock(L);
@ -812,43 +764,61 @@ LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
}
LUA_API void lua_rawset (lua_State *L, int idx) {
LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
StkId t;
lua_lock(L);
api_checknelems(L, 2);
api_checknelems(L, 1);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
invalidateTMcache(hvalue(t));
luaC_barrierback(L, gcvalue(t), L->top-1);
setivalue(L->top++, n);
luaV_settable(L, t, L->top - 1, L->top - 2);
L->top -= 2; /* pop value and key */
lua_unlock(L);
}
LUA_API void lua_rawset (lua_State *L, int idx) {
StkId o;
Table *t;
lua_lock(L);
api_checknelems(L, 2);
o = index2addr(L, idx);
api_check(ttistable(o), "table expected");
t = hvalue(o);
setobj2t(L, luaH_set(L, t, L->top-2), L->top-1);
invalidateTMcache(t);
luaC_barrierback(L, t, L->top-1);
L->top -= 2;
lua_unlock(L);
}
LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
StkId t;
StkId o;
Table *t;
lua_lock(L);
api_checknelems(L, 1);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
luaH_setint(L, hvalue(t), n, L->top - 1);
luaC_barrierback(L, gcvalue(t), L->top-1);
o = index2addr(L, idx);
api_check(ttistable(o), "table expected");
t = hvalue(o);
luaH_setint(L, t, n, L->top - 1);
luaC_barrierback(L, t, L->top-1);
L->top--;
lua_unlock(L);
}
LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
StkId t;
StkId o;
Table *t;
TValue k;
lua_lock(L);
api_checknelems(L, 1);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
o = index2addr(L, idx);
api_check(ttistable(o), "table expected");
t = hvalue(o);
setpvalue(&k, cast(void *, p));
setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1);
luaC_barrierback(L, gcvalue(t), L->top - 1);
setobj2t(L, luaH_set(L, t, &k), L->top - 1);
luaC_barrierback(L, t, L->top - 1);
L->top--;
lua_unlock(L);
}
@ -863,7 +833,7 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) {
if (ttisnil(L->top - 1))
mt = NULL;
else {
api_check(L, ttistable(L->top - 1), "table expected");
api_check(ttistable(L->top - 1), "table expected");
mt = hvalue(L->top - 1);
}
switch (ttnov(obj)) {
@ -878,7 +848,7 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) {
case LUA_TUSERDATA: {
uvalue(obj)->metatable = mt;
if (mt) {
luaC_objbarrier(L, rawuvalue(obj), mt);
luaC_objbarrier(L, uvalue(obj), mt);
luaC_checkfinalizer(L, gcvalue(obj), mt);
}
break;
@ -899,8 +869,8 @@ LUA_API void lua_setuservalue (lua_State *L, int idx) {
lua_lock(L);
api_checknelems(L, 1);
o = index2addr(L, idx);
api_check(L, ttisfulluserdata(o), "full userdata expected");
setuservalue(L, rawuvalue(o), L->top - 1);
api_check(ttisfulluserdata(o), "full userdata expected");
setuservalue(L, uvalue(o), L->top - 1);
luaC_barrier(L, gcvalue(o), L->top - 1);
L->top--;
lua_unlock(L);
@ -908,23 +878,23 @@ LUA_API void lua_setuservalue (lua_State *L, int idx) {
/*
** `load' and `call' functions (run Lua code)
** 'load' and 'call' functions (run Lua code)
*/
#define checkresults(L,na,nr) \
api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
api_check((nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
"results from function overflow current stack size")
LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
lua_KFunction k) {
LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
lua_KContext ctx, lua_KFunction k) {
StkId func;
lua_lock(L);
api_check(L, k == NULL || !isLua(L->ci),
api_check(k == NULL || !isLua(L->ci),
"cannot use continuations inside hooks");
api_checknelems(L, nargs+1);
api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
checkresults(L, nargs, nresults);
func = L->top - (nargs+1);
if (k != NULL && L->nny == 0) { /* need to prepare continuation? */
@ -943,7 +913,7 @@ LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
/*
** Execute a protected call.
*/
struct CallS { /* data to `f_call' */
struct CallS { /* data to 'f_call' */
StkId func;
int nresults;
};
@ -957,21 +927,21 @@ static void f_call (lua_State *L, void *ud) {
LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
int ctx, lua_KFunction k) {
lua_KContext ctx, lua_KFunction k) {
struct CallS c;
int status;
ptrdiff_t func;
lua_lock(L);
api_check(L, k == NULL || !isLua(L->ci),
api_check(k == NULL || !isLua(L->ci),
"cannot use continuations inside hooks");
api_checknelems(L, nargs+1);
api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
checkresults(L, nargs, nresults);
if (errfunc == 0)
func = 0;
else {
StkId o = index2addr(L, errfunc);
api_checkstackindex(L, errfunc, o);
api_checkstackindex(errfunc, o);
func = savestack(L, o);
}
c.func = L->top - (nargs+1); /* function to be called */
@ -1010,13 +980,13 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
status = luaD_protectedparser(L, &z, chunkname, mode);
if (status == LUA_OK) { /* no errors? */
LClosure *f = clLvalue(L->top - 1); /* get newly created function */
if (f->nupvalues == 1) { /* does it have one upvalue? */
if (f->nupvalues >= 1) { /* does it have an upvalue? */
/* get global table from registry */
Table *reg = hvalue(&G(L)->l_registry);
const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
/* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
setobj(L, f->upvals[0]->v, gt);
luaC_barrier(L, f->upvals[0], gt);
luaC_upvalbarrier(L, f->upvals[0]);
}
}
lua_unlock(L);
@ -1079,7 +1049,7 @@ LUA_API int lua_gc (lua_State *L, int what, int data) {
case LUA_GCSTEP: {
l_mem debt = 1; /* =1 to signal that it did an actual step */
int oldrunning = g->gcrunning;
g->gcrunning = 1; /* force GC to run */
g->gcrunning = 1; /* allow GC to run */
if (data == 0) {
luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */
luaC_step(L);
@ -1136,7 +1106,7 @@ LUA_API int lua_next (lua_State *L, int idx) {
int more;
lua_lock(L);
t = index2addr(L, idx);
api_check(L, ttistable(t), "table expected");
api_check(ttistable(t), "table expected");
more = luaH_next(L, hvalue(t), L->top - 1);
if (more) {
api_incr_top(L);
@ -1200,19 +1170,19 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
setuvalue(L, L->top, u);
api_incr_top(L);
lua_unlock(L);
return u + 1;
return getudatamem(u);
}
static const char *aux_upvalue (StkId fi, int n, TValue **val,
GCObject **owner, UpVal **uv) {
CClosure **owner, UpVal **uv) {
switch (ttype(fi)) {
case LUA_TCCL: { /* C closure */
CClosure *f = clCvalue(fi);
if (!(1 <= n && n <= f->nupvalues)) return NULL;
*val = &f->upvalue[n-1];
if (owner) *owner = obj2gco(f);
if (owner) *owner = f;
return "";
}
case LUA_TLCL: { /* Lua closure */
@ -1247,7 +1217,7 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val = NULL; /* to avoid warnings */
GCObject *owner = NULL;
CClosure *owner = NULL;
UpVal *uv = NULL;
StkId fi;
lua_lock(L);
@ -1268,9 +1238,9 @@ LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
LClosure *f;
StkId fi = index2addr(L, fidx);
api_check(L, ttisLclosure(fi), "Lua function expected");
api_check(ttisLclosure(fi), "Lua function expected");
f = clLvalue(fi);
api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
api_check((1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
if (pf) *pf = f;
return &f->upvals[n - 1]; /* get its upvalue pointer */
}
@ -1284,11 +1254,11 @@ LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
}
case LUA_TCCL: { /* C closure */
CClosure *f = clCvalue(fi);
api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
api_check(1 <= n && n <= f->nupvalues, "invalid upvalue index");
return &f->upvalue[n - 1];
}
default: {
api_check(L, 0, "closure expected");
api_check(0, "closure expected");
return NULL;
}
}

View File

@ -1,7 +1,5 @@
/* $NetBSD: lapi.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lapi.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lapi.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
@ -13,13 +11,13 @@
#include "llimits.h"
#include "lstate.h"
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
#define api_incr_top(L) {L->top++; api_check(L->top <= L->ci->top, \
"stack overflow");}
#define adjustresults(L,nres) \
{ if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
#define api_checknelems(L,n) api_check((n) < (L->top - L->ci->func), \
"not enough elements in the stack")

View File

@ -1,15 +1,22 @@
/* $NetBSD: lauxlib.c,v 1.3 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lauxlib.c,v 1.4 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lauxlib.c,v 1.3 2014/07/19 18:38:34 lneto Exp $
** Id: lauxlib.c,v 1.279 2014/12/14 18:32:26 roberto Exp
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#define lauxlib_c
#define LUA_LIB
#include "lprefix.h"
#ifndef _KERNEL
#include <errno.h>
#endif
#include <stdarg.h>
#ifndef _KERNEL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -20,9 +27,6 @@
** Any function declared here could be written as an application function.
*/
#define lauxlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -68,11 +72,20 @@ static int findfield (lua_State *L, int objidx, int level) {
}
/*
** Search for a name for a function in all loaded modules
** (registry._LOADED).
*/
static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
int top = lua_gettop(L);
lua_getinfo(L, "f", ar); /* push function */
lua_pushglobaltable(L);
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
if (findfield(L, top + 1, 2)) {
const char *name = lua_tostring(L, -1);
if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */
lua_pushstring(L, name + 3); /* push name without prefix */
lua_remove(L, -2); /* remove original name */
}
lua_copy(L, -1, top + 1); /* move name to proper place */
lua_pop(L, 2); /* remove pushed values */
return 1;
@ -85,20 +98,18 @@ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
static void pushfuncname (lua_State *L, lua_Debug *ar) {
if (*ar->namewhat != '\0') /* is there a name? */
lua_pushfstring(L, "function " LUA_QS, ar->name);
if (pushglobalfuncname(L, ar)) { /* try first a global name */
lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */
}
else if (*ar->namewhat != '\0') /* is there a name from code? */
lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
else if (*ar->what == 'm') /* main? */
lua_pushliteral(L, "main chunk");
else if (*ar->what == 'C') {
if (pushglobalfuncname(L, ar)) {
lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
lua_remove(L, -2); /* remove name */
}
else
lua_pushliteral(L, "?");
}
else
else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
else /* nothing left... */
lua_pushliteral(L, "?");
}
@ -160,27 +171,27 @@ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
lua_getinfo(L, "n", &ar);
if (strcmp(ar.namewhat, "method") == 0) {
arg--; /* do not count `self' */
arg--; /* do not count 'self' */
if (arg == 0) /* error is in the self argument itself? */
return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
return luaL_error(L, "calling '%s' on bad self (%s)",
ar.name, extramsg);
}
if (ar.name == NULL)
ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
return luaL_error(L, "bad argument #%d to '%s' (%s)",
arg, ar.name, extramsg);
}
static int typeerror (lua_State *L, int arg, const char *tname) {
const char *msg;
const char *typearg = luaL_typename(L, arg);
if (lua_getmetatable(L, arg)) {
if (lua_getfield(L, -1, "__name") == LUA_TSTRING)
typearg = lua_tostring(L, -1);
}
const char *typearg; /* name for the type of the actual argument */
if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
typearg = lua_tostring(L, -1); /* use the given type name */
else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
typearg = "light userdata";
typearg = "light userdata"; /* special name for messages */
else
typearg = luaL_typename(L, arg); /* standard name */
msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
return luaL_argerror(L, arg, msg);
}
@ -235,7 +246,7 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
#endif
#if !defined(inspectstat) /* { */
#if !defined(l_inspectstat) /* { */
#if defined(LUA_USE_POSIX)
@ -244,13 +255,13 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
/*
** use appropriate macros to interpret 'pclose' return status
*/
#define inspectstat(stat,what) \
#define l_inspectstat(stat,what) \
if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
#else
#define inspectstat(stat,what) /* no op */
#define l_inspectstat(stat,what) /* no op */
#endif
@ -263,7 +274,7 @@ LUALIB_API int luaL_execresult (lua_State *L, int stat) {
if (stat == -1) /* error? */
return luaL_fileresult(L, 0, NULL);
else {
inspectstat(stat, what); /* interpret result */
l_inspectstat(stat, what); /* interpret result */
if (*what == 'e' && stat == 0) /* successful termination? */
lua_pushboolean(L, 1);
else
@ -285,8 +296,7 @@ LUALIB_API int luaL_execresult (lua_State *L, int stat) {
*/
LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
luaL_getmetatable(L, tname); /* try to get metatable */
if (!lua_isnil(L, -1)) /* name already in use? */
if (luaL_getmetatable(L, tname)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
lua_newtable(L); /* create metatable */
@ -343,7 +353,7 @@ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
if (strcmp(lst[i], name) == 0)
return i;
return luaL_argerror(L, arg,
lua_pushfstring(L, "invalid option " LUA_QS, name));
lua_pushfstring(L, "invalid option '%s'", name));
}
@ -403,9 +413,10 @@ LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
}
#ifndef _KERNEL
static void interror (lua_State *L, int arg) {
if (lua_type(L, arg) == LUA_TNUMBER)
luaL_argerror(L, arg, "float value out of integer range");
if (lua_isnumber(L, arg))
luaL_argerror(L, arg, "number has no integer representation");
else
tag_error(L, arg, LUA_TNUMBER);
}
@ -421,25 +432,11 @@ LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
}
LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int arg) {
int isnum;
lua_Unsigned d = lua_tounsignedx(L, arg, &isnum);
if (!isnum)
interror(L, arg);
return d;
}
LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
lua_Integer def) {
return luaL_opt(L, luaL_checkinteger, arg, def);
}
LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int arg,
lua_Unsigned def) {
return luaL_opt(L, luaL_checkunsigned, arg, def);
}
#endif
/* }====================================================== */
@ -549,7 +546,7 @@ LUALIB_API int luaL_ref (lua_State *L, int t) {
int ref;
if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* remove from stack */
return LUA_REFNIL; /* `nil' has a unique fixed reference */
return LUA_REFNIL; /* 'nil' has a unique fixed reference */
}
t = lua_absindex(L, t);
lua_rawgeti(L, t, freelist); /* get first free element */
@ -589,7 +586,7 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
typedef struct LoadF {
int n; /* number of pre-read characters */
FILE *f; /* file being read */
char buff[LUAL_BUFFERSIZE]; /* area for reading file */
char buff[BUFSIZ]; /* area for reading file */
} LoadF;
@ -682,7 +679,7 @@ LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
readstatus = ferror(lf.f);
if (filename) fclose(lf.f); /* close file (even in case of errors) */
if (readstatus) {
lua_settop(L, fnameindex); /* ignore results from `lua_load' */
lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
return errfile(L, "read", fnameindex);
}
lua_remove(L, fnameindex);
@ -726,22 +723,23 @@ LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
if (!lua_getmetatable(L, obj)) /* no metatable? */
return 0;
lua_pushstring(L, event);
if (lua_rawget(L, -2) == LUA_TNIL) { /* is metafield nil? */
lua_pop(L, 2); /* remove metatable and metafield */
return 0;
}
return LUA_TNIL;
else {
lua_remove(L, -2); /* remove only metatable */
return 1;
int tt;
lua_pushstring(L, event);
tt = lua_rawget(L, -2);
if (tt == LUA_TNIL) /* is metafield nil? */
lua_pop(L, 2); /* remove metatable and metafield */
else
lua_remove(L, -2); /* remove only metatable */
return tt; /* return metafield type */
}
}
LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
obj = lua_absindex(L, obj);
if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
return 0;
lua_pushvalue(L, obj);
lua_call(L, 1, 1);
@ -847,7 +845,7 @@ LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
/* try global variable (and create one if it does not exist) */
lua_pushglobaltable(L);
if (luaL_findtable(L, 0, modname, sizehint) != NULL)
luaL_error(L, "name conflict for module " LUA_QS, modname);
luaL_error(L, "name conflict for module '%s'", modname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
}
@ -908,22 +906,26 @@ LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
/*
** stripped-down 'require'. Calls 'openf' to open a module,
** registers the result in 'package.loaded' table and, if 'glb'
** is true, also registers the result in the global table.
** Stripped-down 'require': After checking "loaded" table, calls 'openf'
** to open a module, registers the result in 'package.loaded' table and,
** if 'glb' is true, also registers the result in the global table.
** Leaves resulting module on the top.
*/
LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
lua_CFunction openf, int glb) {
lua_pushcfunction(L, openf);
lua_pushstring(L, modname); /* argument to open function */
lua_call(L, 1, 1); /* open module */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_pushvalue(L, -2); /* make copy of module (call result) */
lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
lua_pop(L, 1); /* remove _LOADED table */
lua_getfield(L, -1, modname); /* _LOADED[modname] */
if (!lua_toboolean(L, -1)) { /* package not already loaded? */
lua_pop(L, 1); /* remove field */
lua_pushcfunction(L, openf);
lua_pushstring(L, modname); /* argument to open function */
lua_call(L, 1, 1); /* call 'openf' to open module */
lua_pushvalue(L, -1); /* make copy of module (call result) */
lua_setfield(L, -3, modname); /* _LOADED[modname] = module */
}
lua_remove(L, -2); /* remove _LOADED table */
if (glb) {
lua_pushvalue(L, -1); /* copy of 'mod' */
lua_pushvalue(L, -1); /* copy of module */
lua_setglobal(L, modname); /* _G[modname] = module */
}
}
@ -938,7 +940,7 @@ LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
while ((wild = strstr(s, p)) != NULL) {
luaL_addlstring(&b, s, wild - s); /* push prefix */
luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after `p' */
s = wild + l; /* continue after 'p' */
}
luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
@ -959,8 +961,8 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
static int panic (lua_State *L) {
luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
return 0; /* return to Lua to abort */
}
@ -975,13 +977,12 @@ LUALIB_API lua_State *luaL_newstate (void) {
LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
const lua_Number *v = lua_version(L);
if (sz != LUAL_NUMSIZES) /* check numeric types */
luaL_error(L, "core and library have incompatible numeric types");
if (v != lua_version(NULL))
luaL_error(L, "multiple Lua VMs detected");
else if (*v != ver)
luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
ver, *v);
/* check numeric types */
if (sz != LUAL_NUMSIZES)
luaL_error(L, "core and library have incompatible numeric types");
}

View File

@ -1,7 +1,7 @@
/* $NetBSD: lauxlib.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lauxlib.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lauxlib.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@ -20,7 +20,7 @@
/* extra error code for `luaL_load' */
/* extra error code for 'luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1)
@ -47,12 +47,14 @@ LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
#ifndef _KERNEL
LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
lua_Integer def);
LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int arg);
LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int arg,
lua_Unsigned def);
#else /* _KERNEL */
#define luaL_checkinteger luaL_checknumber
#define luaL_optinteger(L,a,d) luaL_optnumber(L, (a), (lua_Number)(d))
#endif
LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
@ -126,10 +128,6 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
@ -223,6 +221,55 @@ LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
#endif
#ifndef _KERNEL
/*
** {==================================================================
** "Abstraction Layer" for basic report of messages and errors
** ===================================================================
*/
/* print a string */
#if !defined(lua_writestring)
#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#endif
/* print a newline and flush the output */
#if !defined(lua_writeline)
#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
#endif
/* print an error message */
#if !defined(lua_writestringerror)
#define lua_writestringerror(s,p) \
(fprintf(stderr, (s), (p)), fflush(stderr))
#endif
/* }================================================================== */
#endif
/*
** {============================================================
** Compatibility with deprecated conversions
** =============================================================
*/
#if defined(LUA_COMPAT_APIINTCASTS)
#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a))
#define luaL_optunsigned(L,a,d) \
((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#endif
/* }============================================================ */
#endif

View File

@ -1,11 +1,15 @@
/* $NetBSD: lbaselib.c,v 1.3 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lbaselib.c,v 1.4 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lbaselib.c,v 1.3 2014/07/19 18:38:34 lneto Exp $
** Id: lbaselib.c,v 1.309 2014/12/10 12:26:42 roberto Exp
** Basic library
** See Copyright Notice in lua.h
*/
#define lbaselib_c
#define LUA_LIB
#include "lprefix.h"
#ifndef _KERNEL
@ -15,9 +19,6 @@
#include <string.h>
#endif
#define lbaselib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -36,13 +37,12 @@ static int luaB_print (lua_State *L) {
lua_call(L, 1, 1);
s = lua_tolstring(L, -1, &l); /* get result */
if (s == NULL)
return luaL_error(L,
LUA_QL("tostring") " must return a string to " LUA_QL("print"));
if (i>1) luai_writestring("\t", 1);
luai_writestring(s, l);
return luaL_error(L, "'tostring' must return a string to 'print'");
if (i>1) lua_writestring("\t", 1);
lua_writestring(s, l);
lua_pop(L, 1); /* pop result */
}
luai_writeline();
lua_writeline();
return 0;
}
@ -65,8 +65,6 @@ static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
s++;
} while (isalnum((unsigned char)*s));
s += strspn(s, SPACECHARS); /* skip trailing spaces */
if (*s != '\0') /* invalid trailing characters? */
return NULL;
*pn = (lua_Integer)((neg) ? (0u - n) : n);
return s;
}
@ -82,7 +80,7 @@ static int luaB_tonumber (lua_State *L) {
else {
size_t l;
const char *s = lua_tolstring(L, 1, &l);
if (s != NULL && lua_strtonum(L, s) == l + 1)
if (s != NULL && lua_stringtonumber(L, s) == l + 1)
return 1; /* successful conversion to number */
/* else not a number */
}
@ -91,11 +89,11 @@ static int luaB_tonumber (lua_State *L) {
size_t l;
const char *s;
lua_Integer n = 0; /* to avoid warnings */
int base = luaL_checkint(L, 2);
lua_Integer base = luaL_checkinteger(L, 2);
luaL_checktype(L, 1, LUA_TSTRING); /* before 'luaL_checklstring'! */
s = luaL_checklstring(L, 1, &l);
luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
if (b_str2int(s, base, &n) == s + l) {
if (b_str2int(s, (int)base, &n) == s + l) {
lua_pushinteger(L, n);
return 1;
} /* else not a number */
@ -106,7 +104,7 @@ static int luaB_tonumber (lua_State *L) {
static int luaB_error (lua_State *L) {
int level = luaL_optint(L, 2, 1);
int level = (int)luaL_optinteger(L, 2, 1);
lua_settop(L, 1);
if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
luaL_where(L, level);
@ -133,7 +131,7 @@ static int luaB_setmetatable (lua_State *L) {
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"))
if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
return luaL_error(L, "cannot change a protected metatable");
lua_settop(L, 2);
lua_setmetatable(L, 1);
@ -184,7 +182,7 @@ static int luaB_collectgarbage (lua_State *L) {
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
LUA_GCISRUNNING};
int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
int ex = luaL_optint(L, 2, 0);
int ex = (int)luaL_optinteger(L, 2, 0);
int res = lua_gc(L, o, ex);
switch (o) {
case LUA_GCCOUNT: {
@ -204,16 +202,19 @@ static int luaB_collectgarbage (lua_State *L) {
}
/*
** This function has all type names as upvalues, to maximize performance.
*/
static int luaB_type (lua_State *L) {
luaL_checkany(L, 1);
lua_pushstring(L, luaL_typename(L, 1));
lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
return 1;
}
static int pairsmeta (lua_State *L, const char *method, int iszero,
lua_CFunction iter) {
if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */
if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */
luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
lua_pushcfunction(L, iter); /* will return generator, */
lua_pushvalue(L, 1); /* state, */
@ -245,17 +246,44 @@ static int luaB_pairs (lua_State *L) {
}
static int ipairsaux (lua_State *L) {
int i = luaL_checkint(L, 2);
/*
** Traversal function for 'ipairs' for raw tables
*/
static int ipairsaux_raw (lua_State *L) {
lua_Integer i = luaL_checkinteger(L, 2) + 1;
luaL_checktype(L, 1, LUA_TTABLE);
i++; /* next value */
lua_pushinteger(L, i);
return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
}
/*
** Traversal function for 'ipairs' for tables with metamethods
*/
static int ipairsaux (lua_State *L) {
lua_Integer i = luaL_checkinteger(L, 2) + 1;
lua_pushinteger(L, i);
return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
}
/*
** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
** traverse a table, depending on whether the table has metamethods
** that can affect the traversal.
*/
static int luaB_ipairs (lua_State *L) {
return pairsmeta(L, "__ipairs", 1, ipairsaux);
lua_CFunction iter = (luaL_getmetafield(L, 1, "__index") != LUA_TNIL)
? ipairsaux : ipairsaux_raw;
#if defined(LUA_COMPAT_IPAIRS)
return pairsmeta(L, "__ipairs", 1, iter);
#else
luaL_checkany(L, 1);
lua_pushcfunction(L, iter); /* iteration function */
lua_pushvalue(L, 1); /* state */
lua_pushinteger(L, 0); /* initial value */
return 3;
#endif
}
@ -303,7 +331,7 @@ static int luaB_loadfile (lua_State *L) {
/*
** Reader for generic `load' function: `lua_load' uses the
** 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.
@ -348,7 +376,7 @@ static int luaB_load (lua_State *L) {
#ifndef _KERNEL
static int dofilecont (lua_State *L, int d1, int d2) {
static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
(void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
return lua_gettop(L) - 1;
}
@ -369,9 +397,10 @@ static int luaB_assert (lua_State *L) {
if (lua_toboolean(L, 1)) /* condition is true? */
return lua_gettop(L); /* return all arguments */
else { /* error */
if (lua_isnone(L, 2)) /* no error message? */
lua_pushliteral(L, "assertion failed!"); /* use standard message */
lua_remove(L, 1); /* remove the condition (if there is one...) */
luaL_checkany(L, 1); /* there must be a condition */
lua_remove(L, 1); /* remove it */
lua_pushliteral(L, "assertion failed!"); /* default message */
lua_settop(L, 1); /* leave only message (default if no other one) */
return luaB_error(L); /* call 'error' */
}
}
@ -384,30 +413,30 @@ static int luaB_select (lua_State *L) {
return 1;
}
else {
int i = luaL_checkint(L, 1);
lua_Integer i = luaL_checkinteger(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;
return n - (int)i;
}
}
/*
** Continuation function for 'pcall' and 'xpcall'. Both functions
** already pushed a 'true' before doing the call, so in case of sucess
** already pushed a 'true' before doing the call, so in case of success
** 'finishpcall' only has to return everything in the stack minus
** 'extra' values (where 'extra' is exactly the number of items to be
** ignored).
*/
static int finishpcall (lua_State *L, int status, int extra) {
static int finishpcall (lua_State *L, int status, lua_KContext extra) {
if (status != LUA_OK && status != LUA_YIELD) { /* error? */
lua_pushboolean(L, 0); /* first result (false) */
lua_pushvalue(L, -2); /* error message */
return 2; /* return false, msg */
}
else
return lua_gettop(L) - extra; /* return all results */
return lua_gettop(L) - (int)extra; /* return all results */
}
@ -473,21 +502,31 @@ static const luaL_Reg base_funcs[] = {
{"setmetatable", luaB_setmetatable},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
{"type", luaB_type},
{"xpcall", luaB_xpcall},
/* placeholders */
{"type", NULL},
{"_G", NULL},
{"_VERSION", NULL},
{NULL, NULL}
};
LUAMOD_API int luaopen_base (lua_State *L) {
/* set global _G */
lua_pushglobaltable(L);
lua_pushglobaltable(L);
lua_setfield(L, -2, "_G");
int i;
/* open lib into global table */
lua_pushglobaltable(L);
luaL_setfuncs(L, base_funcs, 0);
/* set global _G */
lua_pushvalue(L, -1);
lua_setfield(L, -2, "_G");
/* set global _VERSION */
lua_pushliteral(L, LUA_VERSION);
lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
lua_setfield(L, -2, "_VERSION");
/* set function 'type' with proper upvalues */
for (i = 0; i < LUA_NUMTAGS; i++) /* push all type names as upvalues */
lua_pushstring(L, lua_typename(L, i));
lua_pushcclosure(L, luaB_type, LUA_NUMTAGS);
lua_setfield(L, -2, "type");
return 1;
}

View File

@ -1,7 +1,5 @@
/* $NetBSD: lbitlib.c,v 1.1.1.2 2015/02/02 02:01:06 lneto Exp $ */
/*
** Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp
** $Id: lbitlib.c,v 1.2 2015/02/02 14:03:05 lneto Exp $
** Standard library for bitwise operations
** See Copyright Notice in lua.h
*/

View File

@ -1,20 +1,22 @@
/* $NetBSD: lcode.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lcode.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lcode.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lcode.c,v 2.99 2014/12/29 16:49:25 roberto Exp
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#define lcode_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <math.h>
#include <stdlib.h>
#endif
#define lcode_c
#define LUA_CORE
#include "lua.h"
#include "lcode.h"
@ -31,12 +33,8 @@
#include "lvm.h"
/* test for x == -0 */
#if defined(signbit)
#define isminuszero(x) ((x) == 0.0 && signbit(x))
#else
#define isminuszero(x) ((x) == 0.0 && 1.0/(x) < 0.0)
#endif
/* Maximum number of registers in a Lua function */
#define MAXREGS 250
#define hasjumps(e) ((e)->t != (e)->f)
@ -113,7 +111,7 @@ static void fixjump (FuncState *fs, int pc, int dest) {
/*
** returns current `pc' and marks it as a jump target (to avoid wrong
** returns current 'pc' and marks it as a jump target (to avoid wrong
** optimizations with consecutive instructions not in the same basic block).
*/
int luaK_getlabel (FuncState *fs) {
@ -236,7 +234,7 @@ void luaK_concat (FuncState *fs, int *l1, int l2) {
static int luaK_code (FuncState *fs, Instruction i) {
Proto *f = fs->f;
dischargejpc(fs); /* `pc' will change */
dischargejpc(fs); /* 'pc' will change */
/* put new instruction in code array */
luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
MAX_INT, "opcodes");
@ -286,7 +284,7 @@ int luaK_codek (FuncState *fs, int reg, int k) {
void luaK_checkstack (FuncState *fs, int n) {
int newstack = fs->freereg + n;
if (newstack > fs->f->maxstacksize) {
if (newstack >= MAXSTACK)
if (newstack >= MAXREGS)
luaX_syntaxerror(fs->ls, "function or expression too complex");
fs->f->maxstacksize = cast_byte(newstack);
}
@ -365,14 +363,8 @@ int luaK_intK (FuncState *fs, lua_Integer n) {
#ifndef _KERNEL
/*
** Both NaN and -0.0 should not go to the constant table, as they have
** problems with the hashing. (NaN is not a valid key, -0.0 collides
** with +0.0.)
*/
static int luaK_numberK (FuncState *fs, lua_Number r) {
TValue o;
lua_assert(!luai_numisnan(r) && !isminuszero(r));
setfltvalue(&o, r);
return addk(fs, &o, &o);
}
@ -513,7 +505,7 @@ static void discharge2anyreg (FuncState *fs, expdesc *e) {
static void exp2reg (FuncState *fs, expdesc *e, int reg) {
discharge2reg(fs, e, reg);
if (e->k == VJMP)
luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */
luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
if (hasjumps(e)) {
int final; /* position after whole expression */
int p_f = NO_JUMP; /* position of an eventual LOAD false */
@ -597,7 +589,7 @@ int luaK_exp2RK (FuncState *fs, expdesc *e) {
#endif
case VK: {
vk:
if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */
if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */
return RKASK(e->u.info);
else break;
}
@ -693,7 +685,7 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) {
break;
}
}
luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */
luaK_concat(fs, &e->f, pc); /* insert last jump in 'f' list */
luaK_patchtohere(fs, e->t);
e->t = NO_JUMP;
}
@ -716,7 +708,7 @@ void luaK_goiffalse (FuncState *fs, expdesc *e) {
break;
}
}
luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */
luaK_concat(fs, &e->t, pc); /* insert last jump in 't' list */
luaK_patchtohere(fs, e->f);
e->f = NO_JUMP;
}
@ -775,20 +767,18 @@ void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
** return false if folding can raise an error
*/
static int validop (int op, TValue *v1, TValue *v2) {
lua_Number a, b;
lua_Integer i;
cast_void(a); cast_void(b); /* macro may not use its arguments */
if (luai_numinvalidop(op, (cast_void(tonumber(v1, &a)), a),
(cast_void(tonumber(v2, &b)), b)))
return 0;
switch (op) {
case LUA_OPIDIV: /* division by 0 and conversion errors */
return (tointeger(v1, &i) && tointeger(v2, &i) && i != 0);
case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: /* conversion errors */
case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
lua_Integer i;
return (tointeger(v1, &i) && tointeger(v2, &i));
case LUA_OPMOD: /* integer module by 0 */
return !(ttisinteger(v1) && ttisinteger(v2) && ivalue(v2) == 0);
}
#ifndef _KERNEL
case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
#else /* _KERNEL */
case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
#endif
return (nvalue(v2) != 0);
default: return 1; /* everything else is valid */
}
}
@ -801,39 +791,50 @@ static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
TValue v1, v2, res;
if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
return 0; /* non-numeric operands or not safe to fold */
luaO_arith(fs->ls->L, op, &v1, &v2, &res);
luaO_arith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
if (ttisinteger(&res)) {
e1->k = VKINT;
e1->u.ival = ivalue(&res);
}
else {
else { /* folds neither NaN nor 0.0 (to avoid collapsing with -0.0) */
#ifndef _KERNEL
lua_Number n = fltvalue(&res);
if (luai_numisnan(n) || isminuszero(n))
return 0; /* folds neither NaN nor -0 */
if (luai_numisnan(n) || n == 0)
return 0;
e1->k = VKFLT;
e1->u.nval = n;
#else
return 0;
#else /* _KERNEL */
return 0; /* if it is not integer, we must fail */
#endif
}
return 1;
}
static void codearith (FuncState *fs, OpCode op,
expdesc *e1, expdesc *e2, int line) {
if (!constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2)) {
/*
** Code for binary and unary expressions that "produce values"
** (arithmetic operations, bitwise operations, concat, length). First
** try to do constant folding (only for numeric [arithmetic and
** bitwise] operations, which is what 'lua_arith' accepts).
** Expression to produce final result will be encoded in 'e1'.
*/
static void codeexpval (FuncState *fs, OpCode op,
expdesc *e1, expdesc *e2, int line) {
lua_assert(op >= OP_ADD);
if (op <= OP_BNOT && constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2))
return; /* result has been folded */
else {
int o1, o2;
if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) {
o2 = 0;
/* move operands to registers (if needed) */
if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) { /* unary op? */
o2 = 0; /* no second expression */
o1 = luaK_exp2anyreg(fs, e1); /* cannot operate on constants */
}
else { /* regular case (binary operators) */
o2 = luaK_exp2RK(fs, e2);
o2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */
o1 = luaK_exp2RK(fs, e1);
}
if (o1 > o2) {
if (o1 > o2) { /* free registers in proper order */
freeexp(fs, e1);
freeexp(fs, e2);
}
@ -841,8 +842,8 @@ static void codearith (FuncState *fs, OpCode op,
freeexp(fs, e2);
freeexp(fs, e1);
}
e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);
e1->k = VRELOCABLE;
e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); /* generate opcode */
e1->k = VRELOCABLE; /* all those operations are relocable */
luaK_fixline(fs, line);
}
}
@ -855,7 +856,7 @@ static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
freeexp(fs, e2);
freeexp(fs, e1);
if (cond == 0 && op != OP_EQ) {
int temp; /* exchange args to replace by `<' or `<=' */
int temp; /* exchange args to replace by '<' or '<=' */
temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */
cond = 1;
}
@ -869,7 +870,7 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
switch (op) {
case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
codearith(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
break;
}
case OPR_NOT: codenot(fs, e); break;
@ -889,7 +890,7 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
break;
}
case OPR_CONCAT: {
luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */
luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */
break;
}
case OPR_ADD: case OPR_SUB:
@ -940,7 +941,7 @@ void luaK_posfix (FuncState *fs, BinOpr op,
}
else {
luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */
codearith(fs, OP_CONCAT, e1, e2, line);
codeexpval(fs, OP_CONCAT, e1, e2, line);
}
break;
}
@ -953,7 +954,7 @@ void luaK_posfix (FuncState *fs, BinOpr op,
#endif
case OPR_BAND: case OPR_BOR: case OPR_BXOR:
case OPR_SHL: case OPR_SHR: {
codearith(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
break;
}
case OPR_EQ: case OPR_LT: case OPR_LE: {

View File

@ -1,7 +1,7 @@
/* $NetBSD: lcode.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lcode.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lcode.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lcode.h,v 1.63 2013/12/30 20:47:58 roberto Exp
** Code generator for Lua
** See Copyright Notice in lua.h
*/
@ -29,7 +29,7 @@ typedef enum BinOpr {
#ifndef _KERNEL
OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
OPR_DIV,
#else
#else /* _KERNEL */
OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD,
#endif
OPR_IDIV,

View File

@ -1,4 +1,4 @@
/* $NetBSD: lcorolib.c,v 1.1.1.2 2015/02/02 02:01:08 lneto Exp $ */
/* $NetBSD: lcorolib.c,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
** Id: lcorolib.c,v 1.9 2014/11/02 19:19:04 roberto Exp
@ -12,7 +12,9 @@
#include "lprefix.h"
#ifndef _KERNEL
#include <stdlib.h>
#endif
#include "lua.h"

View File

@ -1,4 +1,4 @@
/* $NetBSD: lctype.c,v 1.1.1.2 2015/02/02 02:01:11 lneto Exp $ */
/* $NetBSD: lctype.c,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
** Id: lctype.c,v 1.12 2014/11/02 19:19:04 roberto Exp
@ -16,7 +16,9 @@
#if !LUA_USE_CTYPE /* { */
#ifndef _KERNEL
#include <limits.h>
#endif
LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
0x00, /* EOZ */

View File

@ -1,4 +1,4 @@
/* $NetBSD: lctype.h,v 1.1.1.1 2014/07/20 23:17:33 lneto Exp $ */
/* $NetBSD: lctype.h,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
** Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp
@ -33,7 +33,9 @@
#if !LUA_USE_CTYPE /* { */
#ifndef _KERNEL
#include <limits.h>
#endif
#include "llimits.h"

View File

@ -1,11 +1,16 @@
/* $NetBSD: ldblib.c,v 1.4 2014/07/19 19:37:31 lneto Exp $ */
/* $NetBSD: ldblib.c,v 1.5 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ldblib.c,v 1.4 2014/07/19 19:37:31 lneto Exp $
** Id: ldblib.c,v 1.148 2015/01/02 12:52:22 roberto Exp
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
#define ldblib_c
#define LUA_LIB
#include "lprefix.h"
#ifndef _KERNEL
#include <stdio.h>
@ -13,43 +18,17 @@
#include <string.h>
#endif
#define ldblib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#define HOOKKEY "_HKEY"
static int db_Csize (lua_State *L) {
static struct {
char c;
unsigned char sz;
} sizes[] = {
{'I', sizeof(lua_Integer)},
{'F', sizeof(lua_Number)},
{'b', CHAR_BIT}, /* here is number of bits (not bytes) */
{'h', sizeof(short)},
{'i', sizeof(int)},
{'l', sizeof(long)},
{'z', sizeof(size_t)},
{'f', sizeof(float)},
{'d', sizeof(double)}
};
const char *s = luaL_checkstring(L, 1);
int i;
for (i = 0; i < (int)(sizeof(sizes)/sizeof(sizes[0])); i++) {
if (*s == sizes[i].c) {
lua_pushinteger(L, sizes[i].sz);
return 1;
}
}
return luaL_argerror(L, 1, lua_pushfstring(L, "invalid option '%c'", *s));
}
/*
** The hook table at registry[&HOOKKEY] maps threads to their current
** hook function. (We only need the unique address of 'HOOKKEY'.)
*/
static const int HOOKKEY = 0;
static int db_getregistry (lua_State *L) {
@ -164,7 +143,7 @@ static int db_getinfo (lua_State *L) {
lua_xmove(L, L1, 1);
}
else { /* stack level */
if (!lua_getstack(L1, luaL_checkint(L, arg + 1), &ar)) {
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
lua_pushnil(L); /* level out of range */
return 1;
}
@ -205,14 +184,15 @@ static int db_getlocal (lua_State *L) {
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
const char *name;
int nvar = luaL_checkint(L, arg+2); /* local-variable index */
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
if (lua_isfunction(L, arg + 1)) { /* function argument? */
lua_pushvalue(L, arg + 1); /* push function */
lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */
return 1; /* return only name (there is no value) */
}
else { /* stack-level argument */
if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */
int level = (int)luaL_checkinteger(L, arg + 1);
if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
name = lua_getlocal(L1, &ar, nvar);
if (name) {
@ -231,14 +211,20 @@ static int db_getlocal (lua_State *L) {
static int db_setlocal (lua_State *L) {
int arg;
const char *name;
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */
int level = (int)luaL_checkinteger(L, arg + 1);
int nvar = (int)luaL_checkinteger(L, arg + 2);
if (!lua_getstack(L1, level, &ar)) /* 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)));
name = lua_setlocal(L1, &ar, nvar);
if (name == NULL)
lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */
lua_pushstring(L, name);
return 1;
}
@ -248,7 +234,7 @@ static int db_setlocal (lua_State *L) {
*/
static int auxupvalue (lua_State *L, int get) {
const char *name;
int n = luaL_checkint(L, 2); /* upvalue index */
int n = (int)luaL_checkinteger(L, 2); /* upvalue index */
luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */
name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
if (name == NULL) return 0;
@ -274,7 +260,7 @@ static int db_setupvalue (lua_State *L) {
** returns its index
*/
static int checkupval (lua_State *L, int argf, int argnup) {
int nup = luaL_checkint(L, argnup); /* upvalue index */
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
"invalid upvalue index");
@ -299,13 +285,6 @@ static int db_upvaluejoin (lua_State *L) {
}
/*
** The hook table (at registry[HOOKKEY]) maps threads to their current
** hook function
*/
#define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)
/*
** Call hook function registered at hook table for the current
** thread (if there is one)
@ -313,7 +292,7 @@ static int db_upvaluejoin (lua_State *L) {
static void hookf (lua_State *L, lua_Debug *ar) {
static const char *const hooknames[] =
{"call", "return", "line", "count", "tail call"};
gethooktable(L);
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L);
if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
@ -363,19 +342,22 @@ static int db_sethook (lua_State *L) {
else {
const char *smask = luaL_checkstring(L, arg+2);
luaL_checktype(L, arg+1, LUA_TFUNCTION);
count = luaL_optint(L, arg+3, 0);
count = (int)luaL_optinteger(L, arg + 3, 0);
func = hookf; mask = makemask(smask, count);
}
if (gethooktable(L) == 0) { /* creating hook table? */
if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
lua_createtable(L, 0, 2); /* create a hook table */
lua_pushvalue(L, -1);
lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */
lua_pushstring(L, "k");
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
lua_pushvalue(L, -1);
lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
}
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key */
lua_pushvalue(L, arg+1); /* value */
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
lua_pushvalue(L, arg + 1); /* value (hook function) */
lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
lua_sethook(L1, func, mask, count); /* set hooks */
lua_sethook(L1, func, mask, count);
return 0;
}
@ -386,10 +368,12 @@ static int db_gethook (lua_State *L) {
char buff[5];
int mask = lua_gethookmask(L1);
lua_Hook hook = lua_gethook(L1);
if (hook != NULL && hook != hookf) /* external hook? */
if (hook == NULL) /* no hook? */
lua_pushnil(L);
else if (hook != hookf) /* external hook? */
lua_pushliteral(L, "external hook");
else {
gethooktable(L);
else { /* hook table must exist */
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L1); lua_xmove(L1, L, 1);
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
lua_remove(L, -2); /* remove hook table */
@ -404,13 +388,13 @@ static int db_gethook (lua_State *L) {
static int db_debug (lua_State *L) {
for (;;) {
char buffer[250];
luai_writestringerror("%s", "lua_debug> ");
lua_writestringerror("%s", "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
strcmp(buffer, "cont\n") == 0)
return 0;
if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
lua_pcall(L, 0, 0, 0))
luai_writestringerror("%s\n", lua_tostring(L, -1));
lua_writestringerror("%s\n", lua_tostring(L, -1));
lua_settop(L, 0); /* remove eventual returns */
}
}
@ -424,7 +408,7 @@ static int db_traceback (lua_State *L) {
if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */
lua_pushvalue(L, arg + 1); /* return it untouched */
else {
int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0);
int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
luaL_traceback(L, L1, msg, level);
}
return 1;
@ -432,7 +416,6 @@ static int db_traceback (lua_State *L) {
static const luaL_Reg dblib[] = {
{"Csize", db_Csize},
#ifndef _KERNEL
{"debug", db_debug},
#endif

View File

@ -1,11 +1,16 @@
/* $NetBSD: ldebug.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ldebug.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ldebug.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ldebug.c,v 2.110 2015/01/02 12:52:22 roberto Exp
** Debug Interface
** See Copyright Notice in lua.h
*/
#define ldebug_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stdarg.h>
@ -13,10 +18,6 @@
#include <string.h>
#endif
#define ldebug_c
#define LUA_CORE
#include "lua.h"
#include "lapi.h"
@ -170,9 +171,10 @@ LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
StkId pos = 0; /* to avoid warnings */
const char *name = findlocal(L, ar->i_ci, n, &pos);
lua_lock(L);
if (name)
if (name) {
setobjs2s(L, pos, L->top - 1);
L->top--; /* pop value */
L->top--; /* pop value */
}
lua_unlock(L);
return name;
}
@ -275,7 +277,7 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
if (*what == '>') {
ci = NULL;
func = L->top - 1;
api_check(L, ttisfunction(func), "function expected");
api_check(ttisfunction(func), "function expected");
what++; /* skip the '>' */
L->top--; /* pop function */
}
@ -369,7 +371,7 @@ static int findsetreg (Proto *p, int lastpc, int reg) {
case OP_JMP: {
int b = GETARG_sBx(i);
int dest = pc + 1 + b;
/* jump is forward and do not skip `lastpc'? */
/* jump is forward and do not skip 'lastpc'? */
if (pc < dest && dest <= lastpc) {
if (dest > jmptarget)
jmptarget = dest; /* update 'jmptarget' */
@ -441,10 +443,14 @@ static const char *getobjname (Proto *p, int lastpc, int reg,
static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
TMS tm;
TMS tm = (TMS)0; /* to avoid warnings */
Proto *p = ci_func(ci)->p; /* calling function */
int pc = currentpc(ci); /* calling instruction index */
Instruction i = p->code[pc]; /* calling instruction */
if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
*name = "?";
return "hook";
}
switch (GET_OPCODE(i)) {
case OP_CALL:
case OP_TAILCALL: /* get function name */
@ -454,30 +460,31 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
return "for iterator";
}
/* all other instructions can call only through metamethods */
case OP_SELF:
case OP_GETTABUP:
case OP_GETTABLE: tm = TM_INDEX; break;
case OP_SETTABUP:
case OP_SETTABLE: tm = TM_NEWINDEX; break;
case OP_EQ: tm = TM_EQ; break;
case OP_ADD: tm = TM_ADD; break;
case OP_SUB: tm = TM_SUB; break;
case OP_MUL: tm = TM_MUL; break;
case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
tm = TM_INDEX;
break;
case OP_SETTABUP: case OP_SETTABLE:
tm = TM_NEWINDEX;
break;
case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:
#ifndef _KERNEL
case OP_DIV: tm = TM_DIV; break;
#endif
case OP_IDIV: tm = TM_IDIV; break;
case OP_MOD: tm = TM_MOD; break;
#ifndef _KERNEL
case OP_POW: tm = TM_POW; break;
case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:
#else /* _KERNEL */
case OP_IDIV: case OP_BAND:
#endif
case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {
int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */
tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */
break;
}
case OP_UNM: tm = TM_UNM; break;
case OP_BNOT: tm = TM_BNOT; break;
case OP_LEN: tm = TM_LEN; break;
case OP_CONCAT: tm = TM_CONCAT; break;
case OP_EQ: tm = TM_EQ; break;
case OP_LT: tm = TM_LT; break;
case OP_LE: tm = TM_LE; break;
case OP_CONCAT: tm = TM_CONCAT; break;
default:
return NULL; /* else no useful name can be found */
default: lua_assert(0); /* other instructions cannot call a function */
}
*name = getstr(G(L)->tmname[tm]);
return "metamethod";
@ -488,17 +495,21 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
/*
** only ANSI way to check whether a pointer points to an array
** (used only for error messages, so efficiency is not a big concern)
** The subtraction of two potentially unrelated pointers is
** not ISO C, but it should not crash a program; the subsequent
** checks are ISO C and ensure a correct result.
*/
static int isinstack (CallInfo *ci, const TValue *o) {
StkId p;
for (p = ci->u.l.base; p < ci->top; p++)
if (o == p) return 1;
return 0;
ptrdiff_t i = o - ci->u.l.base;
return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);
}
/*
** Checks whether value 'o' came from an upvalue. (That can only happen
** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
** upvalues.)
*/
static const char *getupvalname (CallInfo *ci, const TValue *o,
const char **name) {
LClosure *c = ci_func(ci);
@ -514,7 +525,7 @@ static const char *getupvalname (CallInfo *ci, const TValue *o,
static const char *varinfo (lua_State *L, const TValue *o) {
const char *name;
const char *name = NULL; /* to avoid warnings */
CallInfo *ci = L->ci;
const char *kind = NULL;
if (isLua(ci)) {
@ -523,7 +534,7 @@ static const char *varinfo (lua_State *L, const TValue *o) {
kind = getobjname(ci_func(ci)->p, currentpc(ci),
cast_int(o - ci->u.l.base), &name);
}
return (kind) ? luaO_pushfstring(L, " (%s " LUA_QS ")", kind, name) : "";
return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
}
@ -534,26 +545,28 @@ l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
lua_assert(!ttisstring(p1) && !ttisnumber(p1));
if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
luaG_typeerror(L, p1, "concatenate");
}
l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
l_noret luaG_opinterror (lua_State *L, const TValue *p1,
const TValue *p2, const char *msg) {
lua_Number temp;
if (!tonumber(p1, &temp))
p2 = p1; /* first operand is wrong */
luaG_typeerror(L, p2, "perform arithmetic on");
if (!tonumber(p1, &temp)) /* first operand is wrong? */
p2 = p1; /* now second is wrong */
luaG_typeerror(L, p2, msg);
}
/*
** Error when both values are convertible to numbers, but not to integers
*/
l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
lua_Integer temp;
if (!tointeger(p1, &temp))
p2 = p1;
luaG_runerror(L, "attempt to convert an out of range float%s to an integer",
varinfo(L, p2));
luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
}
@ -586,10 +599,9 @@ static void addinfo (lua_State *L, const char *msg) {
l_noret 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 */
L->top++;
L->top++; /* assume EXTRA_STACK */
luaD_call(L, L->top - 2, 1, 0); /* call it */
}
luaD_throw(L, LUA_ERRRUN);

View File

@ -1,7 +1,5 @@
/* $NetBSD: ldebug.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: ldebug.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: ldebug.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Auxiliary functions from Debug Interface module
** See Copyright Notice in lua.h
*/
@ -27,8 +25,9 @@ LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
const char *opname);
LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
const TValue *p2);
LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1,
const TValue *p2);
LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,
const TValue *p2,
const char *msg);
LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,
const TValue *p2);
LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,

View File

@ -1,11 +1,16 @@
/* $NetBSD: ldo.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ldo.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ldo.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ldo.c,v 2.135 2014/11/11 17:13:39 roberto Exp
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
#define ldo_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <setjmp.h>
@ -13,9 +18,6 @@
#include <string.h>
#endif
#define ldo_c
#define LUA_CORE
#include "lua.h"
#include "lapi.h"
@ -71,7 +73,7 @@
#else /* }{ */
/* ANSI handling with long jumps */
/* ISO C handling with long jumps */
#define LUAI_THROW(L,c) longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf
@ -115,15 +117,19 @@ l_noret luaD_throw (lua_State *L, int errcode) {
LUAI_THROW(L, L->errorJmp); /* jump to it */
}
else { /* thread has no error handler */
global_State *g = G(L);
L->status = cast_byte(errcode); /* mark it as dead */
if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */
setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */
luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */
if (g->mainthread->errorJmp) { /* main thread has a handler? */
setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
}
else { /* no handler at all; abort */
if (G(L)->panic) { /* panic function? */
if (g->panic) { /* panic function? */
seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
if (L->ci->top < L->top)
L->ci->top = L->top; /* pushing msg. can break this invariant */
lua_unlock(L);
G(L)->panic(L); /* call it (last chance to jump out) */
g->panic(L); /* call panic function (last chance to jump out) */
}
abort();
}
@ -284,18 +290,21 @@ static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
}
static StkId tryfuncTM (lua_State *L, StkId func) {
/*
** Check whether __call metafield of 'func' is a function. If so, put
** it in stack below original 'func' so that 'luaD_precall' can call
** it. Raise an error if __call metafield is not a function.
*/
static void tryfuncTM (lua_State *L, StkId func) {
const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
StkId p;
ptrdiff_t funcr = savestack(L, func);
if (!ttisfunction(tm))
luaG_typeerror(L, func, "call");
/* Open a hole inside the stack at `func' */
for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
incr_top(L);
func = restorestack(L, funcr); /* previous call may change stack */
/* Open a hole inside the stack at 'func' */
for (p = L->top; p > func; p--)
setobjs2s(L, p, p-1);
L->top++; /* slot ensured by caller */
setobj2s(L, func, tm); /* tag method is the new function to be called */
return func;
}
@ -365,7 +374,9 @@ int luaD_precall (lua_State *L, StkId func, int nresults) {
return 0;
}
default: { /* not a function */
func = tryfuncTM(L, func); /* retry with 'function' tag method */
luaD_checkstack(L, 1); /* ensure space for metamethod */
func = restorestack(L, funcr); /* previous call may change stack */
tryfuncTM(L, func); /* try to get '__call' metamethod */
return luaD_precall(L, func, nresults); /* now it must be a function */
}
}
@ -520,7 +531,7 @@ static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
/*
** Do the work for 'lua_resume' in protected mode. Most of the work
** depends on the status of the coroutine: initial state, suspended
** inside a hook, or regulary suspended (optionally with a continuation
** inside a hook, or regularly suspended (optionally with a continuation
** function), plus erroneous cases: non-suspended coroutine or dead
** coroutine.
*/
@ -578,7 +589,7 @@ LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
status = luaD_rawrunprotected(L, unroll, &status);
}
if (errorstatus(status)) { /* unrecoverable error? */
L->status = cast_byte(status); /* mark thread as `dead' */
L->status = cast_byte(status); /* mark thread as 'dead' */
seterrorobj(L, status, L->top); /* push error message */
L->ci->top = L->top;
}
@ -597,7 +608,8 @@ LUA_API int lua_isyieldable (lua_State *L) {
}
LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_KFunction k) {
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
lua_KFunction k) {
CallInfo *ci = L->ci;
luai_userstateyield(L, nresults);
lua_lock(L);
@ -611,7 +623,7 @@ LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_KFunction k) {
L->status = LUA_YIELD;
ci->extra = savestack(L, ci->func); /* save current 'func' */
if (isLua(ci)) { /* inside a hook? */
api_check(L, k == NULL, "hooks cannot continue after yielding");
api_check(k == NULL, "hooks cannot continue after yielding");
}
else {
if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
@ -652,7 +664,7 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u,
/*
** Execute a protected parser.
*/
struct SParser { /* data to `f_parser' */
struct SParser { /* data to 'f_parser' */
ZIO *z;
Mbuffer buff; /* dynamic structure used by the scanner */
Dyndata dyd; /* dynamic structures used by the parser */
@ -664,7 +676,7 @@ struct SParser { /* data to `f_parser' */
static void checkmode (lua_State *L, const char *mode, const char *x) {
if (mode && strchr(mode, x[0]) == NULL) {
luaO_pushfstring(L,
"attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
"attempt to load a %s chunk (mode is '%s')", x, mode);
luaD_throw(L, LUA_ERRSYNTAX);
}
}

View File

@ -1,7 +1,5 @@
/* $NetBSD: ldo.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: ldo.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: ldo.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
@ -25,7 +23,7 @@
#define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))
/* type of protected functions, to be ran by `runprotected' */
/* type of protected functions, to be ran by 'runprotected' */
typedef void (*Pfunc) (lua_State *L, void *ud);
LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,

View File

@ -1,18 +1,21 @@
/* $NetBSD: ldump.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ldump.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ldump.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ldump.c,v 2.34 2014/11/02 19:19:04 roberto Exp
** save precompiled Lua chunks
** See Copyright Notice in lua.h
*/
#define ldump_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stddef.h>
#endif
#define ldump_c
#define LUA_CORE
#include "lua.h"
#include "lobject.h"
@ -75,7 +78,7 @@ static void DumpString (const TString *s, DumpState *D) {
if (s == NULL)
DumpByte(0, D);
else {
size_t size = s->tsv.len + 1; /* include trailing '\0' */
size_t size = s->len + 1; /* include trailing '\0' */
if (size < 0xFF)
DumpByte(cast_int(size), D);
else {
@ -118,7 +121,7 @@ static void DumpConstants (const Proto *f, DumpState *D) {
break;
case LUA_TSHRSTR:
case LUA_TLNGSTR:
DumpString(rawtsvalue(o), D);
DumpString(tsvalue(o), D);
break;
default:
lua_assert(0);

View File

@ -1,19 +1,21 @@
/* $NetBSD: lfunc.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lfunc.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lfunc.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
#define lfunc_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stddef.h>
#endif
#define lfunc_c
#define LUA_CORE
#include "lua.h"
#include "lfunc.h"
@ -86,7 +88,7 @@ void luaF_close (lua_State *L, StkId level) {
UpVal *uv;
while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
lua_assert(upisopen(uv));
L->openupval = uv->u.open.next; /* remove from `open' list */
L->openupval = uv->u.open.next; /* remove from 'open' list */
if (uv->refcount == 0) /* no references? */
luaM_free(L, uv); /* free upvalue */
else {
@ -136,7 +138,7 @@ void luaF_freeproto (lua_State *L, Proto *f) {
/*
** Look for n-th local variable at line `line' in function `func'.
** Look for n-th local variable at line 'line' in function 'func'.
** Returns NULL if not found.
*/
const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {

View File

@ -1,18 +1,21 @@
/* $NetBSD: lgc.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lgc.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lgc.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lgc.c,v 2.201 2014/12/20 13:58:15 roberto Exp
** Garbage Collector
** See Copyright Notice in lua.h
*/
#define lgc_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define lgc_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -66,10 +69,10 @@
*/
#define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
#define makewhite(g,x) \
(gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
(x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
#define white2gray(x) resetbits(gch(x)->marked, WHITEBITS)
#define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)
#define white2gray(x) resetbits(x->marked, WHITEBITS)
#define black2gray(x) resetbit(x->marked, BLACKBIT)
#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
@ -85,7 +88,7 @@
if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
#define markobject(g,t) \
{ if ((t) && iswhite(obj2gco(t))) reallymarkobject(g, obj2gco(t)); }
{ if ((t) && iswhite(t)) reallymarkobject(g, obj2gco(t)); }
static void reallymarkobject (global_State *g, GCObject *o);
@ -104,9 +107,9 @@ static void reallymarkobject (global_State *g, GCObject *o);
/*
** link table 'h' into list pointed by 'p'
** link collectable object 'o' into list pointed by 'p'
*/
#define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h))
#define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
/*
@ -116,21 +119,21 @@ static void reallymarkobject (global_State *g, GCObject *o);
static void removeentry (Node *n) {
lua_assert(ttisnil(gval(n)));
if (valiswhite(gkey(n)))
setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */
setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */
}
/*
** tells whether a key or value can be cleared from a weak
** table. Non-collectable objects are never removed from weak
** tables. Strings behave as `values', so are never removed too. for
** tables. Strings behave as 'values', so are never removed too. for
** other objects: if really collected, cannot keep them; for objects
** being finalized, keep them in keys, but not in values
*/
static int iscleared (global_State *g, const TValue *o) {
if (!iscollectable(o)) return 0;
else if (ttisstring(o)) {
markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */
markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */
return 0;
}
else return iswhite(gcvalue(o));
@ -139,13 +142,13 @@ static int iscleared (global_State *g, const TValue *o) {
/*
** barrier that moves collector forward, that is, mark the white object
** being pointed by a black object.
** being pointed by a black object. (If in sweep phase, clear the black
** object to white [sweep it] to avoid other barrier calls for this
** same object.)
*/
void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
global_State *g = G(L);
lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
lua_assert(g->gcstate != GCSpause);
lua_assert(gch(o)->tt != LUA_TTABLE); /* tables use a back barrier */
if (keepinvariant(g)) /* must keep invariant? */
reallymarkobject(g, v); /* restore invariant */
else { /* sweep phase */
@ -157,16 +160,13 @@ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
/*
** barrier that moves collector backward, that is, mark the black object
** pointing to a white object as gray again. (Current implementation
** only works for tables; access to 'gclist' is not uniform across
** different types.)
** pointing to a white object as gray again.
*/
void luaC_barrierback_ (lua_State *L, GCObject *o) {
void luaC_barrierback_ (lua_State *L, Table *t) {
global_State *g = G(L);
lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE);
black2gray(o); /* make object gray (again) */
gco2t(o)->gclist = g->grayagain;
g->grayagain = o;
lua_assert(isblack(t) && !isdead(g, t));
black2gray(t); /* make table gray (again) */
linkgclist(t, g->grayagain);
}
@ -189,8 +189,8 @@ void luaC_fix (lua_State *L, GCObject *o) {
global_State *g = G(L);
lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
white2gray(o); /* they will be gray forever */
g->allgc = o->gch.next; /* remove object from 'allgc' list */
o->gch.next = g->fixedgc; /* link it to 'fixedgc' list */
g->allgc = o->next; /* remove object from 'allgc' list */
o->next = g->fixedgc; /* link it to 'fixedgc' list */
g->fixedgc = o;
}
@ -202,9 +202,9 @@ void luaC_fix (lua_State *L, GCObject *o) {
GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
global_State *g = G(L);
GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
gch(o)->marked = luaC_white(g);
gch(o)->tt = tt;
gch(o)->next = g->allgc;
o->marked = luaC_white(g);
o->tt = tt;
o->next = g->allgc;
g->allgc = o;
return o;
}
@ -229,7 +229,7 @@ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
static void reallymarkobject (global_State *g, GCObject *o) {
reentry:
white2gray(o);
switch (gch(o)->tt) {
switch (o->tt) {
case LUA_TSHRSTR:
case LUA_TLNGSTR: {
gray2black(o);
@ -241,7 +241,7 @@ static void reallymarkobject (global_State *g, GCObject *o) {
markobject(g, gco2u(o)->metatable); /* mark its metatable */
gray2black(o);
g->GCmemtrav += sizeudata(gco2u(o));
getuservalue(g->mainthread, rawgco2u(o), &uvalue);
getuservalue(g->mainthread, gco2u(o), &uvalue);
if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
o = gcvalue(&uvalue);
goto reentry;
@ -249,27 +249,23 @@ static void reallymarkobject (global_State *g, GCObject *o) {
break;
}
case LUA_TLCL: {
gco2lcl(o)->gclist = g->gray;
g->gray = o;
linkgclist(gco2lcl(o), g->gray);
break;
}
case LUA_TCCL: {
gco2ccl(o)->gclist = g->gray;
g->gray = o;
linkgclist(gco2ccl(o), g->gray);
break;
}
case LUA_TTABLE: {
linktable(gco2t(o), &g->gray);
linkgclist(gco2t(o), g->gray);
break;
}
case LUA_TTHREAD: {
gco2th(o)->gclist = g->gray;
g->gray = o;
linkgclist(gco2th(o), g->gray);
break;
}
case LUA_TPROTO: {
gco2p(o)->gclist = g->gray;
g->gray = o;
linkgclist(gco2p(o), g->gray);
break;
}
default: lua_assert(0); break;
@ -292,7 +288,7 @@ static void markmt (global_State *g) {
*/
static void markbeingfnz (global_State *g) {
GCObject *o;
for (o = g->tobefnz; o != NULL; o = gch(o)->next)
for (o = g->tobefnz; o != NULL; o = o->next)
markobject(g, o);
}
@ -307,8 +303,8 @@ static void remarkupvals (global_State *g) {
lua_State *thread;
lua_State **p = &g->twups;
while ((thread = *p) != NULL) {
lua_assert(!isblack(obj2gco(thread))); /* threads are never black */
if (isgray(obj2gco(thread)) && thread->openupval != NULL)
lua_assert(!isblack(thread)); /* threads are never black */
if (isgray(thread) && thread->openupval != NULL)
p = &thread->twups; /* keep marked thread with upvalues in the list */
else { /* thread is not marked or without upvalues */
UpVal *uv;
@ -346,12 +342,18 @@ static void restartcollection (global_State *g) {
** =======================================================
*/
/*
** Traverse a table with weak values and link it to proper list. During
** propagate phase, keep it in 'grayagain' list, to be revisited in the
** atomic phase. In the atomic phase, if table has any white value,
** put it in 'weak' list, to be cleared.
*/
static void traverseweakvalue (global_State *g, Table *h) {
Node *n, *limit = gnodelast(h);
/* if there is array part, assume it may have white values (do not
traverse it just to check) */
/* if there is array part, assume it may have white values (it is not
worth traversing it now just to check) */
int hasclears = (h->sizearray > 0);
for (n = gnode(h, 0); n < limit; n++) {
for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */
removeentry(n); /* remove it */
@ -362,20 +364,30 @@ static void traverseweakvalue (global_State *g, Table *h) {
hasclears = 1; /* table will have to be cleared */
}
}
if (hasclears)
linktable(h, &g->weak); /* has to be cleared later */
else /* no white values */
linktable(h, &g->grayagain); /* no need to clean */
if (g->gcstate == GCSpropagate)
linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
else if (hasclears)
linkgclist(h, g->weak); /* has to be cleared later */
}
/*
** Traverse an ephemeron table and link it to proper list. Returns true
** iff any object was marked during this traversal (which implies that
** convergence has to continue). During propagation phase, keep table
** in 'grayagain' list, to be visited again in the atomic phase. In
** the atomic phase, if table has any white->white entry, it has to
** be revisited during ephemeron convergence (as that key may turn
** black). Otherwise, if it has any white key, table has to be cleared
** (in the atomic phase).
*/
static int traverseephemeron (global_State *g, Table *h) {
int marked = 0; /* true if an object is marked in this traversal */
int hasclears = 0; /* true if table has white keys */
int prop = 0; /* true if table has entry "white-key -> white-value" */
int hasww = 0; /* true if table has entry "white-key -> white-value" */
Node *n, *limit = gnodelast(h);
int i;
/* traverse array part (numeric keys are 'strong') */
unsigned int i;
/* traverse array part */
for (i = 0; i < h->sizearray; i++) {
if (valiswhite(&h->array[i])) {
marked = 1;
@ -390,26 +402,27 @@ static int traverseephemeron (global_State *g, Table *h) {
else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
hasclears = 1; /* table must be cleared */
if (valiswhite(gval(n))) /* value not marked yet? */
prop = 1; /* must propagate again */
hasww = 1; /* white-white entry */
}
else if (valiswhite(gval(n))) { /* value not marked yet? */
marked = 1;
reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
}
}
if (prop)
linktable(h, &g->ephemeron); /* have to propagate again */
else if (hasclears) /* does table have white keys? */
linktable(h, &g->allweak); /* may have to clean white keys */
else /* no white keys */
linktable(h, &g->grayagain); /* no need to clean */
/* link table into proper list */
if (g->gcstate == GCSpropagate)
linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
else if (hasww) /* table has white->white entries? */
linkgclist(h, g->ephemeron); /* have to propagate again */
else if (hasclears) /* table has white keys? */
linkgclist(h, g->allweak); /* may have to clean white keys */
return marked;
}
static void traversestrongtable (global_State *g, Table *h) {
Node *n, *limit = gnodelast(h);
int i;
unsigned int i;
for (i = 0; i < h->sizearray; i++) /* traverse array part */
markvalue(g, &h->array[i]);
for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
@ -433,13 +446,13 @@ static lu_mem traversetable (global_State *g, Table *h) {
((weakkey = strchr(svalue(mode), 'k')),
(weakvalue = strchr(svalue(mode), 'v')),
(weakkey || weakvalue))) { /* is really weak? */
black2gray(obj2gco(h)); /* keep table gray */
black2gray(h); /* keep table gray */
if (!weakkey) /* strong keys? */
traverseweakvalue(g, h);
else if (!weakvalue) /* strong values? */
traverseephemeron(g, h);
else /* all weak */
linktable(h, &g->allweak); /* nothing to traverse now */
linkgclist(h, g->allweak); /* nothing to traverse now */
}
else /* not weak */
traversestrongtable(g, h);
@ -450,7 +463,7 @@ static lu_mem traversetable (global_State *g, Table *h) {
static int traverseproto (global_State *g, Proto *f) {
int i;
if (f->cache && iswhite(obj2gco(f->cache)))
if (f->cache && iswhite(f->cache))
f->cache = NULL; /* allow cache to be collected */
markobject(g, f->source);
for (i = 0; i < f->sizek; i++) /* mark literals */
@ -532,7 +545,7 @@ static void propagatemark (global_State *g) {
GCObject *o = g->gray;
lua_assert(isgray(o));
gray2black(o);
switch (gch(o)->tt) {
switch (o->tt) {
case LUA_TTABLE: {
Table *h = gco2t(o);
g->gray = h->gclist; /* remove from 'gray' list */
@ -554,8 +567,7 @@ static void propagatemark (global_State *g) {
case LUA_TTHREAD: {
lua_State *th = gco2th(o);
g->gray = th->gclist; /* remove from 'gray' list */
th->gclist = g->grayagain;
g->grayagain = o; /* insert into 'grayagain' list */
linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
black2gray(o);
size = traversethread(g, th);
break;
@ -577,35 +589,12 @@ static void propagateall (global_State *g) {
}
static void propagatelist (global_State *g, GCObject *l) {
lua_assert(g->gray == NULL); /* no grays left */
g->gray = l;
propagateall(g); /* traverse all elements from 'l' */
}
/*
** retraverse all gray lists. Because tables may be reinserted in other
** lists when traversed, traverse the original lists to avoid traversing
** twice the same table (which is not wrong, but inefficient)
*/
static void retraversegrays (global_State *g) {
GCObject *weak = g->weak; /* save original lists */
GCObject *grayagain = g->grayagain;
GCObject *ephemeron = g->ephemeron;
g->weak = g->grayagain = g->ephemeron = NULL;
propagateall(g); /* traverse main gray list */
propagatelist(g, grayagain);
propagatelist(g, weak);
propagatelist(g, ephemeron);
}
static void convergeephemerons (global_State *g) {
int changed;
do {
GCObject *w;
GCObject *next = g->ephemeron; /* get ephemeron list */
g->ephemeron = NULL; /* tables will return to this list when traversed */
g->ephemeron = NULL; /* tables may return to this list when traversed */
changed = 0;
while ((w = next) != NULL) {
next = gco2t(w)->gclist;
@ -653,7 +642,7 @@ static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
for (; l != f; l = gco2t(l)->gclist) {
Table *h = gco2t(l);
Node *n, *limit = gnodelast(h);
int i;
unsigned int i;
for (i = 0; i < h->sizearray; i++) {
TValue *o = &h->array[i];
if (iscleared(g, o)) /* value was collected? */
@ -689,7 +678,7 @@ static void freeLclosure (lua_State *L, LClosure *cl) {
static void freeobj (lua_State *L, GCObject *o) {
switch (gch(o)->tt) {
switch (o->tt) {
case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
case LUA_TLCL: {
freeLclosure(L, gco2lcl(o));
@ -703,7 +692,7 @@ static void freeobj (lua_State *L, GCObject *o) {
case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
case LUA_TSHRSTR:
luaS_remove(L, rawgco2ts(o)); /* remove it from hash table */
luaS_remove(L, gco2ts(o)); /* remove it from hash table */
/* go through */
case LUA_TLNGSTR: {
luaM_freemem(L, o, sizestring(gco2ts(o)));
@ -720,10 +709,10 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
/*
** sweep at most 'count' elements from a list of GCObjects erasing dead
** objects, where a dead (not alive) object is one marked with the "old"
** (non current) white and not fixed; change all non-dead objects back
** to white, preparing for next collection cycle.
** When object is a thread, sweep its list of open upvalues too.
** objects, where a dead object is one marked with the old (non current)
** white; change all non-dead objects back to white, preparing for next
** collection cycle. Return where to continue the traversal or NULL if
** list is finished.
*/
static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
global_State *g = G(L);
@ -731,14 +720,14 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
int white = luaC_white(g); /* current white */
while (*p != NULL && count-- > 0) {
GCObject *curr = *p;
int marked = gch(curr)->marked;
int marked = curr->marked;
if (isdeadm(ow, marked)) { /* is 'curr' dead? */
*p = gch(curr)->next; /* remove 'curr' from list */
*p = curr->next; /* remove 'curr' from list */
freeobj(L, curr); /* erase 'curr' */
}
else { /* update marks */
gch(curr)->marked = cast_byte((marked & maskcolors) | white);
p = &gch(curr)->next; /* go to next element */
else { /* change mark to 'white' */
curr->marked = cast_byte((marked & maskcolors) | white);
p = &curr->next; /* go to next element */
}
}
return (*p == NULL) ? NULL : p;
@ -785,10 +774,10 @@ static void checkSizes (lua_State *L, global_State *g) {
static GCObject *udata2finalize (global_State *g) {
GCObject *o = g->tobefnz; /* get first element */
lua_assert(tofinalize(o));
g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
gch(o)->next = g->allgc; /* return it to 'allgc' list */
g->tobefnz = o->next; /* remove it from 'tobefnz' list */
o->next = g->allgc; /* return it to 'allgc' list */
g->allgc = o;
resetbit(gch(o)->marked, FINALIZEDBIT); /* object is "normal" again */
resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
if (issweepphase(g))
makewhite(g, o); /* "sweep" object */
return o;
@ -863,14 +852,14 @@ static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
*/
static GCObject **findlast (GCObject **p) {
while (*p != NULL)
p = &gch(*p)->next;
p = &(*p)->next;
return p;
}
/*
** move all unreachable objects (or 'all' objects) that need
** finalization from list 'p' to list 'tobefnz' (to be finalized)
** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
*/
static void separatetobefnz (global_State *g, int all) {
GCObject *curr;
@ -879,12 +868,12 @@ static void separatetobefnz (global_State *g, int all) {
while ((curr = *p) != NULL) { /* traverse all finalizable objects */
lua_assert(tofinalize(curr));
if (!(iswhite(curr) || all)) /* not being collected? */
p = &gch(curr)->next; /* don't bother with it */
p = &curr->next; /* don't bother with it */
else {
*p = gch(curr)->next; /* remove 'curr' from "fin" list */
gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
*p = curr->next; /* remove 'curr' from 'finobj' list */
curr->next = *lastnext; /* link at the end of 'tobefnz' list */
*lastnext = curr;
lastnext = &gch(curr)->next;
lastnext = &curr->next;
}
}
}
@ -903,15 +892,15 @@ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
GCObject **p;
if (issweepphase(g)) {
makewhite(g, o); /* "sweep" object 'o' */
if (g->sweepgc == &o->gch.next) /* shoud not remove 'sweepgc' object */
if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
g->sweepgc = sweeptolive(L, g->sweepgc, NULL); /* change 'sweepgc' */
}
/* search for pointer pointing to 'o' */
for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ }
*p = o->gch.next; /* remove 'o' from 'allgc' list */
o->gch.next = g->finobj; /* link it in "fin" list */
for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
*p = o->next; /* remove 'o' from 'allgc' list */
o->next = g->finobj; /* link it in 'finobj' list */
g->finobj = o;
l_setbit(o->gch.marked, FINALIZEDBIT); /* mark it as such */
l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
}
}
@ -927,12 +916,15 @@ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
/*
** set a reasonable "time" to wait before starting a new GC cycle;
** cycle will start when memory use hits threshold
** Set a reasonable "time" to wait before starting a new GC cycle; cycle
** will start when memory use hits threshold. (Division by 'estimate'
** should be OK: it cannot be zero (because Lua cannot even start with
** less than PAUSEADJ bytes).
*/
static void setpause (global_State *g) {
l_mem threshold, debt;
l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
lua_assert(estimate > 0);
threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
? estimate * g->gcpause /* no overflow */
: MAX_LMEM; /* overflow; truncate to maximum */
@ -978,19 +970,21 @@ static l_mem atomic (lua_State *L) {
global_State *g = G(L);
l_mem work;
GCObject *origweak, *origall;
g->GCmemtrav = 0; /* start counting work */
lua_assert(!iswhite(obj2gco(g->mainthread)));
GCObject *grayagain = g->grayagain; /* save original list */
lua_assert(g->ephemeron == NULL && g->weak == NULL);
lua_assert(!iswhite(g->mainthread));
g->gcstate = GCSinsideatomic;
g->GCmemtrav = 0; /* start counting work */
markobject(g, L); /* mark running thread */
/* registry and global metatables may be changed by API */
markvalue(g, &g->l_registry);
markmt(g); /* mark basic metatables */
markmt(g); /* mark global metatables */
/* remark occasional upvalues of (maybe) dead threads */
remarkupvals(g);
propagateall(g); /* propagate changes */
work = g->GCmemtrav; /* stop counting (do not (re)count grays) */
/* traverse objects caught by write barrier and by 'remarkupvals' */
retraversegrays(g);
work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
g->gray = grayagain;
propagateall(g); /* traverse 'grayagain' list */
g->GCmemtrav = 0; /* restart counting */
convergeephemerons(g);
/* at this point, all strongly accessible objects are marked. */
@ -1008,7 +1002,7 @@ static l_mem atomic (lua_State *L) {
/* at this point, all resurrected objects are marked. */
/* remove dead objects from weak tables */
clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */
clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
/* clear values from resurrected weak tables */
clearvalues(g, g->weak, origweak);
clearvalues(g, g->allweak, origall);
@ -1047,7 +1041,7 @@ static lu_mem singlestep (lua_State *L) {
g->GCmemtrav = 0;
lua_assert(g->gray);
propagatemark(g);
if (g->gray == NULL) /* no more `gray' objects? */
if (g->gray == NULL) /* no more gray objects? */
g->gcstate = GCSatomic; /* finish propagate phase */
return g->GCmemtrav; /* memory traversed in this step */
}
@ -1070,7 +1064,7 @@ static lu_mem singlestep (lua_State *L) {
return sweepstep(L, g, GCSswpend, NULL);
}
case GCSswpend: { /* finish sweeps */
makewhite(g, obj2gco(g->mainthread)); /* sweep main thread */
makewhite(g, g->mainthread); /* sweep main thread */
checkSizes(L, g);
g->gcstate = GCScallfin;
return 0;
@ -1138,7 +1132,7 @@ void luaC_step (lua_State *L) {
/*
** Performs a full GC cycle; if "isemergency", set a flag to avoid
** Performs a full GC cycle; if 'isemergency', set a flag to avoid
** some operations which could change the interpreter state in some
** unexpected ways (running finalizers and shrinking some structures).
** Before running the collection, check 'keepinvariant'; if it is true,

View File

@ -1,7 +1,5 @@
/* $NetBSD: lgc.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lgc.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lgc.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
@ -76,7 +74,7 @@
#define testbit(x,b) testbits(x, bitmask(b))
/* Layout for bit use in `marked' field: */
/* Layout for bit use in 'marked' field: */
#define WHITE0BIT 0 /* object is white (type 0) */
#define WHITE1BIT 1 /* object is white (type 1) */
#define BLACKBIT 2 /* object is black */
@ -86,19 +84,19 @@
#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
#define iswhite(x) testbits((x)->gch.marked, WHITEBITS)
#define isblack(x) testbit((x)->gch.marked, BLACKBIT)
#define iswhite(x) testbits((x)->marked, WHITEBITS)
#define isblack(x) testbit((x)->marked, BLACKBIT)
#define isgray(x) /* neither white nor black */ \
(!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))
(!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
#define tofinalize(x) testbit((x)->gch.marked, FINALIZEDBIT)
#define tofinalize(x) testbit((x)->marked, FINALIZEDBIT)
#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS)
#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow)))
#define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked)
#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
#define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
#define changewhite(x) ((x)->marked ^= WHITEBITS)
#define gray2black(x) l_setbit((x)->marked, BLACKBIT)
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
@ -109,15 +107,15 @@
#define luaC_barrier(L,p,v) { \
if (iscollectable(v) && isblack(obj2gco(p)) && iswhite(gcvalue(v))) \
if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \
luaC_barrier_(L,obj2gco(p),gcvalue(v)); }
#define luaC_barrierback(L,p,v) { \
if (iscollectable(v) && isblack(obj2gco(p)) && iswhite(gcvalue(v))) \
luaC_barrierback_(L,obj2gco(p)); }
if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) \
luaC_barrierback_(L,p); }
#define luaC_objbarrier(L,p,o) { \
if (isblack(obj2gco(p)) && iswhite(obj2gco(o))) \
if (isblack(p) && iswhite(o)) \
luaC_barrier_(L,obj2gco(p),obj2gco(o)); }
#define luaC_upvalbarrier(L,uv) \
@ -131,7 +129,7 @@ LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o);
LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);

View File

@ -1,22 +1,37 @@
/* $NetBSD: linit.c,v 1.3 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: linit.c,v 1.4 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: linit.c,v 1.3 2014/07/19 18:38:34 lneto Exp $
** Id: linit.c,v 1.38 2015/01/05 13:48:33 roberto Exp
** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
/*
** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit
** it to suit your needs.
**
** You can also *preload* libraries, so that a later 'require' can
** open the library, which is already linked to the application.
** For that, do the following code:
**
** luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
** lua_pushcfunction(L, luaopen_modname);
** lua_setfield(L, -2, modname);
** lua_pop(L, 1); // remove _PRELOAD table
*/
#include "lprefix.h"
#define linit_c
#define LUA_LIB
#ifndef _KERNEL
#include <stddef.h>
#endif
#include "lua.h"
@ -43,8 +58,8 @@ static const luaL_Reg loadedlibs[] = {
#ifndef _KERNEL
{LUA_MATHLIBNAME, luaopen_math},
#endif
{LUA_DBLIBNAME, luaopen_debug},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
#if defined(LUA_COMPAT_BITLIB)
{LUA_BITLIBNAME, luaopen_bit32},
#endif
@ -52,27 +67,12 @@ static const luaL_Reg loadedlibs[] = {
};
/*
** these libs are preloaded and must be required before used
*/
static const luaL_Reg preloadedlibs[] = {
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib;
/* call open functions from 'loadedlibs' and set results to global table */
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
/* add open functions from 'preloadedlibs' into 'package.preload' table */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
for (lib = preloadedlibs; lib->func; lib++) {
lua_pushcfunction(L, lib->func);
lua_setfield(L, -2, lib->name);
}
lua_pop(L, 1); /* remove _PRELOAD table */
}

View File

@ -1,20 +1,13 @@
/* $NetBSD: liolib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: liolib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: liolib.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/
#define liolib_c
#define LUA_LIB
/*
** This definition must come before the inclusion of 'stdio.h'; it
** should not affect non-POSIX systems
*/
#if !defined(_FILE_OFFSET_BITS)
#define _LARGEFILE_SOURCE 1
#define _FILE_OFFSET_BITS 64
#endif
#include "lprefix.h"
#include <ctype.h>
@ -24,9 +17,6 @@
#include <stdlib.h>
#include <string.h>
#define liolib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -62,17 +52,17 @@
#define l_popen(L,c,m) (fflush(NULL), popen(c,m))
#define l_pclose(L,file) (pclose(file))
#elif defined(LUA_WIN) /* }{ */
#elif defined(LUA_USE_WINDOWS) /* }{ */
#define l_popen(L,c,m) (_popen(c,m))
#define l_pclose(L,file) (_pclose(file))
#else /* }{ */
/* ANSI definitions */
/* ISO C definitions */
#define l_popen(L,c,m) \
((void)((void)c, m), \
luaL_error(L, LUA_QL("popen") " not supported"), \
luaL_error(L, "'popen' not supported"), \
(FILE*)0)
#define l_pclose(L,file) ((void)L, (void)file, -1)
@ -114,7 +104,7 @@
#define l_ftell(f) ftello(f)
#define l_seeknum off_t
#elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
&& defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
/* Windows (but not DDK) and Visual C++ 2005 or higher */
@ -124,7 +114,7 @@
#else /* }{ */
/* ANSI definitions */
/* ISO C definitions */
#define l_fseek(f,o,w) fseek(f,o,w)
#define l_ftell(f) ftell(f)
#define l_seeknum long
@ -137,6 +127,7 @@
#define IO_PREFIX "_IO_"
#define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
#define IO_INPUT (IO_PREFIX "input")
#define IO_OUTPUT (IO_PREFIX "output")
@ -183,7 +174,7 @@ static FILE *tofile (lua_State *L) {
/*
** When creating file handles, always creates a `closed' file handle
** When creating file handles, always creates a 'closed' file handle
** before opening the actual file; so, if there is a memory error, the
** file is not left opened.
*/
@ -195,9 +186,14 @@ static LStream *newprefile (lua_State *L) {
}
/*
** Calls the 'close' function from a file handle. The 'volatile' avoids
** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
** 32 bits).
*/
static int aux_close (lua_State *L) {
LStream *p = tolstream(L);
lua_CFunction cf = p->closef;
volatile lua_CFunction cf = p->closef;
p->closef = NULL; /* mark stream as closed */
return (*cf)(L); /* close it */
}
@ -241,7 +237,7 @@ static void opencheck (lua_State *L, const char *fname, const char *mode) {
LStream *p = newfile(L);
p->f = fopen(fname, mode);
if (p->f == NULL)
luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
}
@ -287,7 +283,7 @@ static FILE *getiofile (lua_State *L, const char *findex) {
lua_getfield(L, LUA_REGISTRYINDEX, findex);
p = (LStream *)lua_touserdata(L, -1);
if (isclosed(p))
luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
return p->f;
}
@ -404,52 +400,52 @@ static int test2 (RN *rn, const char *set) {
/*
** Read a sequence of (hexa)digits
** Read a sequence of (hex)digits
*/
static int readdigits (RN *rn, int hexa) {
static int readdigits (RN *rn, int hex) {
int count = 0;
while ((hexa ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
count++;
return count;
}
/* access to locale "radix character" (decimal point) */
#if !defined(getlocaledecpoint)
#define getlocaledecpoint() (localeconv()->decimal_point[0])
#if !defined(l_getlocaledecpoint)
#define l_getlocaledecpoint() (localeconv()->decimal_point[0])
#endif
/*
** Read a number: first reads a valid prefix of a numeral into a buffer.
** Then it calls 'lua_strtonum' to check whether the format is correct
** and to convert it to a Lua number
** Then it calls 'lua_stringtonumber' to check whether the format is
** correct and to convert it to a Lua number
*/
static int read_number (lua_State *L, FILE *f) {
RN rn;
int count = 0;
int hexa = 0;
int hex = 0;
char decp[2] = ".";
rn.f = f; rn.n = 0;
decp[0] = getlocaledecpoint(); /* get decimal point from locale */
decp[0] = l_getlocaledecpoint(); /* get decimal point from locale */
l_lockfile(rn.f);
do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
test2(&rn, "-+"); /* optional signal */
if (test2(&rn, "0")) {
if (test2(&rn, "xX")) hexa = 1; /* numeral is hexadecimal */
if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
else count = 1; /* count initial '0' as a valid digit */
}
count += readdigits(&rn, hexa); /* integral part */
count += readdigits(&rn, hex); /* integral part */
if (test2(&rn, decp)) /* decimal point? */
count += readdigits(&rn, hexa); /* fractionary part */
if (count > 0 && test2(&rn, (hexa ? "pP" : "eE"))) { /* exponent mark? */
count += readdigits(&rn, hex); /* fractional part */
if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
test2(&rn, "-+"); /* exponent signal */
readdigits(&rn, 0); /* exponent digits */
}
ungetc(rn.c, rn.f); /* unread look-ahead char */
l_unlockfile(rn.f);
rn.buff[rn.n] = '\0'; /* finish string */
if (lua_strtonum(L, rn.buff)) /* is this a valid number? */
if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
return 1; /* ok */
else { /* invalid format */
lua_pushnil(L); /* "result" to be removed */
@ -468,14 +464,21 @@ static int test_eof (lua_State *L, FILE *f) {
static int read_line (lua_State *L, FILE *f, int chop) {
luaL_Buffer b;
int c;
int c = '\0';
luaL_buffinit(L, &b);
l_lockfile(f);
while ((c = l_getc(f)) != EOF && c != '\n')
luaL_addchar(&b, c);
l_unlockfile(f);
if (!chop && c == '\n') luaL_addchar(&b, c);
while (c != EOF && c != '\n') { /* repeat until end of line */
char *buff = luaL_prepbuffer(&b); /* pre-allocate buffer */
int i = 0;
l_lockfile(f); /* no memory errors can happen inside the lock */
while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
buff[i++] = c;
l_unlockfile(f);
luaL_addsize(&b, i);
}
if (!chop && c == '\n') /* want a newline and have one? */
luaL_addchar(&b, c); /* add ending newline to result */
luaL_pushresult(&b); /* close buffer */
/* return ok if read something (either a newline or something else) */
return (c == '\n' || lua_rawlen(L, -1) > 0);
}
@ -520,7 +523,7 @@ static int g_read (lua_State *L, FILE *f, int first) {
success = 1;
for (n = first; nargs-- && success; n++) {
if (lua_type(L, n) == LUA_TNUMBER) {
size_t l = (size_t)lua_tointeger(L, n);
size_t l = (size_t)luaL_checkinteger(L, n);
success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
}
else {
@ -578,7 +581,7 @@ static int io_readline (lua_State *L) {
lua_pushvalue(L, lua_upvalueindex(3 + i));
n = g_read(L, p->f, 2); /* 'n' is number of results */
lua_assert(n > 0); /* should return at least a nil */
if (!lua_isnil(L, -n)) /* read at least one value? */
if (lua_toboolean(L, -n)) /* read at least one value? */
return n; /* return them */
else { /* first result is nil: EOF or error */
if (n > 1) { /* is there error information? */
@ -656,7 +659,7 @@ static int f_setvbuf (lua_State *L) {
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
int res = setvbuf(f, NULL, mode[op], sz);
int res = setvbuf(f, NULL, mode[op], (size_t)sz);
return luaL_fileresult(L, res == 0, NULL);
}

View File

@ -1,20 +1,22 @@
/* $NetBSD: llex.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: llex.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: llex.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: llex.c,v 2.89 2014/11/14 16:06:09 roberto Exp
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
#define llex_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <locale.h>
#include <string.h>
#endif
#define llex_c
#define LUA_CORE
#include "lua.h"
#include "lctype.h"
@ -45,7 +47,7 @@ static const char *const luaX_tokens [] = {
"return", "then", "true", "until", "while",
"//", "..", "...", "==", ">=", "<=", "~=",
"<<", ">>", "::", "<eof>",
"<number>", "<number>", "<name>", "<string>"
"<number>", "<integer>", "<name>", "<string>"
};
@ -75,21 +77,20 @@ void luaX_init (lua_State *L) {
for (i=0; i<NUM_RESERVED; i++) {
TString *ts = luaS_new(L, luaX_tokens[i]);
luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
ts->tsv.extra = cast_byte(i+1); /* reserved word */
ts->extra = cast_byte(i+1); /* reserved word */
}
}
const char *luaX_token2str (LexState *ls, int token) {
if (token < FIRST_RESERVED) { /* single-byte symbols? */
lua_assert(token == cast(unsigned char, token));
return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) :
luaO_pushfstring(ls->L, "char(%d)", token);
lua_assert(token == cast_uchar(token));
return luaO_pushfstring(ls->L, "'%c'", token);
}
else {
const char *s = luaX_tokens[token - FIRST_RESERVED];
if (token < TK_EOS) /* fixed format (symbols and reserved words)? */
return luaO_pushfstring(ls->L, LUA_QS, s);
return luaO_pushfstring(ls->L, "'%s'", s);
else /* names, strings, and numerals */
return s;
}
@ -105,7 +106,7 @@ static const char *txtToken (LexState *ls, int token) {
case TK_INT:
#endif
save(ls, '\0');
return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff));
return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
default:
return luaX_token2str(ls, token);
}
@ -134,7 +135,7 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
*/
TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
lua_State *L = ls->L;
TValue *o; /* entry for `str' */
TValue *o; /* entry for 'str' */
TString *ts = luaS_newlstr(L, str, l); /* create new string */
setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
o = luaH_set(L, ls->h, L->top - 1);
@ -145,7 +146,7 @@ TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
luaC_checkGC(L);
}
else { /* string already present */
ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */
ts = tsvalue(keyfromval(o)); /* re-use value previously stored */
}
L->top--; /* remove string from stack */
return ts;
@ -159,16 +160,17 @@ TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
static void inclinenumber (LexState *ls) {
int old = ls->current;
lua_assert(currIsNewline(ls));
next(ls); /* skip `\n' or `\r' */
next(ls); /* skip '\n' or '\r' */
if (currIsNewline(ls) && ls->current != old)
next(ls); /* skip `\n\r' or `\r\n' */
next(ls); /* skip '\n\r' or '\r\n' */
if (++ls->linenumber >= MAX_INT)
luaX_syntaxerror(ls, "chunk has too many lines");
lexerror(ls, "chunk has too many lines", 0);
}
void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
int firstchar) {
ls->t.token = 0;
ls->decpoint = '.';
ls->L = L;
ls->current = firstchar;
@ -228,8 +230,8 @@ static void buffreplace (LexState *ls, char from, char to) {
}
#if !defined(getlocaledecpoint)
#define getlocaledecpoint() (localeconv()->decimal_point[0])
#if !defined(l_getlocaledecpoint)
#define l_getlocaledecpoint() (localeconv()->decimal_point[0])
#endif
#endif
@ -243,7 +245,7 @@ static void buffreplace (LexState *ls, char from, char to) {
*/
static void trydecpoint (LexState *ls, TValue *o) {
char old = ls->decpoint;
ls->decpoint = getlocaledecpoint();
ls->decpoint = l_getlocaledecpoint();
buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
if (!buff2num(ls->buff, o)) {
/* format error with correct decimal point: no more options */
@ -329,7 +331,7 @@ static int skip_sep (LexState *ls) {
static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
int line = ls->linenumber; /* initial line (for error message) */
save_and_next(ls); /* skip 2nd `[' */
save_and_next(ls); /* skip 2nd '[' */
if (currIsNewline(ls)) /* string starts with a newline? */
inclinenumber(ls); /* skip it */
for (;;) {
@ -343,7 +345,7 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
}
case ']': {
if (skip_sep(ls) == sep) {
save_and_next(ls); /* skip 2nd `]' */
save_and_next(ls); /* skip 2nd ']' */
goto endloop;
}
break;
@ -390,8 +392,8 @@ static int readhexaesc (LexState *ls) {
}
static unsigned int readutf8esc (LexState *ls) {
unsigned int r;
static unsigned long readutf8esc (LexState *ls) {
unsigned long r;
int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
save_and_next(ls); /* skip 'u' */
esccheck(ls, ls->current == '{', "missing '{'");
@ -469,7 +471,7 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) {
}
default: {
esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
c = readdecesc(ls); /* digital escape \ddd */
c = readdecesc(ls); /* digital escape '\ddd' */
goto only_save;
}
}
@ -511,7 +513,7 @@ static int llex (LexState *ls, SemInfo *seminfo) {
next(ls);
if (ls->current == '[') { /* long comment? */
int sep = skip_sep(ls);
luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
if (sep >= 0) {
read_long_string(ls, NULL, sep); /* skip long comment */
luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
@ -578,7 +580,7 @@ static int llex (LexState *ls, SemInfo *seminfo) {
#ifndef _KERNEL
else if (!lisdigit(ls->current)) return '.';
else return read_numeral(ls, seminfo);
#else
#else /* _KERNEL */
else return '.';
#endif
}
@ -599,7 +601,7 @@ static int llex (LexState *ls, SemInfo *seminfo) {
luaZ_bufflen(ls->buff));
seminfo->ts = ts;
if (isreserved(ts)) /* reserved word? */
return ts->tsv.extra - 1 + FIRST_RESERVED;
return ts->extra - 1 + FIRST_RESERVED;
else {
return TK_NAME;
}

View File

@ -1,7 +1,7 @@
/* $NetBSD: llex.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: llex.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: llex.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: llex.h,v 1.78 2014/10/29 15:38:24 roberto Exp
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
@ -16,6 +16,10 @@
#define FIRST_RESERVED 257
#if !defined(LUA_ENV)
#define LUA_ENV "_ENV"
#endif
/*
* WARNING: if you change the order of this enumeration,
@ -33,7 +37,7 @@ enum RESERVED {
TK_DBCOLON, TK_EOS,
#ifndef _KERNEL
TK_FLT, TK_INT, TK_NAME, TK_STRING
#else
#else /* _KERNEL */
TK_INT, TK_NAME, TK_STRING
#endif
};
@ -60,7 +64,7 @@ typedef struct Token {
typedef struct LexState {
int current; /* current character (charint) */
int linenumber; /* input line counter */
int lastline; /* line of last token `consumed' */
int lastline; /* line of last token 'consumed' */
Token t; /* current token */
Token lookahead; /* look ahead token */
struct FuncState *fs; /* current function (parser) */

View File

@ -1,8 +1,8 @@
/* $NetBSD: llimits.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: llimits.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: llimits.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Limits, basic types, and some other `installation-dependent' definitions
** Id: llimits.h,v 1.125 2014/12/19 13:30:23 roberto Exp
** Limits, basic types, and some other 'installation-dependent' definitions
** See Copyright Notice in lua.h
*/
@ -18,50 +18,59 @@
#include "lua.h"
typedef unsigned LUA_INT32 lu_int32;
/*
** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count
** the total memory used by Lua (in bytes). Usually, 'size_t' and
** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
*/
#if defined(LUAI_MEM) /* { external definitions? */
typedef LUAI_UMEM lu_mem;
typedef LUAI_MEM l_mem;
#elif LUAI_BITSINT >= 32 /* }{ */
typedef size_t lu_mem;
typedef ptrdiff_t l_mem;
#else /* 16-bit ints */ /* }{ */
typedef unsigned long lu_mem;
typedef long l_mem;
#endif /* } */
/* chars used as small naturals (so that `char' is reserved for characters) */
/* chars used as small naturals (so that 'char' is reserved for characters) */
typedef unsigned char lu_byte;
/* maximum value for size_t */
#define MAX_SIZET ((size_t)(~(size_t)0)-2)
#define MAX_SIZET ((size_t)(~(size_t)0))
/* maximum size visible for Lua (must be representable in a lua_Integer */
#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
: (size_t)(LUA_MAXINTEGER)-2)
: (size_t)(LUA_MAXINTEGER))
#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)
#define MAX_LUMEM ((lu_mem)(~(lu_mem)0))
#define MAX_LMEM ((l_mem) ((MAX_LUMEM >> 1) - 2))
#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1))
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
#define MAX_INT INT_MAX /* maximum value of an int */
/*
** conversion of pointer to integer
** conversion of pointer to integer:
** this is for hashing only; there is no problem if the integer
** cannot hold the whole pointer value
*/
#define IntPoint(p) ((unsigned int)(lu_mem)(p))
#define point2int(p) ((unsigned int)((size_t)(p) & UINT_MAX))
/* type to ensure maximum alignment */
#if !defined(LUAI_USER_ALIGNMENT_T)
#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; }
#if defined(LUAI_USER_ALIGNMENT_T)
typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
#else
typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign;
#endif
typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
/* types of 'usual argument conversions' for lua_Number and lua_Integer */
@ -83,18 +92,15 @@ typedef LUAI_UACINT l_uacInt;
/*
** assertion for checking API calls
*/
#if !defined(luai_apicheck)
#if defined(LUA_USE_APICHECK)
#include <assert.h>
#define luai_apicheck(L,e) assert(e)
#define luai_apicheck(e) assert(e)
#else
#define luai_apicheck(L,e) lua_assert(e)
#define luai_apicheck(e) lua_assert(e)
#endif
#endif
#define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
#define api_check(e,msg) luai_apicheck((e) && msg)
#if !defined(UNUSED)
@ -118,7 +124,7 @@ typedef LUAI_UACINT l_uacInt;
/*
** cast a lua_Unsigned to a signed lua_Integer; this cast is
** not strict ANSI C, but two-complement architectures should
** not strict ISO C, but two-complement architectures should
** work fine.
*/
#if !defined(l_castU2S)
@ -131,7 +137,7 @@ typedef LUAI_UACINT l_uacInt;
*/
#if defined(__GNUC__)
#define l_noret void __attribute__((noreturn))
#elif defined(_MSC_VER)
#elif defined(_MSC_VER) && _MSC_VER >= 1200
#define l_noret void __declspec(noreturn)
#else
#define l_noret void
@ -155,17 +161,17 @@ typedef LUAI_UACINT l_uacInt;
/*
** type for virtual-machine instructions
** type for virtual-machine instructions;
** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
*/
typedef lu_int32 Instruction;
#if LUAI_BITSINT >= 32
typedef unsigned int Instruction;
#else
typedef unsigned long Instruction;
#endif
/* maximum stack for a Lua function */
#define MAXSTACK 250
/* minimum size for the string table (must be power of 2) */
#if !defined(MINSTRTABSIZE)
@ -180,12 +186,12 @@ typedef lu_int32 Instruction;
#if !defined(lua_lock)
#define lua_lock(L) ((void) 0)
#define lua_unlock(L) ((void) 0)
#define lua_lock(L) ((void) 0)
#define lua_unlock(L) ((void) 0)
#endif
#if !defined(luai_threadyield)
#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
#endif
@ -211,11 +217,11 @@ typedef lu_int32 Instruction;
#endif
#if !defined(luai_userstateresume)
#define luai_userstateresume(L,n) ((void)L)
#define luai_userstateresume(L,n) ((void)L)
#endif
#if !defined(luai_userstateyield)
#define luai_userstateyield(L,n) ((void)L)
#define luai_userstateyield(L,n) ((void)L)
#endif

View File

@ -1,18 +1,18 @@
/* $NetBSD: lmathlib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lmathlib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lmathlib.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Standard mathematical library
** See Copyright Notice in lua.h
*/
#define lmathlib_c
#define LUA_LIB
#include "lprefix.h"
#include <stdlib.h>
#include <math.h>
#define lmathlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -27,9 +27,11 @@
#if defined(LUA_USE_POSIX)
#define l_rand() random()
#define l_srand(x) srandom(x)
#define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */
#else
#define l_rand() rand()
#define l_srand(x) srand(x)
#define L_RANDMAX RAND_MAX
#endif
#endif /* } */
@ -78,39 +80,39 @@ static int math_atan (lua_State *L) {
}
static int math_ifloor (lua_State *L) {
static int math_toint (lua_State *L) {
int valid;
lua_Integer n = lua_tointegerx(L, 1, &valid);
if (valid)
lua_pushinteger(L, n); /* floor computed by Lua */
lua_pushinteger(L, n);
else {
luaL_checktype(L, 1, LUA_TNUMBER); /* argument must be a number */
lua_pushnil(L); /* number is not convertible to integer */
luaL_checkany(L, 1);
lua_pushnil(L); /* value is not convertible to integer */
}
return 1;
}
static int math_floor (lua_State *L) {
int valid;
lua_Integer n = lua_tointegerx(L, 1, &valid);
if (valid)
lua_pushinteger(L, n); /* floor computed by Lua */
else
lua_pushnumber(L, l_mathop(floor)(luaL_checknumber(L, 1)));
return 1;
}
static void pushnumint (lua_State *L, lua_Number d) {
lua_Integer n;
if (lua_numtointeger(d, &n)) /* fits in an integer? */
if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
lua_pushinteger(L, n); /* result is integer */
else
lua_pushnumber(L, d); /* result is float */
}
static int math_floor (lua_State *L) {
if (lua_isinteger(L, 1))
lua_settop(L, 1); /* integer is its own floor */
else {
lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
pushnumint(L, d);
}
return 1;
}
static int math_ceil (lua_State *L) {
if (lua_isinteger(L, 1))
lua_settop(L, 1); /* integer is its own ceil */
@ -147,15 +149,15 @@ static int math_fmod (lua_State *L) {
static int math_modf (lua_State *L) {
if (lua_isinteger(L ,1)) {
lua_settop(L, 1); /* number is its own integer part */
lua_pushnumber(L, 0); /* no fractionary part */
lua_pushnumber(L, 0); /* no fractional part */
}
else {
lua_Number n = luaL_checknumber(L, 1);
/* integer part (rounds toward zero) */
lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
pushnumint(L, ip);
/* fractionary part (test needed for inf/-inf) */
lua_pushnumber(L, (n == ip) ? 0.0 : (n - ip));
/* fractional part (test needed for inf/-inf) */
lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
}
return 2;
}
@ -166,6 +168,14 @@ static int math_sqrt (lua_State *L) {
return 1;
}
static int math_ult (lua_State *L) {
lua_Integer a = luaL_checkinteger(L, 1);
lua_Integer b = luaL_checkinteger(L, 2);
lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
return 1;
}
static int math_log (lua_State *L) {
lua_Number x = luaL_checknumber(L, 1);
lua_Number res;
@ -186,12 +196,12 @@ static int math_exp (lua_State *L) {
}
static int math_deg (lua_State *L) {
lua_pushnumber(L, luaL_checknumber(L, 1) * (180.0 / PI));
lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
return 1;
}
static int math_rad (lua_State *L) {
lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / 180.0));
lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
return 1;
}
@ -225,15 +235,15 @@ static int math_max (lua_State *L) {
/*
** This function uses 'double' (instead of 'lua_Number') to ensure that
** all bits from 'l_rand' can be represented, and that 'RAND_MAX + 1.0'
** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0'
** will keep full precision (ensuring that 'r' is always less than 1.0.)
*/
static int math_random (lua_State *L) {
lua_Integer low, up;
double r = (double)l_rand() * (1.0 / ((double)RAND_MAX + 1.0));
double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));
switch (lua_gettop(L)) { /* check number of arguments */
case 0: { /* no arguments */
lua_pushnumber(L, r); /* Number between 0 and 1 */
lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */
return 1;
}
case 1: { /* only upper limit */
@ -250,8 +260,8 @@ static int math_random (lua_State *L) {
}
/* random integer in the interval [low, up] */
luaL_argcheck(L, low <= up, 1, "interval is empty");
luaL_argcheck(L, (lua_Unsigned)up - low <= (lua_Unsigned)LUA_MAXINTEGER,
1, "interval too large");
luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
"interval too large");
r *= (double)(up - low) + 1.0;
lua_pushinteger(L, (lua_Integer)r + low);
return 1;
@ -259,22 +269,23 @@ static int math_random (lua_State *L) {
static int math_randomseed (lua_State *L) {
l_srand((unsigned int)luaL_checkunsigned(L, 1));
l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1));
(void)rand(); /* discard first value to avoid undesirable correlations */
return 0;
}
static int math_type (lua_State *L) {
luaL_checkany(L, 1);
if (lua_type(L, 1) == LUA_TNUMBER) {
if (lua_isinteger(L, 1))
lua_pushliteral(L, "integer");
else
lua_pushliteral(L, "float");
}
else
else {
luaL_checkany(L, 1);
lua_pushnil(L);
}
return 1;
}
@ -317,7 +328,7 @@ static int math_frexp (lua_State *L) {
static int math_ldexp (lua_State *L) {
lua_Number x = luaL_checknumber(L, 1);
int ep = luaL_checkint(L, 2);
int ep = (int)luaL_checkinteger(L, 2);
lua_pushnumber(L, l_mathop(ldexp)(x, ep));
return 1;
}
@ -341,9 +352,10 @@ static const luaL_Reg mathlib[] = {
{"cos", math_cos},
{"deg", math_deg},
{"exp", math_exp},
{"ifloor", math_ifloor},
{"tointeger", math_toint},
{"floor", math_floor},
{"fmod", math_fmod},
{"ult", math_ult},
{"log", math_log},
{"max", math_max},
{"min", math_min},
@ -365,6 +377,11 @@ static const luaL_Reg mathlib[] = {
{"ldexp", math_ldexp},
{"log10", math_log10},
#endif
/* placeholders */
{"pi", NULL},
{"huge", NULL},
{"maxinteger", NULL},
{"mininteger", NULL},
{NULL, NULL}
};
@ -376,7 +393,7 @@ LUAMOD_API int luaopen_math (lua_State *L) {
luaL_newlib(L, mathlib);
lua_pushnumber(L, PI);
lua_setfield(L, -2, "pi");
lua_pushnumber(L, HUGE_VAL);
lua_pushnumber(L, (lua_Number)HUGE_VAL);
lua_setfield(L, -2, "huge");
lua_pushinteger(L, LUA_MAXINTEGER);
lua_setfield(L, -2, "maxinteger");

View File

@ -1,19 +1,21 @@
/* $NetBSD: lmem.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lmem.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lmem.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lmem.c,v 1.89 2014/11/02 19:33:33 roberto Exp
** Interface to Memory Manager
** See Copyright Notice in lua.h
*/
#define lmem_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stddef.h>
#endif
#define lmem_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -28,15 +30,15 @@
/*
** About the realloc function:
** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
** (`osize' is the old size, `nsize' is the new size)
** ('osize' is the old size, 'nsize' is the new size)
**
** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no
** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
** matter 'x').
**
** * frealloc(ud, p, x, 0) frees the block `p'
** * frealloc(ud, p, x, 0) frees the block 'p'
** (in this specific case, frealloc must return NULL);
** particularly, frealloc(ud, NULL, 0, 0) does nothing
** (which is equivalent to free(NULL) in ANSI C)
** (which is equivalent to free(NULL) in ISO C)
**
** frealloc returns NULL if it cannot create or reallocate the area
** (any reallocation to an equal or smaller size cannot fail!)
@ -87,12 +89,10 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
#endif
newblock = (*g->frealloc)(g->ud, block, osize, nsize);
if (newblock == NULL && nsize > 0) {
api_check(L, nsize > realosize,
api_check( nsize > realosize,
"realloc cannot fail when shrinking a block");
if (g->gcrunning) {
luaC_fullgc(L, 1); /* try to free some memory... */
newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
}
luaC_fullgc(L, 1); /* try to free some memory... */
newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
if (newblock == NULL)
luaD_throw(L, LUA_ERRMEM);
}

View File

@ -1,7 +1,7 @@
/* $NetBSD: lmem.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lmem.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lmem.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lmem.h,v 1.43 2014/12/19 17:26:14 roberto Exp
** Interface to Memory Manager
** See Copyright Notice in lua.h
*/
@ -19,20 +19,32 @@
/*
** This macro avoids the runtime division MAX_SIZET/(e), as 'e' is
** always constant.
** The macro is somewhat complex to avoid warnings:
** +1 avoids warnings of "comparison has constant result";
** cast to 'void' avoids warnings of "value unused".
** This macro reallocs a vector 'b' from 'on' to 'n' elements, where
** each element has size 'e'. In case of arithmetic overflow of the
** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because
** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).
**
** (The macro is somewhat complex to avoid warnings: The 'sizeof'
** comparison avoids a runtime comparison when overflow cannot occur.
** The compiler should be able to optimize the real test by itself, but
** when it does it, it may give a warning about "comparison is always
** false due to limited range of data type"; the +1 tricks the compiler,
** avoiding this warning but also this optimization.)
*/
#define luaM_reallocv(L,b,on,n,e) \
(cast(void, \
(cast(size_t, (n)+1) > MAX_SIZET/(e)) ? (luaM_toobig(L), 0) : 0), \
(((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
? luaM_toobig(L) : cast_void(0)) , \
luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
/*
** Arrays of chars do not need any test
*/
#define luaM_reallocvchar(L,b,on,n) \
cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
#define luaM_freearray(L, b, n) luaM_reallocv(L, (b), n, 0, sizeof((b)[0]))
#define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s))
#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))

View File

@ -1,7 +1,5 @@
/* $NetBSD: loadlib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: loadlib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: loadlib.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
@ -10,22 +8,15 @@
** systems.
*/
#define loadlib_c
#define LUA_LIB
/*
** if needed, includes windows header before everything else
*/
#if defined(_WIN32)
#include <windows.h>
#endif
#include "lprefix.h"
#include <stdlib.h>
#include <string.h>
#define loadlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -94,29 +85,45 @@
#define LUA_OFSEP "_"
/* table (in the registry) that keeps handles for all loaded C libraries */
#define CLIBS "_CLIBS"
/*
** unique key for table in the registry that keeps handles
** for all loaded C libraries
*/
static const int CLIBS = 0;
#define LIB_FAIL "open"
/* error codes for ll_loadfunc */
#define ERRLIB 1
#define ERRFUNC 2
#define setprogdir(L) ((void)0)
/*
** system-dependent functions
*/
static void ll_unloadlib (void *lib);
static void *ll_load (lua_State *L, const char *path, int seeglb);
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
/*
** unload library 'lib'
*/
static void lsys_unloadlib (void *lib);
/*
** load C library in file 'path'. If 'seeglb', load with all names in
** the library global.
** Returns the library; in case of error, returns NULL plus an
** error string in the stack.
*/
static void *lsys_load (lua_State *L, const char *path, int seeglb);
/*
** Try to find a function named 'sym' in library 'lib'.
** Returns the function; in case of error, returns NULL plus an
** error string in the stack.
*/
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
#if defined(LUA_USE_DLOPEN)
#if defined(LUA_USE_DLOPEN) /* { */
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.
@ -128,20 +135,32 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
#include <dlfcn.h>
static void ll_unloadlib (void *lib) {
/*
** Macro to covert pointer to void* to pointer to function. This cast
** is undefined according to ISO C, but POSIX assumes that it must work.
** (The '__extension__' in gnu compilers is only to avoid warnings.)
*/
#if defined(__GNUC__)
#define cast_func(p) (__extension__ (lua_CFunction)(p))
#else
#define cast_func(p) ((lua_CFunction)(p))
#endif
static void lsys_unloadlib (void *lib) {
dlclose(lib);
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
static void *lsys_load (lua_State *L, const char *path, int seeglb) {
void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
if (lib == NULL) lua_pushstring(L, dlerror());
return lib;
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
lua_CFunction f = cast_func(dlsym(lib, sym));
if (f == NULL) lua_pushstring(L, dlerror());
return f;
}
@ -150,13 +169,15 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
#elif defined(LUA_DL_DLL)
#elif defined(LUA_DL_DLL) /* }{ */
/*
** {======================================================================
** This is an implementation of loadlib for Windows using native functions.
** =======================================================================
*/
#include <windows.h>
#undef setprogdir
/*
@ -192,12 +213,12 @@ static void pusherror (lua_State *L) {
lua_pushfstring(L, "system error %d\n", error);
}
static void ll_unloadlib (void *lib) {
static void lsys_unloadlib (void *lib) {
FreeLibrary((HMODULE)lib);
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
static void *lsys_load (lua_State *L, const char *path, int seeglb) {
HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
(void)(seeglb); /* not used: symbols are 'global' by default */
if (lib == NULL) pusherror(L);
@ -205,7 +226,7 @@ static void *ll_load (lua_State *L, const char *path, int seeglb) {
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
if (f == NULL) pusherror(L);
return f;
@ -214,7 +235,7 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
/* }====================================================== */
#else
#else /* }{ */
/*
** {======================================================
** Fallback for other systems
@ -228,31 +249,34 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
#define DLMSG "dynamic libraries not enabled; check your Lua installation"
static void ll_unloadlib (void *lib) {
static void lsys_unloadlib (void *lib) {
(void)(lib); /* not used */
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
static void *lsys_load (lua_State *L, const char *path, int seeglb) {
(void)(path); (void)(seeglb); /* not used */
lua_pushliteral(L, DLMSG);
return NULL;
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
(void)(lib); (void)(sym); /* not used */
lua_pushliteral(L, DLMSG);
return NULL;
}
/* }====================================================== */
#endif
#endif /* } */
static void *ll_checkclib (lua_State *L, const char *path) {
/*
** return registry.CLIBS[path]
*/
static void *checkclib (lua_State *L, const char *path) {
void *plib;
lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
lua_getfield(L, -1, path);
plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
lua_pop(L, 2); /* pop CLIBS table and 'plib' */
@ -260,8 +284,12 @@ static void *ll_checkclib (lua_State *L, const char *path) {
}
static void ll_addtoclib (lua_State *L, const char *path, void *plib) {
lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
/*
** registry.CLIBS[path] = plib -- for queries
** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
*/
static void addtoclib (lua_State *L, const char *path, void *plib) {
lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
lua_pushlightuserdata(L, plib);
lua_pushvalue(L, -1);
lua_setfield(L, -3, path); /* CLIBS[path] = plib */
@ -271,33 +299,49 @@ static void ll_addtoclib (lua_State *L, const char *path, void *plib) {
/*
** __gc tag method for CLIBS table: calls 'll_unloadlib' for all lib
** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
** handles in list CLIBS
*/
static int gctm (lua_State *L) {
int n = luaL_len(L, 1);
lua_Integer n = luaL_len(L, 1);
for (; n >= 1; n--) { /* for each handle, in reverse order */
lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
ll_unloadlib(lua_touserdata(L, -1));
lsys_unloadlib(lua_touserdata(L, -1));
lua_pop(L, 1); /* pop handle */
}
return 0;
}
static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
void *reg = ll_checkclib(L, path); /* check loaded C libraries */
/* error codes for 'lookforfunc' */
#define ERRLIB 1
#define ERRFUNC 2
/*
** Look for a C function named 'sym' in a dynamically loaded library
** 'path'.
** First, check whether the library is already loaded; if not, try
** to load it.
** Then, if 'sym' is '*', return true (as library has been loaded).
** Otherwise, look for symbol 'sym' in the library and push a
** C function with that symbol.
** Return 0 and 'true' or a function in the stack; in case of
** errors, return an error code and an error message in the stack.
*/
static int lookforfunc (lua_State *L, const char *path, const char *sym) {
void *reg = checkclib(L, path); /* check loaded C libraries */
if (reg == NULL) { /* must load library? */
reg = ll_load(L, path, *sym == '*');
reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
if (reg == NULL) return ERRLIB; /* unable to load library */
ll_addtoclib(L, path, reg);
addtoclib(L, path, reg);
}
if (*sym == '*') { /* loading only library (no function)? */
lua_pushboolean(L, 1); /* return 'true' */
return 0; /* no errors */
}
else {
lua_CFunction f = ll_sym(L, reg, sym);
lua_CFunction f = lsys_sym(L, reg, sym);
if (f == NULL)
return ERRFUNC; /* unable to find function */
lua_pushcfunction(L, f); /* else create new function */
@ -309,7 +353,7 @@ static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
static int ll_loadlib (lua_State *L) {
const char *path = luaL_checkstring(L, 1);
const char *init = luaL_checkstring(L, 2);
int stat = ll_loadfunc(L, path, init);
int stat = lookforfunc(L, path, init);
if (stat == 0) /* no errors? */
return 1; /* return the loaded function */
else { /* error; error message is on stack top */
@ -362,7 +406,7 @@ static const char *searchpath (lua_State *L, const char *name,
lua_remove(L, -2); /* remove path template */
if (readable(filename)) /* does file exist and is readable? */
return filename; /* return that file name */
lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
lua_pushfstring(L, "\n\tno file '%s'", filename);
lua_remove(L, -2); /* remove file name */
luaL_addvalue(&msg); /* concatenate error msg. entry */
}
@ -392,7 +436,7 @@ static const char *findfile (lua_State *L, const char *name,
lua_getfield(L, lua_upvalueindex(1), pname);
path = lua_tostring(L, -1);
if (path == NULL)
luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
luaL_error(L, "'package.%s' must be a string", pname);
return searchpath(L, name, path, ".", dirsep);
}
@ -403,8 +447,7 @@ static int checkload (lua_State *L, int stat, const char *filename) {
return 2; /* return open function and file name */
}
else
return luaL_error(L, "error loading module " LUA_QS
" from file " LUA_QS ":\n\t%s",
return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
lua_tostring(L, 1), filename, lua_tostring(L, -1));
}
@ -418,21 +461,29 @@ static int searcher_Lua (lua_State *L) {
}
/*
** Try to find a load function for module 'modname' at file 'filename'.
** First, change '.' to '_' in 'modname'; then, if 'modname' has
** the form X-Y (that is, it has an "ignore mark"), build a function
** name "luaopen_X" and look for it. (For compatibility, if that
** fails, it also tries "luaopen_Y".) If there is no ignore mark,
** look for a function named "luaopen_modname".
*/
static int loadfunc (lua_State *L, const char *filename, const char *modname) {
const char *funcname;
const char *openfunc;
const char *mark;
modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
mark = strchr(modname, *LUA_IGMARK);
if (mark) {
int stat;
funcname = lua_pushlstring(L, modname, mark - modname);
funcname = lua_pushfstring(L, LUA_POF"%s", funcname);
stat = ll_loadfunc(L, filename, funcname);
openfunc = lua_pushlstring(L, modname, mark - modname);
openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
stat = lookforfunc(L, filename, openfunc);
if (stat != ERRFUNC) return stat;
modname = mark + 1; /* else go ahead and try old-style name */
}
funcname = lua_pushfstring(L, LUA_POF"%s", modname);
return ll_loadfunc(L, filename, funcname);
openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
return lookforfunc(L, filename, openfunc);
}
@ -457,8 +508,7 @@ static int searcher_Croot (lua_State *L) {
if (stat != ERRFUNC)
return checkload(L, 0, filename); /* real error */
else { /* open function not found */
lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
name, filename);
lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
return 1;
}
}
@ -480,16 +530,15 @@ static void findloader (lua_State *L, const char *name) {
int i;
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */
if (!lua_istable(L, 3))
luaL_error(L, LUA_QL("package.searchers") " must be a table");
/* push 'package.searchers' to index 3 in the stack */
if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
luaL_error(L, "'package.searchers' must be a table");
/* iterate over available searchers to find a loader */
for (i = 1; ; i++) {
if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
lua_pop(L, 1); /* remove nil */
luaL_pushresult(&msg); /* create error message */
luaL_error(L, "module " LUA_QS " not found:%s",
name, lua_tostring(L, -1));
luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
}
lua_pushstring(L, name);
lua_call(L, 1, 2); /* call it */
@ -547,7 +596,7 @@ static void set_env (lua_State *L) {
if (lua_getstack(L, 1, &ar) == 0 ||
lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
lua_iscfunction(L, -1))
luaL_error(L, LUA_QL("module") " not called from a Lua function");
luaL_error(L, "'module' not called from a Lua function");
lua_pushvalue(L, -2); /* copy new environment table to top */
lua_setupvalue(L, -2, 1);
lua_pop(L, 1); /* remove function */
@ -657,6 +706,12 @@ static const luaL_Reg pk_funcs[] = {
#if defined(LUA_COMPAT_MODULE)
{"seeall", ll_seeall},
#endif
/* placeholders */
{"preload", NULL},
{"cpath", NULL},
{"path", NULL},
{"searchers", NULL},
{"loaded", NULL},
{NULL, NULL}
};
@ -682,24 +737,32 @@ static void createsearcherstable (lua_State *L) {
lua_pushcclosure(L, searchers[i], 1);
lua_rawseti(L, -2, i+1);
}
#if defined(LUA_COMPAT_LOADERS)
lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */
#endif
lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
}
/*
** create table CLIBS to keep track of loaded C libraries,
** setting a finalizer to close all libraries when closing state.
*/
static void createclibstable (lua_State *L) {
lua_newtable(L); /* create CLIBS table */
lua_createtable(L, 0, 1); /* create metatable for CLIBS */
lua_pushcfunction(L, gctm);
lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
lua_setmetatable(L, -2);
lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */
}
LUAMOD_API int luaopen_package (lua_State *L) {
/* create table CLIBS to keep track of loaded C libraries */
luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);
lua_createtable(L, 0, 1); /* metatable for CLIBS */
lua_pushcfunction(L, gctm);
lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
lua_setmetatable(L, -2);
/* create `package' table */
luaL_newlib(L, pk_funcs);
createclibstable(L);
luaL_newlib(L, pk_funcs); /* create 'package' table */
createsearcherstable(L);
#if defined(LUA_COMPAT_LOADERS)
lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */
#endif
lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
/* set field 'path' */
setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
/* set field 'cpath' */
@ -708,10 +771,10 @@ LUAMOD_API int luaopen_package (lua_State *L) {
lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
lua_setfield(L, -2, "config");
/* set field `loaded' */
/* set field 'loaded' */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_setfield(L, -2, "loaded");
/* set field `preload' */
/* set field 'preload' */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_setfield(L, -2, "preload");
lua_pushglobaltable(L);

View File

@ -1,11 +1,17 @@
/* $NetBSD: lobject.c,v 1.3 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lobject.c,v 1.4 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lobject.c,v 1.3 2014/07/19 18:38:34 lneto Exp $
** Id: lobject.c,v 2.101 2014/12/26 14:43:45 roberto Exp
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
#define lobject_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stdarg.h>
#include <stdio.h>
@ -13,9 +19,6 @@
#include <string.h>
#endif
#define lobject_c
#define LUA_CORE
#include "lua.h"
#include "lctype.h"
@ -103,6 +106,7 @@ static lua_Number numarith (lua_State *L, int op, lua_Number v1,
case LUA_OPMUL: return luai_nummul(L, v1, v2);
case LUA_OPDIV: return luai_numdiv(L, v1, v2);
case LUA_OPPOW: return luai_numpow(L, v1, v2);
case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
case LUA_OPUNM: return luai_numunm(L, v1);
case LUA_OPMOD: {
lua_Number m;
@ -118,9 +122,9 @@ static lua_Number numarith (lua_State *L, int op, lua_Number v1,
void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
TValue *res) {
switch (op) {
case LUA_OPIDIV: case LUA_OPBAND: case LUA_OPBOR:
case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR:
case LUA_OPBNOT: { /* operates only on integers */
case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
case LUA_OPSHL: case LUA_OPSHR:
case LUA_OPBNOT: { /* operate only on integers */
lua_Integer i1; lua_Integer i2;
if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
setivalue(res, intarith(L, op, i1, i2));
@ -141,16 +145,20 @@ void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
default: { /* other operations */
#ifndef _KERNEL
lua_Number n1; lua_Number n2;
#endif
if (ttisinteger(p1) && ttisinteger(p2)) {
setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
return;
}
#ifndef _KERNEL
else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
setfltvalue(res, numarith(L, op, n1, n2));
return;
}
#else /* _KERNEL */
lua_Integer i1; lua_Integer i2;
if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
setivalue(res, intarith(L, op, i1, i2));
return;
}
#endif
else break; /* go to the end */
}
@ -174,25 +182,14 @@ static int isneg (const char **s) {
}
#ifndef _KERNEL
/*
** {======================================================
** lua_strx2number converts an hexadecimal numeric string to a number.
** In C99, 'strtod' does both conversions. C89, however, has no function
** to convert floating hexadecimal strings to numbers. For these
** systems, you can leave 'lua_strx2number' undefined and Lua will
** provide its own implementation.
** =======================================================
** {==================================================================
** Lua's implementation for 'lua_strx2number'
** ===================================================================
*/
#if !defined(lua_strx2number) /* { */
#if defined(LUA_USE_C99) /* { */
#define lua_strx2number(s,p) lua_str2number(s,p)
#else /* }{ */
/* Lua's implementation for 'lua_strx2number' */
#if !defined(lua_strx2number)
#include <math.h>
@ -209,7 +206,7 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
int sigdig = 0; /* number of significant digits */
int nosigdig = 0; /* number of non-significant digits */
int e = 0; /* exponent correction */
int neg = 0; /* 1 if number is negative */
int neg; /* 1 if number is negative */
int dot = 0; /* true after seen a dot */
*endptr = cast(char *, s); /* nothing is valid yet */
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
@ -222,18 +219,12 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
else dot = 1;
}
else if (lisxdigit(cast_uchar(*s))) {
if (sigdig == 0 && *s == '0') { /* non-significant zero? */
if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
nosigdig++;
if (dot) e--; /* zero after dot? correct exponent */
}
else {
if (++sigdig <= MAXSIGDIG) { /* can read it without overflow? */
r = (r * cast_num(16.0)) + luaO_hexavalue(cast_uchar(*s));
if (dot) e--; /* decimal digit */
}
else /* too many digits; ignore */
if (!dot) e++; /* still count it for exponent */
}
else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
else e++; /* too many digits; ignore, but still count for exponent */
if (dot) e--; /* decimal digit? correct exponent */
}
else break; /* neither a dot nor a digit */
}
@ -257,21 +248,16 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
if (neg) r = -r;
return l_mathop(ldexp)(r, e);
}
#endif
#endif /* } */
#endif /* } */
/* }====================================================== */
#ifndef _KERNEL
static const char *l_str2d (const char *s, lua_Number *result) {
char *endptr;
if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */
return NULL;
else if (strpbrk(s, "xX")) /* hexa? */
else if (strpbrk(s, "xX")) /* hex? */
*result = lua_strx2number(s, &endptr);
else
*result = lua_str2number(s, &endptr);
@ -279,7 +265,7 @@ static const char *l_str2d (const char *s, lua_Number *result) {
while (lisspace(cast_uchar(*endptr))) endptr++;
return (*endptr == '\0' ? endptr : NULL); /* OK if no trailing characters */
}
#endif
#endif /* _KERNEL */
static const char *l_str2int (const char *s, lua_Integer *result) {
@ -289,16 +275,16 @@ static const char *l_str2int (const char *s, lua_Integer *result) {
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
neg = isneg(&s);
if (s[0] == '0' &&
(s[1] == 'x' || s[1] == 'X')) { /* hexa? */
(s[1] == 'x' || s[1] == 'X')) { /* hex? */
s += 2; /* skip '0x' */
for (; lisxdigit(cast_uchar(*s)); s++) {
a = a * 16 + luaO_hexavalue(cast_uchar(*s));
a = a * 16 + luaO_hexavalue(*s);
empty = 0;
}
}
else { /* decimal */
for (; lisdigit(cast_uchar(*s)); s++) {
a = a * 10 + luaO_hexavalue(cast_uchar(*s));
a = a * 10 + *s - '0';
empty = 0;
}
}
@ -314,7 +300,7 @@ static const char *l_str2int (const char *s, lua_Integer *result) {
size_t luaO_str2num (const char *s, TValue *o) {
#ifndef _KERNEL
lua_Integer i; lua_Number n;
#else
#else /* _KERNEL */
lua_Integer i;
#endif
const char *e;
@ -332,30 +318,62 @@ size_t luaO_str2num (const char *s, TValue *o) {
}
int luaO_utf8esc (char *buff, unsigned int x) {
int luaO_utf8esc (char *buff, unsigned long x) {
int n = 1; /* number of bytes put in buffer (backwards) */
lua_assert(x <= 0x10FFFF);
if (x < 0x80) /* ascii? */
buff[UTF8BUFFSZ - 1] = x;
buff[UTF8BUFFSZ - 1] = cast(char, x);
else { /* need continuation bytes */
unsigned int mfb = 0x3f; /* maximum that fits in first byte */
do {
buff[UTF8BUFFSZ - (n++)] = 0x80 | (x & 0x3f); /* add continuation byte */
do { /* add continuation bytes */
buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
x >>= 6; /* remove added bits */
mfb >>= 1; /* now there is one less bit available in first byte */
} while (x > mfb); /* still needs continuation byte? */
buff[UTF8BUFFSZ - n] = (~mfb << 1) | x; /* add first byte */
buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x); /* add first byte */
}
return n;
}
/* maximum length of the conversion of a number to a string */
#define MAXNUMBER2STR 50
/*
** Convert a number object to a string
*/
void luaO_tostring (lua_State *L, StkId obj) {
char buff[MAXNUMBER2STR];
size_t len;
lua_assert(ttisnumber(obj));
#ifndef _KERNEL
if (ttisinteger(obj))
len = lua_integer2str(buff, ivalue(obj));
else {
len = lua_number2str(buff, fltvalue(obj));
#if !defined(LUA_COMPAT_FLOATSTRING)
if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
buff[len++] = '.';
buff[len++] = '0'; /* adds '.0' to result */
}
#endif
}
#else /* _KERNEL */
lua_assert(ttisinteger(obj));
len = lua_integer2str(buff, ivalue(obj));
#endif
setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
}
static void pushstr (lua_State *L, const char *str, size_t l) {
setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
}
/* this function handles only '%d', '%c', '%f', '%p', and '%s'
conventional formats, plus Lua-specific '%L' and '%U' */
conventional formats, plus Lua-specific '%I' and '%U' */
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
int n = 0;
for (;;) {
@ -371,37 +389,39 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
break;
}
case 'c': {
char buff;
buff = cast(char, va_arg(argp, int));
pushstr(L, &buff, 1);
char buff = cast(char, va_arg(argp, int));
if (lisprint(cast_uchar(buff)))
pushstr(L, &buff, 1);
else /* non-printable character; print its code */
luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
break;
}
case 'd': {
setivalue(L->top++, cast_int(va_arg(argp, int)));
luaV_tostring(L, L->top - 1);
setivalue(L->top++, va_arg(argp, int));
luaO_tostring(L, L->top - 1);
break;
}
case 'I': {
setivalue(L->top++, cast(lua_Integer, va_arg(argp, l_uacInt)));
luaV_tostring(L, L->top - 1);
luaO_tostring(L, L->top - 1);
break;
}
#ifndef _KERNEL
case 'f': {
setfltvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
luaV_tostring(L, L->top - 1);
luaO_tostring(L, L->top - 1);
break;
}
#endif
case 'p': {
char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
int l = sprintf(buff, "%p", va_arg(argp, void *));
pushstr(L, buff, l);
break;
}
case 'U': {
char buff[UTF8BUFFSZ];
int l = luaO_utf8esc(buff, va_arg(argp, int));
int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
pushstr(L, buff + UTF8BUFFSZ - l, l);
break;
}
@ -410,9 +430,8 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
break;
}
default: {
luaG_runerror(L,
"invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
*(e + 1));
luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
*(e + 1));
}
}
n += 2;

View File

@ -1,7 +1,7 @@
/* $NetBSD: lobject.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lobject.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lobject.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lobject.h,v 2.106 2015/01/05 13:52:37 roberto Exp
** Type definitions for Lua objects
** See Copyright Notice in lua.h
*/
@ -73,9 +73,9 @@
/*
** Union of all collectable objects
** Common type for all collectable objects
*/
typedef union GCObject GCObject;
typedef struct GCObject GCObject;
/*
@ -86,11 +86,11 @@ typedef union GCObject GCObject;
/*
** Common header in struct form
** Common type has only the common header
*/
typedef struct GCheader {
struct GCObject {
CommonHeader;
} GCheader;
};
@ -161,13 +161,15 @@ typedef struct lua_TValue TValue;
#define ivalue(o) check_exp(ttisinteger(o), val_(o).i)
#ifndef _KERNEL
#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n)
#define nvalue(o) check_exp(ttisnumber(o), \
(ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
#else /* _KERNEL */
#define nvalue(o) check_exp(ttisnumber(o), cast_num(ivalue(o)))
#endif
#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
#define rawtsvalue(o) check_exp(ttisstring(o), rawgco2ts(val_(o).gc))
#define tsvalue(o) (&rawtsvalue(o)->tsv)
#define rawuvalue(o) check_exp(ttisfulluserdata(o), rawgco2u(val_(o).gc))
#define uvalue(o) (&rawuvalue(o)->uv)
#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc))
#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc))
#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
@ -185,7 +187,7 @@ typedef struct lua_TValue TValue;
/* Macros for internal tests */
#define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt)
#define righttt(obj) (ttype(obj) == gcvalue(obj)->tt)
#define checkliveness(g,obj) \
lua_longassert(!iscollectable(obj) || \
@ -216,11 +218,11 @@ typedef struct lua_TValue TValue;
#define setgcovalue(L,obj,x) \
{ TValue *io = (obj); GCObject *i_g=(x); \
val_(io).gc = i_g; settt_(io, ctb(gch(i_g)->tt)); }
val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
#define setsvalue(L,obj,x) \
{ TValue *io = (obj); TString *x_ = (x); \
val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tsv.tt)); \
val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
checkliveness(G(L),io); }
#define setuvalue(L,obj,x) \
@ -253,8 +255,7 @@ typedef struct lua_TValue TValue;
#define setobj(L,obj1,obj2) \
{ const TValue *io2=(obj2); TValue *io1=(obj1); \
io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
{ TValue *io1=(obj1); *io1 = *(obj2); \
(void)L; checkliveness(G(L),io1); }
@ -311,50 +312,76 @@ typedef TValue *StkId; /* index to stack elements */
/*
** Header for string value; string bytes follow the end of this structure
** (aligned according to 'UTString'; see next).
*/
typedef union TString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */
struct {
CommonHeader;
lu_byte extra; /* reserved words for short strings; "has hash" for longs */
unsigned int hash;
size_t len; /* number of characters in string */
union TString *hnext; /* linked list for hash table */
} tsv;
typedef struct TString {
CommonHeader;
lu_byte extra; /* reserved words for short strings; "has hash" for longs */
unsigned int hash;
size_t len; /* number of characters in string */
struct TString *hnext; /* linked list for hash table */
} TString;
/* get the actual string (array of bytes) from a TString */
#define getstr(ts) cast(const char *, (ts) + 1)
/*
** Ensures that address after this type is always fully aligned.
*/
typedef union UTString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */
TString tsv;
} UTString;
/*
** Get the actual string (array of bytes) from a 'TString'.
** (Access to 'extra' ensures that value is really a 'TString'.)
*/
#define getaddrstr(ts) (cast(char *, (ts)) + sizeof(UTString))
#define getstr(ts) \
check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))
/* get the actual string (array of bytes) from a Lua value */
#define svalue(o) getstr(rawtsvalue(o))
#define svalue(o) getstr(tsvalue(o))
/*
** Header for userdata; memory area follows the end of this structure
** (aligned according to 'UUdata'; see next).
*/
typedef union Udata {
L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
struct {
CommonHeader;
lu_byte ttuv_; /* user value's tag */
struct Table *metatable;
size_t len; /* number of bytes */
union Value user_; /* user value */
} uv;
typedef struct Udata {
CommonHeader;
lu_byte ttuv_; /* user value's tag */
struct Table *metatable;
size_t len; /* number of bytes */
union Value user_; /* user value */
} Udata;
/*
** Ensures that address after this type is always fully aligned.
*/
typedef union UUdata {
L_Umaxalign dummy; /* ensures maximum alignment for 'local' udata */
Udata uv;
} UUdata;
/*
** Get the address of memory block inside 'Udata'.
** (Access to 'ttuv_' ensures that value is really a 'Udata'.)
*/
#define getudatamem(u) \
check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))
#define setuservalue(L,u,o) \
{ const TValue *io=(o); Udata *iu = (u); \
iu->uv.user_ = io->value_; iu->uv.ttuv_ = io->tt_; \
iu->user_ = io->value_; iu->ttuv_ = io->tt_; \
checkliveness(G(L),io); }
#define getuservalue(L,u,o) \
{ TValue *io=(o); const Udata *iu = (u); \
io->value_ = iu->uv.user_; io->tt_ = iu->uv.ttuv_; \
io->value_ = iu->user_; io->tt_ = iu->ttuv_; \
checkliveness(G(L),io); }
@ -388,10 +415,10 @@ typedef struct Proto {
lu_byte is_vararg;
lu_byte maxstacksize; /* maximum stack used by this function */
int sizeupvalues; /* size of 'upvalues' */
int sizek; /* size of `k' */
int sizek; /* size of 'k' */
int sizecode;
int sizelineinfo;
int sizep; /* size of `p' */
int sizep; /* size of 'p' */
int sizelocvars;
int linedefined;
int lastlinedefined;
@ -459,6 +486,13 @@ typedef union TKey {
} TKey;
/* copy a value into a key without messing up field 'next' */
#define setnodekey(L,key,obj) \
{ TKey *k_=(key); const TValue *io_=(obj); \
k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \
(void)L; checkliveness(G(L),io_); }
typedef struct Node {
TValue i_val;
TKey i_key;
@ -468,8 +502,8 @@ typedef struct Node {
typedef struct Table {
CommonHeader;
lu_byte flags; /* 1<<p means tagmethod(p) is not present */
lu_byte lsizenode; /* log2 of size of `node' array */
int sizearray; /* size of `array' array */
lu_byte lsizenode; /* log2 of size of 'node' array */
unsigned int sizearray; /* size of 'array' array */
TValue *array; /* array part */
Node *node;
Node *lastfree; /* any free position is before this position */
@ -480,7 +514,7 @@ typedef struct Table {
/*
** `module' operation for hashing (size is always a power of 2)
** 'module' operation for hashing (size is always a power of 2)
*/
#define lmod(s,size) \
(check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
@ -503,12 +537,13 @@ LUAI_DDEC const TValue luaO_nilobject_;
LUAI_FUNC int luaO_int2fb (unsigned int x);
LUAI_FUNC int luaO_fb2int (int x);
LUAI_FUNC int luaO_utf8esc (char *buff, unsigned int x);
LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
LUAI_FUNC int luaO_ceillog2 (unsigned int x);
LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
const TValue *p2, TValue *res);
LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);
LUAI_FUNC int luaO_hexavalue (int c);
LUAI_FUNC void luaO_tostring (lua_State *L, StkId obj);
LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
va_list argp);
LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);

View File

@ -1,15 +1,20 @@
/* $NetBSD: lopcodes.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lopcodes.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lopcodes.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lopcodes.c,v 1.55 2015/01/05 13:48:33 roberto Exp
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
#define lopcodes_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stddef.h>
#endif
#include "lopcodes.h"

View File

@ -1,7 +1,7 @@
/* $NetBSD: lopcodes.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lopcodes.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lopcodes.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lopcodes.h,v 1.148 2014/10/25 11:50:46 roberto Exp
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
@ -16,12 +16,12 @@
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits.
Instructions can have the following fields:
`A' : 8 bits
`B' : 9 bits
`C' : 9 bits
'A' : 8 bits
'B' : 9 bits
'C' : 9 bits
'Ax' : 26 bits ('A', 'B', and 'C' together)
`Bx' : 18 bits (`B' and `C' together)
`sBx' : signed Bx
'Bx' : 18 bits ('B' and 'C' together)
'sBx' : signed Bx
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
@ -60,7 +60,7 @@ enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */
*/
#if SIZE_Bx < LUAI_BITSINT-1
#define MAXARG_Bx ((1<<SIZE_Bx)-1)
#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */
#define MAXARG_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */
#else
#define MAXARG_Bx MAX_INT
#define MAXARG_sBx MAX_INT
@ -78,10 +78,10 @@ enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */
#define MAXARG_C ((1<<SIZE_C)-1)
/* creates a mask with `n' 1 bits at position `p' */
/* creates a mask with 'n' 1 bits at position 'p' */
#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
/* creates a mask with `n' 0 bits at position `p' */
/* creates a mask with 'n' 0 bits at position 'p' */
#define MASK0(n,p) (~MASK1(n,p))
/*
@ -207,7 +207,7 @@ OP_LEN,/* A B R(A) := length of R(B) */
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A) + 1 */
OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */
OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
@ -242,16 +242,16 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
/*===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then `top' is
(*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is
set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,
OP_SETLIST) may use `top'.
OP_SETLIST) may use 'top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0).
(*) In OP_RETURN, if (B == 0) then return up to `top'.
(*) In OP_RETURN, if (B == 0) then return up to 'top'.
(*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
(*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next
'instruction' is EXTRAARG(real C).
(*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
@ -259,7 +259,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
(*) For comparisons, A specifies what condition the test should accept
(true or false).
(*) All `skips' (pc++) assume that next instruction is a jump.
(*) All 'skips' (pc++) assume that next instruction is a jump.
===========================================================================*/

View File

@ -1,11 +1,14 @@
/* $NetBSD: loslib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: loslib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: loslib.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Standard Operating System library
** See Copyright Notice in lua.h
*/
#define loslib_c
#define LUA_LIB
#include "lprefix.h"
#include <errno.h>
#include <locale.h>
@ -13,9 +16,6 @@
#include <string.h>
#include <time.h>
#define loslib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -27,9 +27,9 @@
** list of valid conversion specifiers for the 'strftime' function
*/
#if !defined(LUA_USE_POSIX)
#if defined(LUA_USE_C89)
#define LUA_STRFTIMEOPTIONS { "aAbBcdHIjmMpSUwWxXyYz%", "" }
#else
#else /* C99 specification */
#define LUA_STRFTIMEOPTIONS \
{ "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \
"E", "cCxXyY", \
@ -76,7 +76,7 @@
#else /* }{ */
/* ANSI definitions */
/* ISO C definitions */
#define LUA_TMPNAMBUFSIZE L_tmpnam
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
@ -99,9 +99,9 @@
#else /* }{ */
/* ANSI definitions */
#define l_gmtime(t,r) ((void)r, gmtime(t))
#define l_localtime(t,r) ((void)r, localtime(t))
/* ISO C definitions */
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
#endif /* } */
@ -191,7 +191,7 @@ static int getfield (lua_State *L, const char *key, int d) {
res = (int)lua_tointegerx(L, -1, &isnum);
if (!isnum) {
if (d < 0)
return luaL_error(L, "field " LUA_QS " missing in date table", key);
return luaL_error(L, "field '%s' missing in date table", key);
res = d;
}
lua_pop(L, 1);
@ -229,7 +229,7 @@ static int os_date (lua_State *L) {
struct tm tmr, *stm;
if (*s == '!') { /* UTC? */
stm = l_gmtime(&t, &tmr);
s++; /* skip `!' */
s++; /* skip '!' */
}
else
stm = l_localtime(&t, &tmr);
@ -297,7 +297,8 @@ static int os_time (lua_State *L) {
static int os_difftime (lua_State *L) {
lua_pushnumber(L, difftime((l_checktime(L, 1)), (l_checktime(L, 2))));
double res = difftime((l_checktime(L, 1)), (l_checktime(L, 2)));
lua_pushnumber(L, (lua_Number)res);
return 1;
}
@ -321,7 +322,7 @@ static int os_exit (lua_State *L) {
if (lua_isboolean(L, 1))
status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
else
status = luaL_optint(L, 1, EXIT_SUCCESS);
status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
if (lua_toboolean(L, 2))
lua_close(L);
if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */

View File

@ -1,19 +1,21 @@
/* $NetBSD: lparser.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lparser.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lparser.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lparser.c,v 2.147 2014/12/27 20:31:43 roberto Exp
** Lua Parser
** See Copyright Notice in lua.h
*/
#define lparser_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define lparser_c
#define LUA_CORE
#include "lua.h"
#include "lcode.h"
@ -49,11 +51,11 @@
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
short firstlabel; /* index of first label in this block */
short firstgoto; /* index of first pending goto in this block */
int firstlabel; /* index of first label in this block */
int firstgoto; /* index of first pending goto in this block */
lu_byte nactvar; /* # active locals outside the block */
lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isloop; /* true if `block' is a loop */
lu_byte isloop; /* true if 'block' is a loop */
} BlockCnt;
@ -67,7 +69,7 @@ static void expr (LexState *ls, expdesc *v);
/* semantic error */
static l_noret semerror (LexState *ls, const char *msg) {
ls->t.token = 0; /* remove 'near to' from final message */
ls->t.token = 0; /* remove "near <token>" from final message */
luaX_syntaxerror(ls, msg);
}
@ -344,7 +346,7 @@ static void closegoto (LexState *ls, int g, Labeldesc *label) {
if (gt->nactvar < label->nactvar) {
TString *vname = getlocvar(fs, gt->nactvar)->varname;
const char *msg = luaO_pushfstring(ls->L,
"<goto %s> at line %d jumps into the scope of local " LUA_QS,
"<goto %s> at line %d jumps into the scope of local '%s'",
getstr(gt->name), gt->line, getstr(vname));
semerror(ls, msg);
}
@ -388,7 +390,7 @@ static int newlabelentry (LexState *ls, Labellist *l, TString *name,
l->arr[n].line = line;
l->arr[n].nactvar = ls->fs->nactvar;
l->arr[n].pc = pc;
l->n++;
l->n = n + 1;
return n;
}
@ -410,7 +412,7 @@ static void findgotos (LexState *ls, Labeldesc *lb) {
/*
** "export" pending gotos to outer level, to check them against
** export pending gotos to outer level, to check them against
** outer labels; if the block being exited has upvalues, and
** the goto exits the scope of any variable (which can be the
** upvalue), close those variables being exited.
@ -446,7 +448,7 @@ static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
/*
** create a label named "break" to resolve break statements
** create a label named 'break' to resolve break statements
*/
static void breaklabel (LexState *ls) {
TString *n = luaS_new(ls->L, "break");
@ -461,7 +463,7 @@ static void breaklabel (LexState *ls) {
static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
const char *msg = isreserved(gt->name)
? "<%s> at line %d not inside a loop"
: "no visible label " LUA_QS " for <goto> at line %d";
: "no visible label '%s' for <goto> at line %d";
msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
semerror(ls, msg);
}
@ -578,7 +580,7 @@ static void close_func (LexState *ls) {
/*
** check whether current token is in the follow set of a block.
** 'until' closes syntactical blocks, but do not close scope,
** so it handled in separate.
** so it is handled in separate.
*/
static int block_follow (LexState *ls, int withuntil) {
switch (ls->t.token) {
@ -592,7 +594,7 @@ static int block_follow (LexState *ls, int withuntil) {
static void statlist (LexState *ls) {
/* statlist -> { stat [`;'] } */
/* statlist -> { stat [';'] } */
while (!block_follow(ls, 1)) {
if (ls->t.token == TK_RETURN) {
statement(ls);
@ -633,14 +635,14 @@ static void yindex (LexState *ls, expdesc *v) {
struct ConsControl {
expdesc v; /* last list item read */
expdesc *t; /* table descriptor */
int nh; /* total number of `record' elements */
int nh; /* total number of 'record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
static void recfield (LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | `['exp1`]') = exp1 */
/* recfield -> (NAME | '['exp1']') = exp1 */
FuncState *fs = ls->fs;
int reg = ls->fs->freereg;
expdesc key, val;
@ -747,12 +749,12 @@ static void constructor (LexState *ls, expdesc *t) {
static void parlist (LexState *ls) {
/* parlist -> [ param { `,' param } ] */
/* parlist -> [ param { ',' param } ] */
FuncState *fs = ls->fs;
Proto *f = fs->f;
int nparams = 0;
f->is_vararg = 0;
if (ls->t.token != ')') { /* is `parlist' not empty? */
if (ls->t.token != ')') { /* is 'parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME: { /* param -> NAME */
@ -760,12 +762,12 @@ static void parlist (LexState *ls) {
nparams++;
break;
}
case TK_DOTS: { /* param -> `...' */
case TK_DOTS: { /* param -> '...' */
luaX_next(ls);
f->is_vararg = 1;
break;
}
default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
default: luaX_syntaxerror(ls, "<name> or '...' expected");
}
} while (!f->is_vararg && testnext(ls, ','));
}
@ -776,7 +778,7 @@ static void parlist (LexState *ls) {
static void body (LexState *ls, expdesc *e, int ismethod, int line) {
/* body -> `(' parlist `)' block END */
/* body -> '(' parlist ')' block END */
FuncState new_fs;
BlockCnt bl;
new_fs.f = addprototype(ls);
@ -798,7 +800,7 @@ static void body (LexState *ls, expdesc *e, int ismethod, int line) {
static int explist (LexState *ls, expdesc *v) {
/* explist -> expr { `,' expr } */
/* explist -> expr { ',' expr } */
int n = 1; /* at least one expression */
expr(ls, v);
while (testnext(ls, ',')) {
@ -815,7 +817,7 @@ static void funcargs (LexState *ls, expdesc *f, int line) {
expdesc args;
int base, nparams;
switch (ls->t.token) {
case '(': { /* funcargs -> `(' [ explist ] `)' */
case '(': { /* funcargs -> '(' [ explist ] ')' */
luaX_next(ls);
if (ls->t.token == ')') /* arg list is empty? */
args.k = VVOID;
@ -832,7 +834,7 @@ static void funcargs (LexState *ls, expdesc *f, int line) {
}
case TK_STRING: { /* funcargs -> STRING */
codestring(ls, &args, ls->t.seminfo.ts);
luaX_next(ls); /* must use `seminfo' before `next' */
luaX_next(ls); /* must use 'seminfo' before 'next' */
break;
}
default: {
@ -898,14 +900,14 @@ static void suffixedexp (LexState *ls, expdesc *v) {
fieldsel(ls, v);
break;
}
case '[': { /* `[' exp1 `]' */
case '[': { /* '[' exp1 ']' */
expdesc key;
luaK_exp2anyregup(fs, v);
yindex(ls, &key);
luaK_indexed(fs, v, &key);
break;
}
case ':': { /* `:' NAME funcargs */
case ':': { /* ':' NAME funcargs */
expdesc key;
luaX_next(ls);
checkname(ls, &key);
@ -959,7 +961,7 @@ static void simpleexp (LexState *ls, expdesc *v) {
case TK_DOTS: { /* vararg */
FuncState *fs = ls->fs;
check_condition(ls, fs->f->is_vararg,
"cannot use " LUA_QL("...") " outside a vararg function");
"cannot use '...' outside a vararg function");
init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
break;
}
@ -1045,7 +1047,7 @@ static const struct {
/*
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where `binop' is any binary operator with a priority higher than `limit'
** where 'binop' is any binary operator with a priority higher than 'limit'
*/
static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
BinOpr op;
@ -1059,7 +1061,7 @@ static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
luaK_prefix(ls->fs, uop, v, line);
}
else simpleexp(ls, v);
/* expand while operators have priorities higher than `limit' */
/* expand while operators have priorities higher than 'limit' */
op = getbinopr(ls->t.token);
while (op != OPR_NOBINOPR && priority[op].left > limit) {
expdesc v2;
@ -1159,7 +1161,7 @@ static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
"C levels");
assignment(ls, &nv, nvars+1);
}
else { /* assignment -> `=' explist */
else { /* assignment -> '=' explist */
int nexps;
checknext(ls, '=');
nexps = explist(ls, &e);
@ -1183,7 +1185,7 @@ static int cond (LexState *ls) {
/* cond -> exp */
expdesc v;
expr(ls, &v); /* read condition */
if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
luaK_goiftrue(ls->fs, &v);
return v.f;
}
@ -1210,7 +1212,7 @@ static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
for (i = fs->bl->firstlabel; i < ll->n; i++) {
if (eqstr(label, ll->arr[i].name)) {
const char *msg = luaO_pushfstring(fs->ls->L,
"label " LUA_QS " already defined on line %d",
"label '%s' already defined on line %d",
getstr(label), ll->arr[i].line);
semerror(fs->ls, msg);
}
@ -1372,15 +1374,15 @@ static void forstat (LexState *ls, int line) {
TString *varname;
BlockCnt bl;
enterblock(fs, &bl, 1); /* scope for loop and control variables */
luaX_next(ls); /* skip `for' */
luaX_next(ls); /* skip 'for' */
varname = str_checkname(ls); /* first variable name */
switch (ls->t.token) {
case '=': fornum(ls, varname, line); break;
case ',': case TK_IN: forlist(ls, varname); break;
default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
default: luaX_syntaxerror(ls, "'=' or 'in' expected");
}
check_match(ls, TK_END, TK_FOR, line);
leaveblock(fs); /* loop scope (`break' jumps to this point) */
leaveblock(fs); /* loop scope ('break' jumps to this point) */
}
@ -1410,7 +1412,7 @@ static void test_then_block (LexState *ls, int *escapelist) {
enterblock(fs, &bl, 0);
jf = v.f;
}
statlist(ls); /* `then' part */
statlist(ls); /* 'then' part */
leaveblock(fs);
if (ls->t.token == TK_ELSE ||
ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
@ -1427,7 +1429,7 @@ static void ifstat (LexState *ls, int line) {
while (ls->t.token == TK_ELSEIF)
test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
if (testnext(ls, TK_ELSE))
block(ls); /* `else' part */
block(ls); /* 'else' part */
check_match(ls, TK_END, TK_IF, line);
luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
}
@ -1445,7 +1447,7 @@ static void localfunc (LexState *ls) {
static void localstat (LexState *ls) {
/* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
/* stat -> LOCAL NAME {',' NAME} ['=' explist] */
int nvars = 0;
int nexps;
expdesc e;
@ -1465,7 +1467,7 @@ static void localstat (LexState *ls) {
static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {fieldsel} [`:' NAME] */
/* funcname -> NAME {fieldsel} [':' NAME] */
int ismethod = 0;
singlevar(ls, v);
while (ls->t.token == '.')
@ -1486,7 +1488,7 @@ static void funcstat (LexState *ls, int line) {
ismethod = funcname(ls, &v);
body(ls, &b, ismethod, line);
luaK_storevar(ls->fs, &v, &b);
luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
}
@ -1528,8 +1530,8 @@ static void retstat (LexState *ls) {
if (nret == 1) /* only one single value? */
first = luaK_exp2anyreg(fs, &e);
else {
luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
first = fs->nactvar; /* return all `active' values */
luaK_exp2nextreg(fs, &e); /* values must go to the stack */
first = fs->nactvar; /* return all active values */
lua_assert(nret == fs->freereg - first);
}
}
@ -1640,7 +1642,7 @@ LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
incr_top(L);
funcstate.f = cl->p = luaF_newproto(L);
funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
luaC_objbarrier(L, funcstate.f, funcstate.f->source);
lua_assert(iswhite(funcstate.f)); /* do not need barrier here */
lexstate.buff = buff;
lexstate.dyd = dyd;
dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;

View File

@ -1,7 +1,7 @@
/* $NetBSD: lparser.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lparser.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lparser.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lparser.h,v 1.74 2014/10/25 11:50:46 roberto Exp
** Lua Parser
** See Copyright Notice in lua.h
*/
@ -23,7 +23,7 @@ typedef enum {
VNIL,
VTRUE,
VFALSE,
VK, /* info = index of constant in `k' */
VK, /* info = index of constant in 'k' */
#ifndef _KERNEL
VKFLT, /* nval = numerical float value */
#endif
@ -56,8 +56,8 @@ typedef struct expdesc {
#endif
lua_Integer ival; /* for VKINT */
} u;
int t; /* patch list of `exit when true' */
int f; /* patch list of `exit when false' */
int t; /* patch list of 'exit when true' */
int f; /* patch list of 'exit when false' */
} expdesc;
@ -106,11 +106,11 @@ typedef struct FuncState {
struct FuncState *prev; /* enclosing function */
struct LexState *ls; /* lexical state */
struct BlockCnt *bl; /* chain of current blocks */
int pc; /* next position to code (equivalent to `ncode') */
int pc; /* next position to code (equivalent to 'ncode') */
int lasttarget; /* 'label' of last 'jump label' */
int jpc; /* list of pending jumps to `pc' */
int nk; /* number of elements in `k' */
int np; /* number of elements in `p' */
int jpc; /* list of pending jumps to 'pc' */
int nk; /* number of elements in 'k' */
int np; /* number of elements in 'p' */
int firstlocal; /* index of first local var (in Dyndata array) */
short nlocvars; /* number of elements in 'f->locvars' */
lu_byte nactvar; /* number of active local variables */

View File

@ -1,4 +1,4 @@
/* $NetBSD: lprefix.h,v 1.1.1.1 2015/02/02 02:01:13 lneto Exp $ */
/* $NetBSD: lprefix.h,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
** Id: lprefix.h,v 1.2 2014/12/29 16:54:13 roberto Exp
@ -10,6 +10,7 @@
#define lprefix_h
#ifndef _KERNEL
/*
** Allows POSIX/XSI stuff
*/
@ -30,6 +31,7 @@
#endif
#endif /* } */
#endif
/*

View File

@ -1,20 +1,22 @@
/* $NetBSD: lstate.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lstate.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lstate.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lstate.c,v 2.127 2014/11/02 19:33:33 roberto Exp
** Global State
** See Copyright Notice in lua.h
*/
#define lstate_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <stddef.h>
#include <string.h>
#endif
#define lstate_c
#define LUA_CORE
#include "lua.h"
#include "lapi.h"
@ -57,9 +59,7 @@
** thread state + extra space
*/
typedef struct LX {
#if defined(LUAI_EXTRASPACE)
char buff[LUAI_EXTRASPACE];
#endif
lu_byte extra_[LUA_EXTRASPACE];
lua_State l;
} LX;
@ -78,9 +78,8 @@ typedef struct LG {
/*
** Compute an initial seed as random as possible. In ANSI, rely on
** Address Space Layout Randomization (if present) to increase
** randomness..
** Compute an initial seed as random as possible. Rely on Address Space
** Layout Randomization (if present) to increase randomness..
*/
#define addbuff(b,p,e) \
{ size_t t = cast(size_t, e); \
@ -256,7 +255,7 @@ static void close_state (lua_State *L) {
LUA_API lua_State *lua_newthread (lua_State *L) {
global_State *g = G(L);
global_State *g = G(L);
lua_State *L1;
lua_lock(L);
luaC_checkGC(L);
@ -267,6 +266,7 @@ LUA_API lua_State *lua_newthread (lua_State *L) {
/* link it on list 'allgc' */
L1->next = g->allgc;
g->allgc = obj2gco(L1);
/* anchor it on L stack */
setthvalue(L, L->top, L1);
api_incr_top(L);
preinit_thread(L1, g);
@ -274,6 +274,9 @@ LUA_API lua_State *lua_newthread (lua_State *L) {
L1->basehookcount = L->basehookcount;
L1->hook = L->hook;
resethookcount(L1);
/* initialize L1 extra space */
memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
LUA_EXTRASPACE);
luai_userstatethread(L, L1);
stack_init(L1, L); /* init stack */
lua_unlock(L);

View File

@ -1,7 +1,5 @@
/* $NetBSD: lstate.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lstate.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lstate.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Global State
** See Copyright Notice in lua.h
*/
@ -23,10 +21,10 @@
** belong to one (and only one) of these lists, using field 'next' of
** the 'CommonHeader' for the link:
**
** allgc: all objects not marked for finalization;
** finobj: all objects marked for finalization;
** tobefnz: all objects ready to be finalized;
** fixedgc: all objects that are not to be collected (currently
** 'allgc': all objects not marked for finalization;
** 'finobj': all objects marked for finalization;
** 'tobefnz': all objects ready to be finalized;
** 'fixedgc': all objects that are not to be collected (currently
** only small strings, such as reserved words).
*/
@ -56,15 +54,18 @@ typedef struct stringtable {
/*
** information about a call
** Information about a call.
** When a thread yields, 'func' is adjusted to pretend that the
** top function has only the yielded values in its stack; in that
** case, the actual 'func' value is saved in field 'extra'.
** When a function calls another with a continuation, 'extra' keeps
** the function index so that, in case of errors, the continuation
** function can be called with the correct top.
*/
typedef struct CallInfo {
StkId func; /* function index in the stack */
StkId top; /* top for this function */
struct CallInfo *previous, *next; /* dynamic call link */
ptrdiff_t extra;
short nresults; /* expected number of results from this function */
lu_byte callstatus;
union {
struct { /* only for Lua functions */
StkId base; /* base for this function */
@ -73,9 +74,12 @@ typedef struct CallInfo {
struct { /* only for C functions */
lua_KFunction k; /* continuation in case of yields */
ptrdiff_t old_errfunc;
int ctx; /* context info. in case of yields */
lua_KContext ctx; /* context info. in case of yields */
} c;
} u;
ptrdiff_t extra;
short nresults; /* expected number of results from this function */
lu_byte callstatus;
} CallInfo;
@ -99,11 +103,11 @@ typedef struct CallInfo {
/*
** `global state', shared by all threads of this state
** 'global state', shared by all threads of this state
*/
typedef struct global_State {
lua_Alloc frealloc; /* function to reallocate memory */
void *ud; /* auxiliary data to `frealloc' */
void *ud; /* auxiliary data to 'frealloc' */
lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */
l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
lu_mem GCmemtrav; /* memory traversed by the GC */
@ -129,7 +133,7 @@ typedef struct global_State {
Mbuffer buff; /* temporary buffer for string concatenation */
unsigned int gcfinnum; /* number of finalizers to call in each GC step */
int gcpause; /* size of pause between successive GCs */
int gcstepmul; /* GC `granularity' */
int gcstepmul; /* GC 'granularity' */
lua_CFunction panic; /* to be called in unprotected errors */
struct lua_State *mainthread;
const lua_Number *version; /* pointer to version number */
@ -140,7 +144,7 @@ typedef struct global_State {
/*
** `per thread' state
** 'per thread' state
*/
struct lua_State {
CommonHeader;
@ -151,20 +155,20 @@ struct lua_State {
const Instruction *oldpc; /* last pc traced */
StkId stack_last; /* last free slot in the stack */
StkId stack; /* stack base */
int stacksize;
unsigned short nny; /* number of non-yieldable calls in stack */
unsigned short nCcalls; /* number of nested C calls */
lu_byte hookmask;
lu_byte allowhook;
int basehookcount;
int hookcount;
lua_Hook hook;
UpVal *openupval; /* list of open upvalues in this stack */
GCObject *gclist;
struct lua_State *twups; /* list of threads with open upvalues */
struct lua_longjmp *errorJmp; /* current error recover point */
ptrdiff_t errfunc; /* current error handling function (stack index) */
CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
lua_Hook hook;
ptrdiff_t errfunc; /* current error handling function (stack index) */
int stacksize;
int basehookcount;
int hookcount;
unsigned short nny; /* number of non-yieldable calls in stack */
unsigned short nCcalls; /* number of nested C calls */
lu_byte hookmask;
lu_byte allowhook;
};
@ -172,12 +176,12 @@ struct lua_State {
/*
** Union of all collectable objects
** Union of all collectable objects (only for conversions)
*/
union GCObject {
GCheader gch; /* common header */
union TString ts;
union Udata u;
union GCUnion {
GCObject gc; /* common header */
struct TString ts;
struct Udata u;
union Closure cl;
struct Table h;
struct Proto p;
@ -185,24 +189,24 @@ union GCObject {
};
#define gch(o) (&(o)->gch)
#define cast_u(o) cast(union GCUnion *, (o))
/* macros to convert a GCObject into a specific value */
#define rawgco2ts(o) \
check_exp(novariant((o)->gch.tt) == LUA_TSTRING, &((o)->ts))
#define gco2ts(o) (&rawgco2ts(o)->tsv)
#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
#define gco2u(o) (&rawgco2u(o)->uv)
#define gco2lcl(o) check_exp((o)->gch.tt == LUA_TLCL, &((o)->cl.l))
#define gco2ccl(o) check_exp((o)->gch.tt == LUA_TCCL, &((o)->cl.c))
#define gco2ts(o) \
check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
#define gco2u(o) check_exp((o)->tt == LUA_TUSERDATA, &((cast_u(o))->u))
#define gco2lcl(o) check_exp((o)->tt == LUA_TLCL, &((cast_u(o))->cl.l))
#define gco2ccl(o) check_exp((o)->tt == LUA_TCCL, &((cast_u(o))->cl.c))
#define gco2cl(o) \
check_exp(novariant((o)->gch.tt) == LUA_TFUNCTION, &((o)->cl))
#define gco2t(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
#define gco2t(o) check_exp((o)->tt == LUA_TTABLE, &((cast_u(o))->h))
#define gco2p(o) check_exp((o)->tt == LUA_TPROTO, &((cast_u(o))->p))
#define gco2th(o) check_exp((o)->tt == LUA_TTHREAD, &((cast_u(o))->th))
/* macro to convert any Lua object into a GCObject */
#define obj2gco(v) (cast(GCObject *, (v)))
/* macro to convert a Lua object into a GCObject */
#define obj2gco(v) \
check_exp(novariant((v)->tt) < LUA_TDEADKEY, (&(cast_u(v)->gc)))
/* actual number of total bytes allocated */

View File

@ -1,19 +1,21 @@
/* $NetBSD: lstring.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lstring.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lstring.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lstring.c,v 2.45 2014/11/02 19:19:04 roberto Exp
** String table (keeps all strings handled by Lua)
** See Copyright Notice in lua.h
*/
#define lstring_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define lstring_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -38,10 +40,10 @@
** equality for long strings
*/
int luaS_eqlngstr (TString *a, TString *b) {
size_t len = a->tsv.len;
lua_assert(a->tsv.tt == LUA_TLNGSTR && b->tsv.tt == LUA_TLNGSTR);
size_t len = a->len;
lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);
return (a == b) || /* same instance or... */
((len == b->tsv.len) && /* equal length and ... */
((len == b->len) && /* equal length and ... */
(memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */
}
@ -71,9 +73,9 @@ void luaS_resize (lua_State *L, int newsize) {
TString *p = tb->hash[i];
tb->hash[i] = NULL;
while (p) { /* for each node in the list */
TString *hnext = p->tsv.hnext; /* save next */
unsigned int h = lmod(p->tsv.hash, newsize); /* new position */
p->tsv.hnext = tb->hash[h]; /* chain it */
TString *hnext = p->hnext; /* save next */
unsigned int h = lmod(p->hash, newsize); /* new position */
p->hnext = tb->hash[h]; /* chain it */
tb->hash[h] = p;
p = hnext;
}
@ -96,24 +98,24 @@ static TString *createstrobj (lua_State *L, const char *str, size_t l,
TString *ts;
GCObject *o;
size_t totalsize; /* total size of TString object */
totalsize = sizeof(TString) + ((l + 1) * sizeof(char));
totalsize = sizelstring(l);
o = luaC_newobj(L, tag, totalsize);
ts = rawgco2ts(o);
ts->tsv.len = l;
ts->tsv.hash = h;
ts->tsv.extra = 0;
memcpy(ts+1, str, l*sizeof(char));
((char *)(ts+1))[l] = '\0'; /* ending 0 */
ts = gco2ts(o);
ts->len = l;
ts->hash = h;
ts->extra = 0;
memcpy(getaddrstr(ts), str, l * sizeof(char));
getaddrstr(ts)[l] = '\0'; /* ending 0 */
return ts;
}
void luaS_remove (lua_State *L, TString *ts) {
stringtable *tb = &G(L)->strt;
TString **p = &tb->hash[lmod(ts->tsv.hash, tb->size)];
TString **p = &tb->hash[lmod(ts->hash, tb->size)];
while (*p != ts) /* find previous element */
p = &(*p)->tsv.hnext;
*p = (*p)->tsv.hnext; /* remove element from its list */
p = &(*p)->hnext;
*p = (*p)->hnext; /* remove element from its list */
tb->nuse--;
}
@ -126,12 +128,12 @@ static TString *internshrstr (lua_State *L, const char *str, size_t l) {
global_State *g = G(L);
unsigned int h = luaS_hash(str, l, g->seed);
TString **list = &g->strt.hash[lmod(h, g->strt.size)];
for (ts = *list; ts != NULL; ts = ts->tsv.hnext) {
if (l == ts->tsv.len &&
for (ts = *list; ts != NULL; ts = ts->hnext) {
if (l == ts->len &&
(memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
/* found! */
if (isdead(g, obj2gco(ts))) /* dead (but not collected yet)? */
changewhite(obj2gco(ts)); /* resurrect it */
if (isdead(g, ts)) /* dead (but not collected yet)? */
changewhite(ts); /* resurrect it */
return ts;
}
}
@ -140,7 +142,7 @@ static TString *internshrstr (lua_State *L, const char *str, size_t l) {
list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */
}
ts = createstrobj(L, str, l, LUA_TSHRSTR, h);
ts->tsv.hnext = *list;
ts->hnext = *list;
*list = ts;
g->strt.nuse++;
return ts;
@ -174,10 +176,10 @@ Udata *luaS_newudata (lua_State *L, size_t s) {
GCObject *o;
if (s > MAX_SIZE - sizeof(Udata))
luaM_toobig(L);
o = luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s);
u = rawgco2u(o);
u->uv.len = s;
u->uv.metatable = NULL;
o = luaC_newobj(L, LUA_TUSERDATA, sizeludata(s));
u = gco2u(o);
u->len = s;
u->metatable = NULL;
setuservalue(L, u, luaO_nilobject);
return u;
}

View File

@ -1,7 +1,5 @@
/* $NetBSD: lstring.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lstring.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lstring.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** String table (keep all strings handled by Lua)
** See Copyright Notice in lua.h
*/
@ -14,9 +12,11 @@
#include "lstate.h"
#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char))
#define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char))
#define sizestring(s) sizelstring((s)->len)
#define sizeudata(u) (sizeof(union Udata)+(u)->len)
#define sizeludata(l) (sizeof(union UUdata) + (l))
#define sizeudata(u) sizeludata((u)->len)
#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
(sizeof(s)/sizeof(char))-1))
@ -25,13 +25,13 @@
/*
** test whether a string is a reserved word
*/
#define isreserved(s) ((s)->tsv.tt == LUA_TSHRSTR && (s)->tsv.extra > 0)
#define isreserved(s) ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
/*
** equality for short strings, which are always internalized
*/
#define eqshrstr(a,b) check_exp((a)->tsv.tt == LUA_TSHRSTR, (a) == (b))
#define eqshrstr(a,b) check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);

View File

@ -1,11 +1,16 @@
/* $NetBSD: lstrlib.c,v 1.5 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lstrlib.c,v 1.6 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lstrlib.c,v 1.5 2014/07/19 18:38:34 lneto Exp $
** Id: lstrlib.c,v 1.221 2014/12/11 14:03:07 roberto Exp
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/
#define lstrlib_c
#define LUA_LIB
#include "lprefix.h"
#ifndef _KERNEL
#include <ctype.h>
@ -16,9 +21,6 @@
#include <string.h>
#endif
#define lstrlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
@ -34,10 +36,19 @@
#endif
/* macro to `unsign' a character */
/* macro to 'unsign' a character */
#define uchar(c) ((unsigned char)(c))
/*
** Some sizes are better limited to fit in 'int', but must also fit in
** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
*/
#define MAXSIZE \
(sizeof(size_t) < sizeof(int) ? (~(size_t)0) : (size_t)(INT_MAX))
static int str_len (lua_State *L) {
size_t l;
@ -63,7 +74,7 @@ static int str_sub (lua_State *L) {
if (start < 1) start = 1;
if (end > (lua_Integer)l) end = l;
if (start <= end)
lua_pushlstring(L, s + start - 1, end - start + 1);
lua_pushlstring(L, s + start - 1, (size_t)(end - start + 1));
else lua_pushliteral(L, "");
return 1;
}
@ -107,13 +118,6 @@ static int str_upper (lua_State *L) {
}
/* reasonable limit to avoid arithmetic overflow and strings too big */
#if LUA_MAXINTEGER / 2 <= 0x10000000
#define MAXSIZE ((size_t)(LUA_MAXINTEGER / 2))
#else
#define MAXSIZE ((size_t)0x10000000)
#endif
static int str_rep (lua_State *L) {
size_t l, lsep;
const char *s = luaL_checklstring(L, 1, &l);
@ -123,7 +127,7 @@ static int str_rep (lua_State *L) {
else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
return luaL_error(L, "resulting string too large");
else {
size_t totallen = n * l + (n - 1) * lsep;
size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
luaL_Buffer b;
char *p = luaL_buffinitsize(L, &b, totallen);
while (n-- > 1) { /* first n-1 copies (followed by separator) */
@ -254,16 +258,16 @@ static const char *classend (MatchState *ms, const char *p) {
switch (*p++) {
case L_ESC: {
if (p == ms->p_end)
luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
luaL_error(ms->L, "malformed pattern (ends with '%%')");
return p+1;
}
case '[': {
if (*p == '^') p++;
do { /* look for a `]' */
do { /* look for a ']' */
if (p == ms->p_end)
luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
luaL_error(ms->L, "malformed pattern (missing ']')");
if (*(p++) == L_ESC && p < ms->p_end)
p++; /* skip escapes (e.g. `%]') */
p++; /* skip escapes (e.g. '%]') */
} while (*p != ']');
return p+1;
}
@ -298,7 +302,7 @@ static int matchbracketclass (int c, const char *p, const char *ec) {
int sig = 1;
if (*(p+1) == '^') {
sig = 0;
p++; /* skip the `^' */
p++; /* skip the '^' */
}
while (++p < ec) {
if (*p == L_ESC) {
@ -336,8 +340,7 @@ static int singlematch (MatchState *ms, const char *s, const char *p,
static const char *matchbalance (MatchState *ms, const char *s,
const char *p) {
if (p >= ms->p_end - 1)
luaL_error(ms->L, "malformed pattern "
"(missing arguments to " LUA_QL("%%b") ")");
luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
if (*s != *p) return NULL;
else {
int b = *p;
@ -436,7 +439,7 @@ static const char *match (MatchState *ms, const char *s, const char *p) {
break;
}
case '$': {
if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
goto dflt; /* no; go to default */
s = (s == ms->src_end) ? s : NULL; /* check end of string */
break;
@ -454,8 +457,7 @@ static const char *match (MatchState *ms, const char *s, const char *p) {
const char *ep; char previous;
p += 2;
if (*p != '[')
luaL_error(ms->L, "missing " LUA_QL("[") " after "
LUA_QL("%%f") " in pattern");
luaL_error(ms->L, "missing '[' after '%%f' in pattern");
ep = classend(ms, p); /* points to what is next */
previous = (s == ms->src_init) ? '\0' : *(s - 1);
if (!matchbracketclass(uchar(previous), p, ep - 1) &&
@ -525,16 +527,16 @@ static const char *match (MatchState *ms, const char *s, const char *p) {
static const char *lmemfind (const char *s1, size_t l1,
const char *s2, size_t l2) {
if (l2 == 0) return s1; /* empty strings are everywhere */
else if (l2 > l1) return NULL; /* avoids a negative `l1' */
else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
else {
const char *init; /* to search for a `*s2' inside `s1' */
l2--; /* 1st char will be checked by `memchr' */
l1 = l1-l2; /* `s2' cannot be found after that */
const char *init; /* to search for a '*s2' inside 's1' */
l2--; /* 1st char will be checked by 'memchr' */
l1 = l1-l2; /* 's2' cannot be found after that */
while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct `l1' and `s1' to try again */
else { /* correct 'l1' and 's1' to try again */
l1 -= init-s1;
s1 = init;
}
@ -550,7 +552,7 @@ static void push_onecapture (MatchState *ms, int i, const char *s,
if (i == 0) /* ms->level == 0, too */
lua_pushlstring(ms->L, s, e - s); /* add whole match */
else
luaL_error(ms->L, "invalid capture index");
luaL_error(ms->L, "invalid capture index %%%d", i + 1);
}
else {
ptrdiff_t l = ms->capture[i].len;
@ -598,7 +600,7 @@ static int str_find_aux (lua_State *L, int find) {
/* explicit request or no special characters? */
if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
/* do a plain search */
const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
if (s2) {
lua_pushinteger(L, s2 - s + 1);
lua_pushinteger(L, s2 - s + lp);
@ -689,7 +691,8 @@ static int gmatch (lua_State *L) {
static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
const char *e) {
size_t l, i;
const char *news = lua_tolstring(ms->L, 3, &l);
lua_State *L = ms->L;
const char *news = lua_tolstring(L, 3, &l);
for (i = 0; i < l; i++) {
if (news[i] != L_ESC)
luaL_addchar(b, news[i]);
@ -697,14 +700,15 @@ static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
i++; /* skip ESC */
if (!isdigit(uchar(news[i]))) {
if (news[i] != L_ESC)
luaL_error(ms->L, "invalid use of " LUA_QL("%c")
" in replacement string", L_ESC);
luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
luaL_addchar(b, news[i]);
}
else if (news[i] == '0')
luaL_addlstring(b, s, e - s);
else {
push_onecapture(ms, news[i] - '1', s, e);
luaL_tolstring(L, -1, NULL); /* if number, convert it to string */
lua_remove(L, -2); /* remove original value */
luaL_addvalue(b); /* add capture to accumulated result */
}
}
@ -748,9 +752,9 @@ static int str_gsub (lua_State *L) {
const char *src = luaL_checklstring(L, 1, &srcl);
const char *p = luaL_checklstring(L, 2, &lp);
int tr = lua_type(L, 3);
size_t max_s = luaL_optinteger(L, 4, srcl+1);
lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);
int anchor = (*p == '^');
size_t n = 0;
lua_Integer n = 0;
MatchState ms;
luaL_Buffer b;
luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
@ -883,7 +887,7 @@ static int str_format (lua_State *L) {
else if (*++strfrmt == L_ESC)
luaL_addchar(&b, *strfrmt++); /* %% */
else { /* format item */
char form[MAX_FORMAT]; /* to store the format (`%...') */
char form[MAX_FORMAT]; /* to store the format ('%...') */
char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
int nb = 0; /* number of bytes in added item */
if (++arg > top)
@ -891,7 +895,7 @@ static int str_format (lua_State *L) {
strfrmt = scanformat(L, strfrmt, form);
switch (*strfrmt++) {
case 'c': {
nb = sprintf(buff, form, luaL_checkint(L, arg));
nb = sprintf(buff, form, (int)luaL_checkinteger(L, arg));
break;
}
case 'd': case 'i':
@ -902,10 +906,10 @@ static int str_format (lua_State *L) {
break;
}
#ifndef _KERNEL
case 'e': case 'E': case 'f':
#if defined(LUA_USE_AFORMAT)
case 'a': case 'A':
#endif
case 'e': case 'E': case 'f':
case 'g': case 'G': {
addlenmod(form, LUA_NUMBER_FRMLEN);
nb = sprintf(buff, form, luaL_checknumber(L, arg));
@ -931,9 +935,9 @@ static int str_format (lua_State *L) {
break;
}
}
default: { /* also treat cases `pnLlh' */
return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
LUA_QL("format"), *(strfrmt - 1));
default: { /* also treat cases 'pnLlh' */
return luaL_error(L, "invalid option '%%%c' to 'format'",
*(strfrmt - 1));
}
}
luaL_addsize(&b, nb);
@ -953,215 +957,448 @@ static int str_format (lua_State *L) {
*/
/* value used for padding */
#if !defined(LUA_PACKPADBYTE)
#define LUA_PACKPADBYTE 0x00
#endif
/* maximum size for the binary representation of an integer */
#define MAXINTSIZE 16
/* number of bits in a character */
#define NB CHAR_BIT
/* mask for one character (NB 1's) */
#define MC ((1 << NB) - 1)
/* mask for one character without sign bit ((NB - 1) 1's) */
#define SM (MC >> 1)
/* size of a lua_Integer */
#define SZINT ((int)sizeof(lua_Integer))
/* maximum size for the binary representation of an integer */
#define MAXINTSIZE 12
static union {
/* dummy union to get native endianness */
static const union {
int dummy;
char little; /* true iff machine is little endian */
} const nativeendian = {1};
} nativeendian = {1};
static int getendian (lua_State *L, int arg) {
const char *endian = luaL_optstring(L, arg,
(nativeendian.little ? "l" : "b"));
if (*endian == 'n') /* native? */
return nativeendian.little;
luaL_argcheck(L, *endian == 'l' || *endian == 'b', arg,
"endianness must be 'l'/'b'/'n'");
return (*endian == 'l');
}
/* dummy structure to get native alignment requirements */
struct cD {
char c;
union { double d; void *p; lua_Integer i; lua_Number n; } u;
};
static int getintsize (lua_State *L, int arg) {
int size = luaL_optint(L, arg, 0);
if (size == 0) size = SZINT;
luaL_argcheck(L, 1 <= size && size <= MAXINTSIZE, arg,
"integer size out of valid range");
return size;
}
/* mask for all ones in last byte in a lua Integer */
#define HIGHERBYTE ((lua_Unsigned)MC << (NB * (SZINT - 1)))
static int dumpint (char *buff, lua_Integer m, int littleendian, int size) {
int i;
lua_Unsigned n = (lua_Unsigned)m;
lua_Unsigned mask = (m >= 0) ? 0 : HIGHERBYTE; /* sign extension */
if (littleendian) {
for (i = 0; i < size - 1; i++) {
buff[i] = (n & MC);
n = (n >> NB) | mask;
}
}
else {
for (i = size - 1; i > 0; i--) {
buff[i] = (n & MC);
n = (n >> NB) | mask;
}
}
buff[i] = (n & MC); /* last byte */
if (size < SZINT) { /* need test for overflow? */
/* OK if there are only zeros left in higher bytes,
or only ones left (excluding non-signal bits in last byte) */
return ((n & ~(lua_Unsigned)MC) == 0 ||
(n | SM) == ~(lua_Unsigned)0);
}
else return 1; /* no overflow can occur with full size */
}
static int dumpint_l (lua_State *L) {
char buff[MAXINTSIZE];
lua_Integer n = luaL_checkinteger(L, 1);
int size = getintsize(L, 2);
int endian = getendian(L, 3);
if (dumpint(buff, n, endian, size))
lua_pushlstring(L, buff, size);
else
luaL_error(L, "integer does not fit into given size (%d)", size);
return 1;
}
/* mask to check higher-order byte + signal bit of next (lower) byte */
#define HIGHERBYTE1 (HIGHERBYTE | (HIGHERBYTE >> 1))
static int undumpint (const char *buff, lua_Integer *res,
int littleendian, int size) {
lua_Unsigned n = 0;
int i;
for (i = 0; i < size; i++) {
if (i >= SZINT) { /* will throw away a byte? */
/* check for overflow: it is OK to throw away leading zeros for a
positive number, leading ones for a negative number, and a
leading zero byte to allow unsigned integers with a 1 in
its "signal bit" */
if (!((n & HIGHERBYTE1) == 0 || /* zeros for positive number */
(n & HIGHERBYTE1) == HIGHERBYTE1 || /* ones for negative number */
(i == size - 1 && (n & HIGHERBYTE) == 0))) /* leading zero */
return 0; /* overflow */
}
n <<= NB;
n |= (lua_Unsigned)(unsigned char)buff[littleendian ? size - 1 - i : i];
}
if (size < SZINT) { /* need sign extension? */
lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
*res = (lua_Integer)((n ^ mask) - mask); /* do sign extension */
}
else
*res = (lua_Integer)n;
return 1;
}
static int undumpint_l (lua_State *L) {
lua_Integer res;
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
int size = getintsize(L, 3);
int endian = getendian(L, 4);
luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
"string too short");
if(undumpint(s + pos - 1, &res, endian, size))
lua_pushinteger(L, res);
else
luaL_error(L, "result does not fit into a Lua integer");
return 1;
}
#define MAXALIGN (offsetof(struct cD, u))
#ifndef _KERNEL
static void correctendianness (lua_State *L, char *b, int size, int endianarg) {
int endian = getendian(L, endianarg);
if (endian != nativeendian.little) { /* not native endianness? */
int i = 0;
while (i < --size) {
char temp = b[i];
b[i++] = b[size];
b[size] = temp;
/*
** Union for serializing floats
*/
typedef union Ftypes {
float f;
double d;
lua_Number n;
char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
} Ftypes;
#endif
/*
** information to pack/unpack stuff
*/
typedef struct Header {
lua_State *L;
int islittle;
int maxalign;
} Header;
/*
** options for pack/unpack
*/
typedef enum KOption {
Kint, /* signed integers */
Kuint, /* unsigned integers */
#ifndef _KERNEL
Kfloat, /* floating-point numbers */
#endif
Kchar, /* fixed-length strings */
Kstring, /* strings with prefixed length */
Kzstr, /* zero-terminated strings */
Kpadding, /* padding */
Kpaddalign, /* padding for alignment */
Knop /* no-op (configuration or spaces) */
} KOption;
/*
** Read an integer numeral from string 'fmt' or return 'df' if
** there is no numeral
*/
static int digit (int c) { return '0' <= c && c <= '9'; }
static int getnum (const char **fmt, int df) {
if (!digit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
a = a*10 + (*((*fmt)++) - '0');
} while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
return a;
}
}
/*
** Read an integer numeral and raises an error if it is larger
** than the maximum size for integers.
*/
static int getnumlimit (Header *h, const char **fmt, int df) {
int sz = getnum(fmt, df);
if (sz > MAXINTSIZE || sz <= 0)
luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
sz, MAXINTSIZE);
return sz;
}
/*
** Initialize Header
*/
static void initheader (lua_State *L, Header *h) {
h->L = L;
h->islittle = nativeendian.little;
h->maxalign = 1;
}
/*
** Read and classify next option. 'size' is filled with option's size.
*/
static KOption getoption (Header *h, const char **fmt, int *size) {
int opt = *((*fmt)++);
*size = 0; /* default */
switch (opt) {
case 'b': *size = sizeof(char); return Kint;
case 'B': *size = sizeof(char); return Kuint;
case 'h': *size = sizeof(short); return Kint;
case 'H': *size = sizeof(short); return Kuint;
case 'l': *size = sizeof(long); return Kint;
case 'L': *size = sizeof(long); return Kuint;
case 'j': *size = sizeof(lua_Integer); return Kint;
case 'J': *size = sizeof(lua_Integer); return Kuint;
case 'T': *size = sizeof(size_t); return Kuint;
#ifndef _KERNEL
case 'f': *size = sizeof(float); return Kfloat;
case 'd': *size = sizeof(double); return Kfloat;
case 'n': *size = sizeof(lua_Number); return Kfloat;
#else /* _KERNEL */
case 'n': *size = sizeof(lua_Number); return Kint;
#endif
case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
case 'c':
*size = getnum(fmt, -1);
if (*size == -1)
luaL_error(h->L, "missing size for format option 'c'");
return Kchar;
case 'z': return Kzstr;
case 'x': *size = 1; return Kpadding;
case 'X': return Kpaddalign;
case ' ': break;
case '<': h->islittle = 1; break;
case '>': h->islittle = 0; break;
case '=': h->islittle = nativeendian.little; break;
case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
default: luaL_error(h->L, "invalid format option '%c'", opt);
}
return Knop;
}
/*
** Read, classify, and fill other details about the next option.
** 'psize' is filled with option's size, 'notoalign' with its
** alignment requirements.
** Local variable 'size' gets the size to be aligned. (Kpadal option
** always gets its full alignment, other options are limited by
** the maximum alignment ('maxalign'). Kchar option needs no alignment
** despite its size.
*/
static KOption getdetails (Header *h, size_t totalsize,
const char **fmt, int *psize, int *ntoalign) {
KOption opt = getoption(h, fmt, psize);
int align = *psize; /* usually, alignment follows size */
if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
luaL_argerror(h->L, 1, "invalid next option for option 'X'");
}
if (align <= 1 || opt == Kchar) /* need no alignment? */
*ntoalign = 0;
else {
if (align > h->maxalign) /* enforce maximum alignment */
align = h->maxalign;
if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
*ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
}
return opt;
}
/*
** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
** The final 'if' handles the case when 'size' is larger than
** the size of a Lua integer, correcting the extra sign-extension
** bytes if necessary (by default they would be zeros).
*/
static void packint (luaL_Buffer *b, lua_Unsigned n,
int islittle, int size, int neg) {
char *buff = luaL_prepbuffsize(b, size);
int i;
buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
for (i = 1; i < size; i++) {
n >>= NB;
buff[islittle ? i : size - 1 - i] = (char)(n & MC);
}
if (neg && size > SZINT) { /* negative number need sign extension? */
for (i = SZINT; i < size; i++) /* correct extra bytes */
buff[islittle ? i : size - 1 - i] = (char)MC;
}
luaL_addsize(b, size); /* add result to buffer */
}
/*
** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
** given 'islittle' is different from native endianness.
*/
static void copywithendian (volatile char *dest, volatile const char *src,
int size, int islittle) {
if (islittle == nativeendian.little) {
while (size-- != 0)
*(dest++) = *(src++);
}
else {
dest += size - 1;
while (size-- != 0)
*(dest--) = *(src++);
}
}
static int str_pack (lua_State *L) {
luaL_Buffer b;
Header h;
const char *fmt = luaL_checkstring(L, 1); /* format string */
int arg = 1; /* current argument to pack */
size_t totalsize = 0; /* accumulate total size of result */
initheader(L, &h);
lua_pushnil(L); /* mark to separate arguments from string buffer */
luaL_buffinit(L, &b);
while (*fmt != '\0') {
int size, ntoalign;
KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
totalsize += ntoalign + size;
while (ntoalign-- > 0)
luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */
arg++;
switch (opt) {
case Kint: { /* signed integers */
lua_Integer n = luaL_checkinteger(L, arg);
if (size < SZINT) { /* need overflow check? */
lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
}
packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
break;
}
case Kuint: { /* unsigned integers */
lua_Integer n = luaL_checkinteger(L, arg);
if (size < SZINT) /* need overflow check? */
luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
arg, "unsigned overflow");
packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
break;
}
#ifndef _KERNEL
case Kfloat: { /* floating-point options */
volatile Ftypes u;
char *buff = luaL_prepbuffsize(&b, size);
lua_Number n = luaL_checknumber(L, arg); /* get argument */
if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
else if (size == sizeof(u.d)) u.d = (double)n;
else u.n = n;
/* move 'u' to final result, correcting endianness if needed */
copywithendian(buff, u.buff, size, h.islittle);
luaL_addsize(&b, size);
break;
}
#endif
case Kchar: { /* fixed-size string */
size_t len;
const char *s = luaL_checklstring(L, arg, &len);
luaL_argcheck(L, len == (size_t)size, arg, "wrong length");
luaL_addlstring(&b, s, size);
break;
}
case Kstring: { /* strings with length count */
size_t len;
const char *s = luaL_checklstring(L, arg, &len);
luaL_argcheck(L, size >= (int)sizeof(size_t) ||
len < ((size_t)1 << (size * NB)),
arg, "string length does not fit in given size");
packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
luaL_addlstring(&b, s, len);
totalsize += len;
break;
}
case Kzstr: { /* zero-terminated string */
size_t len;
const char *s = luaL_checklstring(L, arg, &len);
luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
luaL_addlstring(&b, s, len);
luaL_addchar(&b, '\0'); /* add zero at the end */
totalsize += len + 1;
break;
}
case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE); /* go through */
case Kpaddalign: case Knop:
arg--; /* undo increment */
break;
}
}
}
static int getfloatsize (lua_State *L, int arg) {
const char *size = luaL_optstring(L, arg, "n");
if (*size == 'n') return sizeof(lua_Number);
luaL_argcheck(L, *size == 'd' || *size == 'f', arg,
"size must be 'f'/'d'/'n'");
return (*size == 'd' ? sizeof(double) : sizeof(float));
}
static int dumpfloat_l (lua_State *L) {
float f; double d;
char *pn; /* pointer to number */
lua_Number n = luaL_checknumber(L, 1);
int size = getfloatsize(L, 2);
if (size == sizeof(lua_Number))
pn = (char*)&n;
else if (size == sizeof(float)) {
f = (float)n;
pn = (char*)&f;
}
else { /* native lua_Number may be neither float nor double */
lua_assert(size == sizeof(double));
d = (double)n;
pn = (char*)&d;
}
correctendianness(L, pn, size, 3);
lua_pushlstring(L, pn, size);
luaL_pushresult(&b);
return 1;
}
static int undumpfloat_l (lua_State *L) {
lua_Number res;
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
int size = getfloatsize(L, 3);
luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
"string too short");
if (size == sizeof(lua_Number)) {
memcpy(&res, s + pos - 1, size);
correctendianness(L, (char*)&res, size, 4);
static int str_packsize (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1); /* format string */
size_t totalsize = 0; /* accumulate total size of result */
initheader(L, &h);
while (*fmt != '\0') {
int size, ntoalign;
KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
size += ntoalign; /* total space used by option */
luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
"format result too large");
totalsize += size;
switch (opt) {
case Kstring: /* strings with length count */
case Kzstr: /* zero-terminated string */
luaL_argerror(L, 1, "variable-length format");
break;
default: break;
}
}
else if (size == sizeof(float)) {
float f;
memcpy(&f, s + pos - 1, size);
correctendianness(L, (char*)&f, size, 4);
res = (lua_Number)f;
}
else { /* native lua_Number may be neither float nor double */
double d;
lua_assert(size == sizeof(double));
memcpy(&d, s + pos - 1, size);
correctendianness(L, (char*)&d, size, 4);
res = (lua_Number)d;
}
lua_pushnumber(L, res);
lua_pushinteger(L, (lua_Integer)totalsize);
return 1;
}
/*
** Unpack an integer with 'size' bytes and 'islittle' endianness.
** If size is smaller than the size of a Lua integer and integer
** is signed, must do sign extension (propagating the sign to the
** higher bits); if size is larger than the size of a Lua integer,
** it must check the unread bytes to see whether they do not cause an
** overflow.
*/
static lua_Integer unpackint (lua_State *L, const char *str,
int islittle, int size, int issigned) {
lua_Unsigned res = 0;
int i;
int limit = (size <= SZINT) ? size : SZINT;
for (i = limit - 1; i >= 0; i--) {
res <<= NB;
res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
}
if (size < SZINT) { /* real size smaller than lua_Integer? */
if (issigned) { /* needs sign extension? */
lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
res = ((res ^ mask) - mask); /* do sign extension */
}
}
else if (size > SZINT) { /* must check unread bytes */
int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
for (i = limit; i < size; i++) {
if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
}
}
return (lua_Integer)res;
}
static int str_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1;
int n = 0; /* number of results */
luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
initheader(L, &h);
while (*fmt != '\0') {
int size, ntoalign;
KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)
luaL_argerror(L, 2, "data string too short");
pos += ntoalign; /* skip alignment */
/* stack space for item + next position */
luaL_checkstack(L, 2, "too many results");
n++;
switch (opt) {
case Kint:
case Kuint: {
lua_Integer res = unpackint(L, data + pos, h.islittle, size,
(opt == Kint));
lua_pushinteger(L, res);
break;
}
#ifndef _KERNEL
case Kfloat: {
volatile Ftypes u;
lua_Number num;
copywithendian(u.buff, data + pos, size, h.islittle);
if (size == sizeof(u.f)) num = (lua_Number)u.f;
else if (size == sizeof(u.d)) num = (lua_Number)u.d;
else num = u.n;
lua_pushnumber(L, num);
break;
}
#endif
case Kchar: {
lua_pushlstring(L, data + pos, size);
break;
}
case Kstring: {
size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short");
lua_pushlstring(L, data + pos + size, len);
pos += len; /* skip string */
break;
}
case Kzstr: {
size_t len = (int)strlen(data + pos);
lua_pushlstring(L, data + pos, len);
pos += len + 1; /* skip string plus final '\0' */
break;
}
case Kpaddalign: case Kpadding: case Knop:
n--; /* undo increment */
break;
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
/* }====================================================== */
@ -1181,14 +1418,9 @@ static const luaL_Reg strlib[] = {
{"reverse", str_reverse},
{"sub", str_sub},
{"upper", str_upper},
#ifndef _KERNEL
{"dumpfloat", dumpfloat_l},
#endif
{"dumpint", dumpint_l},
#ifndef _KERNEL
{"undumpfloat", undumpfloat_l},
#endif
{"undumpint", undumpint_l},
{"pack", str_pack},
{"packsize", str_packsize},
{"unpack", str_unpack},
{NULL, NULL}
};

View File

@ -1,21 +1,26 @@
/* $NetBSD: ltable.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ltable.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ltable.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ltable.c,v 2.100 2015/01/05 13:52:37 roberto Exp
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
#define ltable_c
#define LUA_CORE
#include "lprefix.h"
/*
** Implementation of tables (aka arrays, objects, or hash tables).
** Tables keep its elements in two parts: an array part and a hash part.
** Non-negative integer keys are all candidates to be kept in the array
** part. The actual size of the array is the largest `n' such that at
** part. The actual size of the array is the largest 'n' such that at
** least half the slots between 0 and n are in use.
** Hash uses a mix of chained scatter table with Brent's variation.
** A main invariant of these tables is that, if an element is not
** in its main position (i.e. the `original' position that its hash gives
** in its main position (i.e. the 'original' position that its hash gives
** to it), then the colliding element is in its own main position.
** Hence even when the load factor reaches 100%, performance remains good.
*/
@ -27,9 +32,6 @@
#include <limits.h>
#endif
#define ltable_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -44,19 +46,24 @@
/*
** Maximum size of array part (MAXASIZE) is 2^MAXBITS. (SIZEINT is the
** minimum between size of int and size of LUA_INTEGER; array indices
** are limited by both types.)
** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is
** the largest integer such that MAXASIZE fits in an unsigned int.
*/
#define SIZEINT \
(sizeof(int) < sizeof(LUA_INTEGER) ? sizeof(int) : sizeof(LUA_INTEGER))
#define MAXBITS cast_int(SIZEINT * CHAR_BIT - 2)
#define MAXASIZE (1 << MAXBITS)
#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
#define MAXASIZE (1u << MAXABITS)
/*
** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest
** integer such that 2^MAXHBITS fits in a signed int. (Note that the
** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still
** fits comfortably in an unsigned int.)
*/
#define MAXHBITS (MAXABITS - 1)
#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
#define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
#define hashstr(t,str) hashpow2(t, (str)->hash)
#define hashboolean(t,p) hashpow2(t, p)
#define hashint(t,i) hashpow2(t, i)
@ -68,7 +75,7 @@
#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
#define hashpointer(t,p) hashmod(t, IntPoint(p))
#define hashpointer(t,p) hashmod(t, point2int(p))
#define dummynode (&dummynode_)
@ -88,7 +95,7 @@ static const Node dummynode_ = {
*/
static int numisinteger (lua_Number x, lua_Integer *p) {
if ((x) == l_floor(x)) /* integral value? */
return lua_numtointeger(x, p); /* try as an integer */
return lua_numbertointeger(x, p); /* try as an integer */
else return 0;
}
@ -112,7 +119,7 @@ static Node *hashfloat (const Table *t, lua_Number n) {
/*
** returns the `main' position of an element in a table (that is, the index
** returns the 'main' position of an element in a table (that is, the index
** of its hash value)
*/
static Node *mainposition (const Table *t, const TValue *key) {
@ -124,14 +131,14 @@ static Node *mainposition (const Table *t, const TValue *key) {
return hashfloat(t, fltvalue(key));
#endif
case LUA_TSHRSTR:
return hashstr(t, rawtsvalue(key));
return hashstr(t, tsvalue(key));
case LUA_TLNGSTR: {
TString *s = rawtsvalue(key);
if (s->tsv.extra == 0) { /* no hash? */
s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);
s->tsv.extra = 1; /* now it has its hash */
TString *s = tsvalue(key);
if (s->extra == 0) { /* no hash? */
s->hash = luaS_hash(getstr(s), s->len, s->hash);
s->extra = 1; /* now it has its hash */
}
return hashstr(t, rawtsvalue(key));
return hashstr(t, tsvalue(key));
}
case LUA_TBOOLEAN:
return hashboolean(t, bvalue(key));
@ -146,45 +153,45 @@ static Node *mainposition (const Table *t, const TValue *key) {
/*
** returns the index for `key' if `key' is an appropriate key to live in
** the array part of the table, -1 otherwise.
** returns the index for 'key' if 'key' is an appropriate key to live in
** the array part of the table, 0 otherwise.
*/
static int arrayindex (const TValue *key) {
static unsigned int arrayindex (const TValue *key) {
if (ttisinteger(key)) {
lua_Integer k = ivalue(key);
if (0 < k && k <= MAXASIZE) /* is `key' an appropriate array index? */
return cast_int(k);
if (0 < k && (lua_Unsigned)k <= MAXASIZE)
return cast(unsigned int, k); /* 'key' is an appropriate array index */
}
return -1; /* `key' did not match some condition */
return 0; /* 'key' did not match some condition */
}
/*
** returns the index of a `key' for table traversals. First goes all
** returns the index of a 'key' for table traversals. First goes all
** elements in the array part, then elements in the hash part. The
** beginning of a traversal is signaled by -1.
** beginning of a traversal is signaled by 0.
*/
static int findindex (lua_State *L, Table *t, StkId key) {
int i;
if (ttisnil(key)) return -1; /* first iteration */
static unsigned int findindex (lua_State *L, Table *t, StkId key) {
unsigned int i;
if (ttisnil(key)) return 0; /* first iteration */
i = arrayindex(key);
if (0 < i && i <= t->sizearray) /* is `key' inside array part? */
return i-1; /* yes; that's the index (corrected to C) */
if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */
return i; /* yes; that's the index */
else {
int nx;
Node *n = mainposition(t, key);
for (;;) { /* check whether `key' is somewhere in the chain */
/* key may be dead already, but it is ok to use it in `next' */
for (;;) { /* check whether 'key' is somewhere in the chain */
/* key may be dead already, but it is ok to use it in 'next' */
if (luaV_rawequalobj(gkey(n), key) ||
(ttisdeadkey(gkey(n)) && iscollectable(key) &&
deadvalue(gkey(n)) == gcvalue(key))) {
i = cast_int(n - gnode(t, 0)); /* key index in hash table */
/* hash elements are numbered after array ones */
return i + t->sizearray;
return (i + 1) + t->sizearray;
}
nx = gnext(n);
if (nx == 0)
luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
luaG_runerror(L, "invalid key to 'next'"); /* key not found */
else n += nx;
}
}
@ -192,15 +199,15 @@ static int findindex (lua_State *L, Table *t, StkId key) {
int luaH_next (lua_State *L, Table *t, StkId key) {
int i = findindex(L, t, key); /* find original element */
for (i++; i < t->sizearray; i++) { /* try first array part */
unsigned int i = findindex(L, t, key); /* find original element */
for (; i < t->sizearray; i++) { /* try first array part */
if (!ttisnil(&t->array[i])) { /* a non-nil value? */
setivalue(key, i + 1);
setobj2s(L, key+1, &t->array[i]);
return 1;
}
}
for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */
if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
setobj2s(L, key, gkey(gnode(t, i)));
setobj2s(L, key+1, gval(gnode(t, i)));
@ -217,19 +224,24 @@ int luaH_next (lua_State *L, Table *t, StkId key) {
** ==============================================================
*/
static int computesizes (int nums[], int *narray) {
/*
** Compute the optimal size for the array part of table 't'. 'nums' is a
** "count array" where 'nums[i]' is the number of integers in the table
** between 2^(i - 1) + 1 and 2^i. Put in '*narray' the optimal size, and
** return the number of elements that will go to that part.
*/
static unsigned int computesizes (unsigned int nums[], unsigned int *narray) {
int i;
int twotoi; /* 2^i */
int a = 0; /* number of elements smaller than 2^i */
int na = 0; /* number of elements to go to array part */
int n = 0; /* optimal size for array part */
unsigned int twotoi; /* 2^i */
unsigned int a = 0; /* number of elements smaller than 2^i */
unsigned int na = 0; /* number of elements to go to array part */
unsigned int n = 0; /* optimal size for array part */
for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
if (nums[i] > 0) {
a += nums[i];
if (a > twotoi/2) { /* more than half elements present? */
n = twotoi; /* optimal size (till now) */
na = a; /* all elements smaller than n will go to array part */
na = a; /* all elements up to 'n' will go to array part */
}
}
if (a == *narray) break; /* all elements already counted */
@ -240,9 +252,9 @@ static int computesizes (int nums[], int *narray) {
}
static int countint (const TValue *key, int *nums) {
int k = arrayindex(key);
if (k > 0) { /* is `key' an appropriate array index? */
static int countint (const TValue *key, unsigned int *nums) {
unsigned int k = arrayindex(key);
if (k != 0) { /* is 'key' an appropriate array index? */
nums[luaO_ceillog2(k)]++; /* count as such */
return 1;
}
@ -251,20 +263,21 @@ static int countint (const TValue *key, int *nums) {
}
static int numusearray (const Table *t, int *nums) {
static unsigned int numusearray (const Table *t, unsigned int *nums) {
int lg;
int ttlg; /* 2^lg */
int ause = 0; /* summation of `nums' */
int i = 1; /* count to traverse all array keys */
for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */
int lc = 0; /* counter */
int lim = ttlg;
unsigned int ttlg; /* 2^lg */
unsigned int ause = 0; /* summation of 'nums' */
unsigned int i = 1; /* count to traverse all array keys */
/* traverse each slice */
for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
unsigned int lc = 0; /* counter */
unsigned int lim = ttlg;
if (lim > t->sizearray) {
lim = t->sizearray; /* adjust upper limit */
if (i > lim)
break; /* no more elements to count */
}
/* count elements in range (2^(lg-1), 2^lg] */
/* count elements in range (2^(lg - 1), 2^lg] */
for (; i <= lim; i++) {
if (!ttisnil(&t->array[i-1]))
lc++;
@ -276,9 +289,10 @@ static int numusearray (const Table *t, int *nums) {
}
static int numusehash (const Table *t, int *nums, int *pnasize) {
static int numusehash (const Table *t, unsigned int *nums,
unsigned int *pnasize) {
int totaluse = 0; /* total number of elements */
int ause = 0; /* summation of `nums' */
int ause = 0; /* elements added to 'nums' (can go to array part) */
int i = sizenode(t);
while (i--) {
Node *n = &t->node[i];
@ -292,8 +306,8 @@ static int numusehash (const Table *t, int *nums, int *pnasize) {
}
static void setarrayvector (lua_State *L, Table *t, int size) {
int i;
static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
unsigned int i;
luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
for (i=t->sizearray; i<size; i++)
setnilvalue(&t->array[i]);
@ -301,23 +315,23 @@ static void setarrayvector (lua_State *L, Table *t, int size) {
}
static void setnodevector (lua_State *L, Table *t, int size) {
static void setnodevector (lua_State *L, Table *t, unsigned int size) {
int lsize;
if (size == 0) { /* no elements to hash part? */
t->node = cast(Node *, dummynode); /* use common `dummynode' */
t->node = cast(Node *, dummynode); /* use common 'dummynode' */
lsize = 0;
}
else {
int i;
lsize = luaO_ceillog2(size);
if (lsize > MAXBITS)
if (lsize > MAXHBITS)
luaG_runerror(L, "table overflow");
size = twoto(lsize);
t->node = luaM_newvector(L, size, Node);
for (i=0; i<size; i++) {
for (i = 0; i < (int)size; i++) {
Node *n = gnode(t, i);
gnext(n) = 0;
setnilvalue(gkey(n));
setnilvalue(wgkey(n));
setnilvalue(gval(n));
}
}
@ -326,9 +340,11 @@ static void setnodevector (lua_State *L, Table *t, int size) {
}
void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
int i;
int oldasize = t->sizearray;
void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
unsigned int nhsize) {
unsigned int i;
int j;
unsigned int oldasize = t->sizearray;
int oldhsize = t->lsizenode;
Node *nold = t->node; /* save old hash ... */
if (nasize > oldasize) /* array part must grow? */
@ -346,8 +362,8 @@ void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
}
/* re-insert elements from hash part */
for (i = twoto(oldhsize) - 1; i >= 0; i--) {
Node *old = nold+i;
for (j = twoto(oldhsize) - 1; j >= 0; j--) {
Node *old = nold + j;
if (!ttisnil(gval(old))) {
/* doesn't need barrier/invalidate cache, as entry was
already present in the table */
@ -359,18 +375,20 @@ void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
}
void luaH_resizearray (lua_State *L, Table *t, int nasize) {
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
int nsize = isdummy(t->node) ? 0 : sizenode(t);
luaH_resize(L, t, nasize, nsize);
}
/*
** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
*/
static void rehash (lua_State *L, Table *t, const TValue *ek) {
int nasize, na;
int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
unsigned int nasize, na;
unsigned int nums[MAXABITS + 1];
int i;
int totaluse;
for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
nasize = numusearray(t, nums); /* count keys in array part */
totaluse = nasize; /* all those keys are integer keys */
totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */
@ -430,7 +448,9 @@ static Node *getfreepos (Table *t) {
*/
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
#ifndef _KERNEL
TValue aux;
#endif
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
#ifndef _KERNEL
else if (ttisfloat(key)) {
@ -443,8 +463,6 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
key = &aux; /* insert it as an integer */
}
}
#else
UNUSED(aux);
#endif
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
@ -452,7 +470,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *f = getfreepos(t); /* get a free place */
if (f == NULL) { /* cannot find a free place? */
rehash(L, t, key); /* grow table */
/* whatever called 'newkey' take care of TM cache and GC barrier */
/* whatever called 'newkey' takes care of TM cache and GC barrier */
return luaH_set(L, t, key); /* insert key into grown table */
}
lua_assert(!isdummy(f));
@ -478,7 +496,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
mp = f;
}
}
setobj2t(L, gkey(mp), key);
setnodekey(L, &mp->i_key, key);
luaC_barrierback(L, t, key);
lua_assert(ttisnil(gval(mp)));
return gval(mp);
@ -490,11 +508,11 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
*/
const TValue *luaH_getint (Table *t, lua_Integer key) {
/* (1 <= key && key <= t->sizearray) */
if (l_castS2U(key - 1) < cast(unsigned int, t->sizearray))
if (l_castS2U(key - 1) < t->sizearray)
return &t->array[key - 1];
else {
Node *n = hashint(t, key);
for (;;) { /* check whether `key' is somewhere in the chain */
for (;;) { /* check whether 'key' is somewhere in the chain */
if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key)
return gval(n); /* that's it */
else {
@ -513,9 +531,10 @@ const TValue *luaH_getint (Table *t, lua_Integer key) {
*/
const TValue *luaH_getstr (Table *t, TString *key) {
Node *n = hashstr(t, key);
lua_assert(key->tsv.tt == LUA_TSHRSTR);
for (;;) { /* check whether `key' is somewhere in the chain */
if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))
lua_assert(key->tt == LUA_TSHRSTR);
for (;;) { /* check whether 'key' is somewhere in the chain */
const TValue *k = gkey(n);
if (ttisshrstring(k) && eqshrstr(tsvalue(k), key))
return gval(n); /* that's it */
else {
int nx = gnext(n);
@ -532,7 +551,7 @@ const TValue *luaH_getstr (Table *t, TString *key) {
*/
const TValue *luaH_get (Table *t, const TValue *key) {
switch (ttype(key)) {
case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
case LUA_TSHRSTR: return luaH_getstr(t, tsvalue(key));
case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
case LUA_TNIL: return luaO_nilobject;
#ifndef _KERNEL
@ -545,7 +564,7 @@ const TValue *luaH_get (Table *t, const TValue *key) {
#endif
default: {
Node *n = mainposition(t, key);
for (;;) { /* check whether `key' is somewhere in the chain */
for (;;) { /* check whether 'key' is somewhere in the chain */
if (luaV_rawequalobj(gkey(n), key))
return gval(n); /* that's it */
else {
@ -589,7 +608,7 @@ void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
static int unbound_search (Table *t, unsigned int j) {
unsigned int i = j; /* i is zero or a present index */
j++;
/* find `i' and `j' such that i is present and j is not */
/* find 'i' and 'j' such that i is present and j is not */
while (!ttisnil(luaH_getint(t, j))) {
i = j;
if (j > cast(unsigned int, MAX_INT)/2) { /* overflow? */
@ -611,7 +630,7 @@ static int unbound_search (Table *t, unsigned int j) {
/*
** Try to find a boundary in table `t'. A `boundary' is an integer index
** Try to find a boundary in table 't'. A 'boundary' is an integer index
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
*/
int luaH_getn (Table *t) {

View File

@ -1,7 +1,5 @@
/* $NetBSD: ltable.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: ltable.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: ltable.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
@ -13,10 +11,15 @@
#define gnode(t,i) (&(t)->node[i])
#define gkey(n) (&(n)->i_key.tvk)
#define gval(n) (&(n)->i_val)
#define gnext(n) ((n)->i_key.nk.next)
/* 'const' to avoid wrong writings that can mess up field 'next' */
#define gkey(n) cast(const TValue*, (&(n)->i_key.tvk))
#define wgkey(n) (&(n)->i_key.nk)
#define invalidateTMcache(t) ((t)->flags = 0)
@ -27,14 +30,15 @@
LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
TValue *value);
TValue *value);
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
LUAI_FUNC Table *luaH_new (lua_State *L);
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize);
LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
unsigned int nhsize);
LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);
LUAI_FUNC void luaH_free (lua_State *L, Table *t);
LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
LUAI_FUNC int luaH_getn (Table *t);

View File

@ -1,28 +1,62 @@
/* $NetBSD: ltablib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ltablib.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ltablib.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ltablib.c,v 1.79 2014/11/02 19:19:04 roberto Exp
** Library for Table Manipulation
** See Copyright Notice in lua.h
*/
#define ltablib_c
#define LUA_LIB
#include "lprefix.h"
#ifndef _KERNEL
#include <limits.h>
#include <stddef.h>
#endif
#define ltablib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))
/*
** Structure with table-access functions
*/
typedef struct {
int (*geti) (lua_State *L, int idx, lua_Integer n);
void (*seti) (lua_State *L, int idx, lua_Integer n);
} TabA;
/*
** Check that 'arg' has a table and set access functions in 'ta' to raw
** or non-raw according to the presence of corresponding metamethods.
*/
static void checktab (lua_State *L, int arg, TabA *ta) {
ta->geti = NULL; ta->seti = NULL;
if (lua_getmetatable(L, arg)) {
lua_pushliteral(L, "__index"); /* 'index' metamethod */
if (lua_rawget(L, -2) != LUA_TNIL)
ta->geti = lua_geti;
lua_pushliteral(L, "__newindex"); /* 'newindex' metamethod */
if (lua_rawget(L, -3) != LUA_TNIL)
ta->seti = lua_seti;
lua_pop(L, 3); /* pop metatable plus both metamethods */
}
if (ta->geti == NULL || ta->seti == NULL) {
luaL_checktype(L, arg, LUA_TTABLE); /* must be table for raw methods */
if (ta->geti == NULL) ta->geti = lua_rawgeti;
if (ta->seti == NULL) ta->seti = lua_rawseti;
}
}
#define aux_getn(L,n,ta) (checktab(L, n, ta), luaL_len(L, n))
#if defined(LUA_COMPAT_MAXN)
@ -44,7 +78,8 @@ static int maxn (lua_State *L) {
static int tinsert (lua_State *L) {
lua_Integer e = aux_getn(L, 1) + 1; /* first empty element */
TabA ta;
lua_Integer e = aux_getn(L, 1, &ta) + 1; /* first empty element */
lua_Integer pos; /* where to insert new element */
switch (lua_gettop(L)) {
case 2: { /* called with only 2 arguments */
@ -56,60 +91,97 @@ static int tinsert (lua_State *L) {
pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
for (i = e; i > pos; i--) { /* move up elements */
lua_rawgeti(L, 1, i-1);
lua_rawseti(L, 1, i); /* t[i] = t[i-1] */
(*ta.geti)(L, 1, i - 1);
(*ta.seti)(L, 1, i); /* t[i] = t[i - 1] */
}
break;
}
default: {
return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
return luaL_error(L, "wrong number of arguments to 'insert'");
}
}
lua_rawseti(L, 1, pos); /* t[pos] = v */
(*ta.seti)(L, 1, pos); /* t[pos] = v */
return 0;
}
static int tremove (lua_State *L) {
lua_Integer size = aux_getn(L, 1);
TabA ta;
lua_Integer size = aux_getn(L, 1, &ta);
lua_Integer pos = luaL_optinteger(L, 2, size);
if (pos != size) /* validate 'pos' if given */
luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
lua_rawgeti(L, 1, pos); /* result = t[pos] */
(*ta.geti)(L, 1, pos); /* result = t[pos] */
for ( ; pos < size; pos++) {
lua_rawgeti(L, 1, pos+1);
lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */
(*ta.geti)(L, 1, pos + 1);
(*ta.seti)(L, 1, pos); /* t[pos] = t[pos + 1] */
}
lua_pushnil(L);
lua_rawseti(L, 1, pos); /* t[pos] = nil */
(*ta.seti)(L, 1, pos); /* t[pos] = nil */
return 1;
}
static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
lua_rawgeti(L, 1, i);
static int tmove (lua_State *L) {
TabA ta;
lua_Integer f = luaL_checkinteger(L, 2);
lua_Integer e = luaL_checkinteger(L, 3);
lua_Integer t = luaL_checkinteger(L, 4);
int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
/* the following restriction avoids several problems with overflows */
luaL_argcheck(L, f > 0, 2, "initial position must be positive");
if (e >= f) { /* otherwise, nothing to move */
lua_Integer n, i;
ta.geti = (luaL_getmetafield(L, 1, "__index") == LUA_TNIL)
? (luaL_checktype(L, 1, LUA_TTABLE), lua_rawgeti)
: lua_geti;
ta.seti = (luaL_getmetafield(L, tt, "__newindex") == LUA_TNIL)
? (luaL_checktype(L, tt, LUA_TTABLE), lua_rawseti)
: lua_seti;
n = e - f + 1; /* number of elements to move */
if (t > f) {
for (i = n - 1; i >= 0; i--) {
(*ta.geti)(L, 1, f + i);
(*ta.seti)(L, tt, t + i);
}
}
else {
for (i = 0; i < n; i++) {
(*ta.geti)(L, 1, f + i);
(*ta.seti)(L, tt, t + i);
}
}
}
lua_pushvalue(L, tt); /* return "to table" */
return 1;
}
static void addfield (lua_State *L, luaL_Buffer *b, TabA *ta, lua_Integer i) {
(*ta->geti)(L, 1, i);
if (!lua_isstring(L, -1))
luaL_error(L, "invalid value (%s) at index %d in table for "
LUA_QL("concat"), luaL_typename(L, -1), i);
luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
luaL_typename(L, -1), i);
luaL_addvalue(b);
}
static int tconcat (lua_State *L) {
TabA ta;
luaL_Buffer b;
size_t lsep;
lua_Integer i, last;
const char *sep = luaL_optlstring(L, 2, "", &lsep);
luaL_checktype(L, 1, LUA_TTABLE);
checktab(L, 1, &ta);
i = luaL_optinteger(L, 3, 1);
last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1));
luaL_buffinit(L, &b);
for (; i < last; i++) {
addfield(L, &b, i);
addfield(L, &b, &ta, i);
luaL_addlstring(&b, sep, lsep);
}
if (i == last) /* add last value (if interval was not empty) */
addfield(L, &b, i);
addfield(L, &b, &ta, i);
luaL_pushresult(&b);
return 1;
}
@ -135,20 +207,21 @@ static int pack (lua_State *L) {
static int unpack (lua_State *L) {
TabA ta;
lua_Integer i, e;
lua_Unsigned n;
luaL_checktype(L, 1, LUA_TTABLE);
checktab(L, 1, &ta);
i = luaL_optinteger(L, 2, 1);
e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
if (i > e) return 0; /* empty range */
n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, ++n))
if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))
return luaL_error(L, "too many results to unpack");
do { /* must have at least one element */
lua_rawgeti(L, 1, i); /* push arg[i..e] */
(*ta.geti)(L, 1, i); /* push arg[i..e] */
} while (i++ < e);
return n;
return (int)n;
}
/* }====================================================== */
@ -158,15 +231,15 @@ static int unpack (lua_State *L) {
/*
** {======================================================
** Quicksort
** (based on `Algorithms in MODULA-3', Robert Sedgewick;
** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
** Addison-Wesley, 1993.)
** =======================================================
*/
static void set2 (lua_State *L, int i, int j) {
lua_rawseti(L, 1, i);
lua_rawseti(L, 1, j);
static void set2 (lua_State *L, TabA *ta, int i, int j) {
(*ta->seti)(L, 1, i);
(*ta->seti)(L, 1, j);
}
static int sort_comp (lua_State *L, int a, int b) {
@ -174,7 +247,7 @@ static int sort_comp (lua_State *L, int a, int b) {
int res;
lua_pushvalue(L, 2);
lua_pushvalue(L, a-1); /* -1 to compensate function */
lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
lua_call(L, 2, 1);
res = lua_toboolean(L, -1);
lua_pop(L, 1);
@ -184,45 +257,45 @@ static int sort_comp (lua_State *L, int a, int b) {
return lua_compare(L, a, b, LUA_OPLT);
}
static void auxsort (lua_State *L, int l, int u) {
static void auxsort (lua_State *L, TabA *ta, int l, int u) {
while (l < u) { /* for tail recursion */
int i, j;
/* sort elements a[l], a[(l+u)/2] and a[u] */
lua_rawgeti(L, 1, l);
lua_rawgeti(L, 1, u);
(*ta->geti)(L, 1, l);
(*ta->geti)(L, 1, u);
if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
set2(L, l, u); /* swap a[l] - a[u] */
set2(L, ta, l, u); /* swap a[l] - a[u] */
else
lua_pop(L, 2);
if (u-l == 1) break; /* only 2 elements */
i = (l+u)/2;
lua_rawgeti(L, 1, i);
lua_rawgeti(L, 1, l);
(*ta->geti)(L, 1, i);
(*ta->geti)(L, 1, l);
if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
set2(L, i, l);
set2(L, ta, i, l);
else {
lua_pop(L, 1); /* remove a[l] */
lua_rawgeti(L, 1, u);
(*ta->geti)(L, 1, u);
if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
set2(L, i, u);
set2(L, ta, i, u);
else
lua_pop(L, 2);
}
if (u-l == 2) break; /* only 3 elements */
lua_rawgeti(L, 1, i); /* Pivot */
(*ta->geti)(L, 1, i); /* Pivot */
lua_pushvalue(L, -1);
lua_rawgeti(L, 1, u-1);
set2(L, i, u-1);
(*ta->geti)(L, 1, u-1);
set2(L, ta, i, u-1);
/* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
i = l; j = u-1;
for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
/* repeat ++i until a[i] >= P */
while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) {
if (i>=u) luaL_error(L, "invalid order function for sorting");
lua_pop(L, 1); /* remove a[i] */
}
/* repeat --j until a[j] <= P */
while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) {
if (j<=l) luaL_error(L, "invalid order function for sorting");
lua_pop(L, 1); /* remove a[j] */
}
@ -230,11 +303,11 @@ static void auxsort (lua_State *L, int l, int u) {
lua_pop(L, 3); /* pop pivot, a[i], a[j] */
break;
}
set2(L, i, j);
set2(L, ta, i, j);
}
lua_rawgeti(L, 1, u-1);
lua_rawgeti(L, 1, i);
set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
(*ta->geti)(L, 1, u-1);
(*ta->geti)(L, 1, i);
set2(L, ta, u-1, i); /* swap pivot (a[u-1]) with a[i] */
/* a[l..i-1] <= a[i] == P <= a[i+1..u] */
/* adjust so that smaller half is in [j..i] and larger one in [l..u] */
if (i-l < u-i) {
@ -243,17 +316,18 @@ static void auxsort (lua_State *L, int l, int u) {
else {
j=i+1; i=u; u=j-2;
}
auxsort(L, j, i); /* call recursively the smaller one */
auxsort(L, ta, j, i); /* call recursively the smaller one */
} /* repeat the routine for the larger one */
}
static int sort (lua_State *L) {
int n = aux_getn(L, 1);
luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */
TabA ta;
int n = (int)aux_getn(L, 1, &ta);
luaL_checkstack(L, 50, ""); /* assume array is smaller than 2^50 */
if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
luaL_checktype(L, 2, LUA_TFUNCTION);
lua_settop(L, 2); /* make sure there is two arguments */
auxsort(L, 1, n);
lua_settop(L, 2); /* make sure there are two arguments */
auxsort(L, &ta, 1, n);
return 0;
}
@ -269,6 +343,7 @@ static const luaL_Reg tab_funcs[] = {
{"pack", pack},
{"unpack", unpack},
{"remove", tremove},
{"move", tmove},
{"sort", sort},
{NULL, NULL}
};

View File

@ -1,19 +1,21 @@
/* $NetBSD: ltm.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ltm.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ltm.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ltm.c,v 2.33 2014/11/21 12:15:57 roberto Exp
** Tag methods
** See Copyright Notice in lua.h
*/
#define ltm_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define ltm_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -93,7 +95,7 @@ const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
const TValue *p2, TValue *p3, int hasres) {
ptrdiff_t result = savestack(L, p3);
setobj2s(L, L->top++, f); /* push function */
setobj2s(L, L->top++, f); /* push function (assume EXTRA_STACK) */
setobj2s(L, L->top++, p1); /* 1st argument */
setobj2s(L, L->top++, p2); /* 2nd argument */
if (!hasres) /* no result? 'p3' is third argument */
@ -124,15 +126,17 @@ void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
switch (event) {
case TM_CONCAT:
luaG_concaterror(L, p1, p2);
case TM_IDIV: case TM_BAND: case TM_BOR: case TM_BXOR:
case TM_BAND: case TM_BOR: case TM_BXOR:
case TM_SHL: case TM_SHR: case TM_BNOT: {
lua_Number dummy;
if (tonumber(p1, &dummy) && tonumber(p2, &dummy))
luaG_tointerror(L, p1, p2);
else
luaG_opinterror(L, p1, p2, "perform bitwise operation on");
/* else go through */
}
default:
luaG_aritherror(L, p1, p2);
luaG_opinterror(L, p1, p2, "perform arithmetic on");
}
}
}

View File

@ -1,7 +1,7 @@
/* $NetBSD: ltm.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: ltm.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: ltm.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: ltm.h,v 2.21 2014/10/25 11:50:46 roberto Exp
** Tag methods
** See Copyright Notice in lua.h
*/
@ -23,7 +23,7 @@ typedef enum {
TM_GC,
TM_MODE,
TM_LEN,
TM_EQ, /* last tag method with `fast' access */
TM_EQ, /* last tag method with fast access */
TM_ADD,
TM_SUB,
TM_MUL,

View File

@ -1,19 +1,19 @@
/* $NetBSD: lua.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lua.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lua.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Lua stand-alone interpreter
** See Copyright Notice in lua.h
*/
#define lua_c
#include "lprefix.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lua_c
#include "lua.h"
#include "lauxlib.h"
@ -52,14 +52,14 @@
#include <unistd.h>
#define lua_stdin_is_tty() isatty(0)
#elif defined(LUA_WIN) /* }{ */
#elif defined(LUA_USE_WINDOWS) /* }{ */
#include <io.h>
#define lua_stdin_is_tty() _isatty(_fileno(stdin))
#else /* }{ */
/* ANSI definition */
/* ISO C definition */
#define lua_stdin_is_tty() 1 /* assume stdin is a tty */
#endif /* } */
@ -117,7 +117,7 @@ static void lstop (lua_State *L, lua_Debug *ar) {
/*
** Function to be called at a C signal. Because a C signal cannot
** just change a Lua state (as there is no proper syncronization),
** just change a Lua state (as there is no proper synchronization),
** this function only sets a hook that, when called, will stop the
** interpreter.
*/
@ -128,17 +128,17 @@ static void laction (int i) {
static void print_usage (const char *badoption) {
luai_writestringerror("%s: ", progname);
lua_writestringerror("%s: ", progname);
if (badoption[1] == 'e' || badoption[1] == 'l')
luai_writestringerror("'%s' needs argument\n", badoption);
lua_writestringerror("'%s' needs argument\n", badoption);
else
luai_writestringerror("unrecognized option '%s'\n", badoption);
luai_writestringerror(
lua_writestringerror("unrecognized option '%s'\n", badoption);
lua_writestringerror(
"usage: %s [options] [script [args]]\n"
"Available options are:\n"
" -e stat execute string " LUA_QL("stat") "\n"
" -i enter interactive mode after executing " LUA_QL("script") "\n"
" -l name require library " LUA_QL("name") "\n"
" -e stat execute string 'stat'\n"
" -i enter interactive mode after executing 'script'\n"
" -l name require library 'name'\n"
" -v show version information\n"
" -E ignore environment variables\n"
" -- stop handling options\n"
@ -153,41 +153,41 @@ static void print_usage (const char *badoption) {
** (if present)
*/
static void l_message (const char *pname, const char *msg) {
if (pname) luai_writestringerror("%s: ", pname);
luai_writestringerror("%s\n", msg);
if (pname) lua_writestringerror("%s: ", pname);
lua_writestringerror("%s\n", msg);
}
/*
** Check whether 'status' is not OK and, if so, prints the error
** message on the top of the stack. Because this function can be called
** unprotected, it only accepts actual strings as error messages. (A
** coercion could raise a memory error.)
** message on the top of the stack. It assumes that the error object
** is a string, as it was either generated by Lua or by 'msghandler'.
*/
static int report (lua_State *L, int status) {
if (status != LUA_OK) {
const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
: NULL;
if (msg == NULL) msg = "(error object is not a string)";
const char *msg = lua_tostring(L, -1);
l_message(progname, msg);
lua_pop(L, 1);
lua_pop(L, 1); /* remove message */
}
return status;
}
/*
** Message handler to be used to run all chunks
** Message handler used to run all chunks
*/
static int msghandler (lua_State *L) {
const char *msg = lua_tostring(L, 1);
if (msg) /* is error object a string? */
luaL_traceback(L, L, msg, 1); /* use standard traceback */
else if (!lua_isnoneornil(L, 1)) { /* non-string error object? */
if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
lua_pushliteral(L, "(no error message)");
} /* else no error object, does nothing */
return 1;
if (msg == NULL) { /* is error object not a string? */
if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
return 1; /* that is the message */
else
msg = lua_pushfstring(L, "(error object is a %s value)",
luaL_typename(L, 1));
}
luaL_traceback(L, L, msg, 1); /* append a standard traceback */
return 1; /* return the traceback */
}
@ -210,8 +210,8 @@ static int docall (lua_State *L, int narg, int nres) {
static void print_version (void) {
luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
luai_writeline();
lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
lua_writeline();
}
@ -286,7 +286,7 @@ static const char *get_prompt (lua_State *L, int firstline) {
/*
** Check whether 'status' signals a syntax error and the error
** message at the top of the stack ends with the above mark for
** incoplete statements.
** incomplete statements.
*/
static int incomplete (lua_State *L, int status) {
if (status == LUA_ERRSYNTAX) {
@ -391,9 +391,8 @@ static void l_print (lua_State *L) {
lua_getglobal(L, "print");
lua_insert(L, 1);
if (lua_pcall(L, n, 0, 0) != LUA_OK)
l_message(progname, lua_pushfstring(L,
"error calling " LUA_QL("print") " (%s)",
lua_tostring(L, -1)));
l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
lua_tostring(L, -1)));
}
}
@ -413,31 +412,36 @@ static void doREPL (lua_State *L) {
else report(L, status);
}
lua_settop(L, 0); /* clear stack */
luai_writeline();
lua_writeline();
progname = oldprogname;
}
/*
** Push on the stack 'n' strings from 'argv'
** Push on the stack the contents of table 'arg' from 1 to #arg
*/
static void pushargs (lua_State *L, char **argv, int n) {
int i;
static int pushargs (lua_State *L) {
int i, n;
if (lua_getglobal(L, "arg") != LUA_TTABLE)
luaL_error(L, "'arg' is not a table");
n = (int)luaL_len(L, -1);
luaL_checkstack(L, n + 3, "too many arguments to script");
for (i = 1; i < n; i++) /* skip 0 (the script name) */
lua_pushstring(L, argv[i]);
for (i = 1; i <= n; i++)
lua_rawgeti(L, -i, i);
lua_remove(L, -i); /* remove table from the stack */
return n;
}
static int handle_script (lua_State *L, char **argv, int n) {
static int handle_script (lua_State *L, char **argv) {
int status;
const char *fname = argv[0];
if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
fname = NULL; /* stdin */
status = luaL_loadfile(L, fname);
if (status == LUA_OK) {
pushargs(L, argv, n); /* push arguments to script */
status = docall(L, n - 1, LUA_MULTRET);
int n = pushargs(L); /* push arguments to script */
status = docall(L, n, LUA_MULTRET);
}
return report(L, status);
}
@ -572,7 +576,7 @@ static int pmain (lua_State *L) {
if (!runargs(L, argv, script)) /* execute arguments -e and -l */
return 0; /* something failed */
if (script < argc && /* execute main script (if there is one) */
handle_script(L, argv + script, argc - script) != LUA_OK)
handle_script(L, argv + script) != LUA_OK)
return 0;
if (args & has_i) /* -i option? */
doREPL(L); /* do read-eval-print loop */

View File

@ -1,7 +1,7 @@
/* $NetBSD: lua.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lua.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lua.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lua.h,v 1.325 2014/12/26 17:24:27 roberto Exp
** Lua - A Scripting Language
** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
** See Copyright Notice at the end of this file
@ -11,8 +11,8 @@
#ifndef lua_h
#define lua_h
#ifndef _KERNEL
#include <stdarg.h>
#ifndef _KERNEL
#include <stddef.h>
#endif
@ -24,26 +24,25 @@
#define LUA_VERSION_MINOR "3"
#define LUA_VERSION_NUM 503
#ifndef _KERNEL
#define LUA_VERSION_RELEASE "0 (work3)"
#else
#define LUA_VERSION_RELEASE "0 (work3) (kernel)"
#define LUA_VERSION_RELEASE "0"
#else /* _KERNEL */
#define LUA_VERSION_RELEASE "0 (kernel)"
#endif
#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
#ifndef _KERNEL
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2014 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
#else
#define LUA_COPYRIGHT LUA_RELEASE " " \
"Copyright (c) 2014, Lourival Vieira Neto <lneto@NetBSD.org>. " \
"Copyright (C) 1994-2014 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" \
", L. Vieira Neto"
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2015 Lua.org, PUC-Rio"
#else /* _KERNEL */
#define LUA_COPYRIGHT LUA_RELEASE \
" Copyright (c) 2015, Lourival Vieira Neto <lneto@NetBSD.org>." \
" Copyright (C) 1994-2015 Lua.org, PUC-Rio"
#endif
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
/* mark for precompiled code ('<esc>Lua') */
#define LUA_SIGNATURE "\033Lua"
#define LUA_SIGNATURE "\x1bLua"
/* option for multiple returns in 'lua_pcall' and 'lua_call' */
#define LUA_MULTRET (-1)
@ -68,30 +67,6 @@
typedef struct lua_State lua_State;
/*
** Type for C functions registered with Lua
*/
typedef int (*lua_CFunction) (lua_State *L);
/*
** Type for continuation functions
*/
typedef int (*lua_KFunction) (lua_State *L, int status, int ctx);
/*
** functions that read/write blocks when loading/dumping Lua chunks
*/
typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);
/*
** prototype for memory-allocation functions
*/
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
/*
** basic types
@ -132,6 +107,34 @@ typedef LUA_INTEGER lua_Integer;
/* unsigned integer type */
typedef LUA_UNSIGNED lua_Unsigned;
/* type for continuation-function contexts */
typedef LUA_KCONTEXT lua_KContext;
/*
** Type for C functions registered with Lua
*/
typedef int (*lua_CFunction) (lua_State *L);
/*
** Type for continuation functions
*/
typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
/*
** Type for functions that read/write blocks when loading/dumping Lua chunks
*/
typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);
/*
** Type for memory-allocation functions
*/
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
/*
@ -169,9 +172,8 @@ LUA_API int (lua_gettop) (lua_State *L);
LUA_API void (lua_settop) (lua_State *L, int idx);
LUA_API void (lua_pushvalue) (lua_State *L, int idx);
LUA_API void (lua_rotate) (lua_State *L, int idx, int n);
LUA_API void (lua_replace) (lua_State *L, int idx);
LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx);
LUA_API int (lua_checkstack) (lua_State *L, int sz);
LUA_API int (lua_checkstack) (lua_State *L, int n);
LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);
@ -180,7 +182,11 @@ LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);
** access functions (stack -> C)
*/
#ifndef _KERNEL
LUA_API int (lua_isnumber) (lua_State *L, int idx);
#else /* _KERNEL */
#define lua_isnumber lua_isinteger
#endif
LUA_API int (lua_isstring) (lua_State *L, int idx);
LUA_API int (lua_iscfunction) (lua_State *L, int idx);
LUA_API int (lua_isinteger) (lua_State *L, int idx);
@ -188,9 +194,12 @@ LUA_API int (lua_isuserdata) (lua_State *L, int idx);
LUA_API int (lua_type) (lua_State *L, int idx);
LUA_API const char *(lua_typename) (lua_State *L, int tp);
#ifndef _KERNEL
LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum);
#else /* _KERNEL */
#define lua_tonumberx (lua_Integer) lua_tointegerx
#endif
LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum);
LUA_API lua_Unsigned (lua_tounsignedx) (lua_State *L, int idx, int *isnum);
LUA_API int (lua_toboolean) (lua_State *L, int idx);
LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
LUA_API size_t (lua_rawlen) (lua_State *L, int idx);
@ -219,7 +228,7 @@ LUA_API const void *(lua_topointer) (lua_State *L, int idx);
#define LUA_OPSHR 11
#define LUA_OPUNM 12
#define LUA_OPBNOT 13
#else
#else /* _KERNEL */
#define LUA_OPIDIV 4
#define LUA_OPBAND 5
#define LUA_OPBOR 6
@ -244,10 +253,13 @@ LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op);
** push functions (C -> stack)
*/
LUA_API void (lua_pushnil) (lua_State *L);
#ifndef _KERNEL
LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);
#else /* _KERNEL */
#define lua_pushnumber(L, n) lua_pushinteger(L, (lua_Integer)(n))
#endif
LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);
LUA_API void (lua_pushunsigned) (lua_State *L, lua_Unsigned n);
LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l);
LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);
LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
va_list argp);
@ -261,9 +273,10 @@ LUA_API int (lua_pushthread) (lua_State *L);
/*
** get functions (Lua -> stack)
*/
LUA_API int (lua_getglobal) (lua_State *L, const char *var);
LUA_API int (lua_getglobal) (lua_State *L, const char *name);
LUA_API int (lua_gettable) (lua_State *L, int idx);
LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);
LUA_API int (lua_rawget) (lua_State *L, int idx);
LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
@ -277,9 +290,10 @@ LUA_API int (lua_getuservalue) (lua_State *L, int idx);
/*
** set functions (stack -> Lua)
*/
LUA_API void (lua_setglobal) (lua_State *L, const char *var);
LUA_API void (lua_setglobal) (lua_State *L, const char *name);
LUA_API void (lua_settable) (lua_State *L, int idx);
LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);
LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n);
LUA_API void (lua_rawset) (lua_State *L, int idx);
LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);
@ -290,17 +304,16 @@ LUA_API void (lua_setuservalue) (lua_State *L, int idx);
/*
** 'load' and 'call' functions (load and run Lua code)
*/
LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
lua_KFunction k);
LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults,
lua_KContext ctx, lua_KFunction k);
#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL)
LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
int ctx, lua_KFunction k);
lua_KContext ctx, lua_KFunction k);
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
const char *chunkname,
const char *mode);
const char *chunkname, const char *mode);
LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
@ -308,12 +321,13 @@ LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
/*
** coroutine functions
*/
LUA_API int (lua_yieldk) (lua_State *L, int nresults, int ctx,
lua_KFunction k);
LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx,
lua_KFunction k);
LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);
LUA_API int (lua_status) (lua_State *L);
LUA_API int (lua_isyieldable) (lua_State *L);
#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)
LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);
LUA_API int (lua_status) (lua_State *L);
LUA_API int lua_isyieldable (lua_State *L);
/*
@ -344,7 +358,7 @@ LUA_API int (lua_next) (lua_State *L, int idx);
LUA_API void (lua_concat) (lua_State *L, int n);
LUA_API void (lua_len) (lua_State *L, int idx);
LUA_API size_t (lua_strtonum) (lua_State *L, const char *s);
LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s);
LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
@ -352,14 +366,15 @@ LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
/*
** ===============================================================
** {==============================================================
** some useful macros
** ===============================================================
*/
#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE))
#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL)
#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL)
#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL)
#define lua_pop(L,n) lua_settop(L, -(n)-1)
@ -391,6 +406,24 @@ LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1))
#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1))
/* }============================================================== */
/*
** {==============================================================
** compatibility macros for unsigned conversions
** ===============================================================
*/
#if defined(LUA_COMPAT_APIINTCASTS)
#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is))
#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL)
#endif
/* }============================================================== */
/*
** {======================================================================
@ -463,8 +496,10 @@ struct lua_Debug {
/******************************************************************************
* Copyright (c) 2014, Lourival Vieira Neto <lneto@NetBSD.org>.
* Copyright (C) 1994-2014 Lua.org, PUC-Rio.
#ifdef _KERNEL
* Copyright (c) 2015, Lourival Vieira Neto <lneto@NetBSD.org>.
#endif
* Copyright (C) 1994-2015 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

View File

@ -1,19 +1,20 @@
/* $NetBSD: luac.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: luac.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Lua compiler (saves bytecodes to files; also list bytecodes)
** $Id: luac.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Lua compiler (saves bytecodes to files; also lists bytecodes)
** See Copyright Notice in lua.h
*/
#define luac_c
#define LUA_CORE
#include "lprefix.h"
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define luac_c
#define LUA_CORE
#include "lua.h"
#include "lauxlib.h"
@ -49,14 +50,14 @@ static void cannot(const char* what)
static void usage(const char* message)
{
if (*message=='-')
fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message);
else
fprintf(stderr,"%s: %s\n",progname,message);
fprintf(stderr,
"usage: %s [options] [filenames]\n"
"Available options are:\n"
" -l list (use -l -l for full listing)\n"
" -o name output to file " LUA_QL("name") " (default is \"%s\")\n"
" -o name output to file 'name' (default is \"%s\")\n"
" -p parse only\n"
" -s strip debug information\n"
" -v show version information\n"
@ -91,7 +92,7 @@ static int doargs(int argc, char* argv[])
{
output=argv[++i];
if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
usage(LUA_QL("-o") " needs argument");
usage("'-o' needs argument");
if (IS("-")) output=NULL;
}
else if (IS("-p")) /* parse only */
@ -205,7 +206,7 @@ int main(int argc, char* argv[])
}
/*
** $Id: luac.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: luac.c,v 1.3 2015/02/02 14:03:05 lneto Exp $
** print bytecodes
** See Copyright Notice in lua.h
*/
@ -225,7 +226,7 @@ int main(int argc, char* argv[])
static void PrintString(const TString* ts)
{
const char* s=getstr(ts);
size_t i,n=ts->tsv.len;
size_t i,n=ts->len;
printf("%c",'"');
for (i=0; i<n; i++)
{
@ -261,16 +262,19 @@ static void PrintConstant(const Proto* f, int i)
case LUA_TBOOLEAN:
printf(bvalue(o) ? "true" : "false");
break;
#ifndef _KERNEL
case LUA_TNUMFLT:
printf(LUA_NUMBER_FMT,fltvalue(o));
{
char buff[100];
sprintf(buff,LUA_NUMBER_FMT,fltvalue(o));
printf("%s",buff);
if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0");
break;
#endif
}
case LUA_TNUMINT:
printf(LUA_INTEGER_FMT,ivalue(o));
break;
case LUA_TSHRSTR: case LUA_TLNGSTR:
PrintString(rawtsvalue(o));
PrintString(tsvalue(o));
break;
default: /* cannot happen */
printf("? type=%d",ttype(o));
@ -344,10 +348,8 @@ static void PrintCode(const Proto* f)
case OP_ADD:
case OP_SUB:
case OP_MUL:
#ifndef _KERNEL
case OP_POW:
case OP_DIV:
#endif
case OP_IDIV:
case OP_BAND:
case OP_BOR:

View File

@ -1,109 +1,162 @@
/* $NetBSD: luaconf.h,v 1.10 2014/11/30 19:00:46 lneto Exp $ */
/* $NetBSD: luaconf.h,v 1.11 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: luaconf.h,v 1.10 2014/11/30 19:00:46 lneto Exp $
** Id: luaconf.h,v 1.238 2014/12/29 13:27:55 roberto Exp
** Configuration file for Lua
** See Copyright Notice in lua.h
*/
#ifndef lconfig_h
#define lconfig_h
#ifndef luaconf_h
#define luaconf_h
#ifndef _KERNEL
#include <limits.h>
#include <stddef.h>
#else
/* limits.h */
#include <machine/limits.h>
#include <sys/systm.h>
#endif
/*
** ==================================================================
** ===================================================================
** Search for "@@" to find all configurable definitions.
** ===================================================================
*/
/*
** ===================================================================
@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines type for
@@ Lua integers;
@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines
@@ type for Lua floats.
**
** These definitions set the numeric types for Lua. Lua should work
** fine with any mix of these previous options.
** The usual configurations are 64-bit integers and floats (the default)
** and 32-bit integers and floats (Small Lua, for restricted hardware).
** {====================================================================
** System Configuration: macros to adapt (if needed) Lua to some
** particular platform, for instance compiling it with 32-bit numbers or
** restricting it to C89.
** =====================================================================
*/
#define LUA_INT_LONGLONG
#define LUA_REAL_DOUBLE
/*
@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You
** can also define LUA_32BITS in the make file, but changing here you
** ensure that all software connected to Lua will be compiled with the
** same configuration.
*/
/* #define LUA_32BITS */
/*
@@ LUA_ANSI controls the use of non-ansi features.
** CHANGE it (define it) if you want Lua to avoid the use of any
** non-ansi feature or library.
@@ LUA_USE_C89 controls the use of non-ISO-C89 features.
** Define it if you want Lua to avoid the use of a few C99 features
** or Windows-specific features on Windows.
*/
#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__)
#define LUA_ANSI
/* #define LUA_USE_C89 */
/*
** By default, Lua on Windows use (some) specific Windows features
*/
#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE)
#define LUA_USE_WINDOWS /* enable goodies for regular Windows */
#endif
#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE)
#define LUA_WIN /* enable goodies for regular Windows platforms */
#if defined(LUA_USE_WINDOWS)
#define LUA_DL_DLL /* enable support for DLL */
#define LUA_USE_C89 /* broadly, Windows is C89 */
#endif
#if defined(LUA_WIN)
#define LUA_DL_DLL
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#endif
#if defined(LUA_USE_LINUX)
#define LUA_USE_C99
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
#define LUA_USE_READLINE /* needs some extra libraries */
#endif
#if defined(LUA_USE_MACOSX)
#define LUA_USE_C99
#define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* does not need -ldl */
#define LUA_USE_DLOPEN /* MacOS does not need -ldl */
#define LUA_USE_READLINE /* needs an extra library: -lreadline */
#endif
/*
@@ LUA_USE_C99 includes all functionality that depends on C 99.
** CHANGE it (define it) if your system is compatible.
@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
** C89 ('long' and 'double'); Windows always has '__int64', so it does
** not need to use this case.
*/
#if defined(LUA_USE_C99)
#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
#define LUA_C89_NUMBERS
#endif
/*
@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'.
*/
/* avoid undefined shifts */
#if ((INT_MAX >> 15) >> 15) >= 1
#define LUAI_BITSINT 32
#else
/* 'int' always must have at least 16 bits */
#define LUAI_BITSINT 16
#endif
/*
@@ LUA_USE_POSIX includes all functionality listed as X/Open System
@@ Interfaces Extension (XSI).
** CHANGE it (define it) if your system is XSI compatible.
@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines the type for
** Lua integers.
@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines
** the type for Lua floats.
** Lua should work fine with any mix of these options (if supported
** by your C compiler). The usual configurations are 64-bit integers
** and 'double' (the default), 32-bit integers and 'float' (for
** restricted platforms), and 'long'/'double' (for C compilers not
** compliant with C99, which may not have support for 'long long').
*/
#if defined(LUA_USE_POSIX)
#if defined(LUA_32BITS) /* { */
/*
** 32-bit integers and 'float'
*/
#if LUAI_BITSINT >= 32 /* use 'int' if big enough */
#define LUA_INT_INT
#else /* otherwise use 'long' */
#define LUA_INT_LONG
#endif
#define LUA_REAL_FLOAT
#elif defined(LUA_C89_NUMBERS) /* }{ */
/*
** largest types available for C89 ('long' and 'double')
*/
#define LUA_INT_LONG
#define LUA_REAL_DOUBLE
#else /* }{ */
/*
** default configuration for 64-bit Lua ('long long' and 'double')
*/
#define LUA_INT_LONGLONG
#define LUA_REAL_DOUBLE
#endif /* } */
/* }================================================================== */
/*
** {==================================================================
** Configuration for Paths.
** ===================================================================
*/
/*
@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
@@ Lua libraries.
** Lua libraries.
@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
@@ C libraries.
** C libraries.
** CHANGE them if your machine has a non-conventional directory
** hierarchy or if you want to install your libraries in
** non-conventional directories.
@ -120,7 +173,7 @@
#define LUA_PATH_DEFAULT \
LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \
LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \
LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \
".\\?.lua;" ".\\?\\init.lua"
#define LUA_CPATH_DEFAULT \
LUA_CDIR"?.dll;" \
@ -152,14 +205,14 @@
#define LUA_DIRSEP "/"
#endif
/* }================================================================== */
/*
@@ LUA_ENV is the name of the variable that holds the current
@@ environment, used to access global names.
** CHANGE it if you do not like this name.
** {==================================================================
** Marks for exported symbols in the C code
** ===================================================================
*/
#define LUA_ENV "_ENV"
/*
@@ LUA_API is a mark for all core API functions.
@ -192,10 +245,10 @@
/*
@@ LUAI_FUNC is a mark for all extern functions that are not to be
@@ exported to outside modules.
** exported to outside modules.
@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables
@@ that are not to be exported to outside modules (LUAI_DDEF for
@@ definitions and LUAI_DDEC for declarations).
** that are not to be exported to outside modules (LUAI_DDEF for
** definitions and LUAI_DDEC for declarations).
** CHANGE them if you need to mark them in some special way. Elf/gcc
** (versions 3.2 and later) mark them as "hidden" to optimize access
** when Lua is compiled as a shared library. Not all elf targets support
@ -207,62 +260,14 @@
#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
defined(__ELF__) /* { */
#define LUAI_FUNC __attribute__((visibility("hidden"))) extern
#else /* }{ */
#define LUAI_FUNC extern
#endif /* } */
#define LUAI_DDEC LUAI_FUNC
#define LUAI_DDEF /* empty */
#else /* }{ */
#define LUAI_FUNC extern
#define LUAI_DDEC extern
#define LUAI_DDEF /* empty */
#endif /* } */
/*
@@ LUA_QL describes how error messages quote program elements.
** CHANGE it if you want a different appearance.
*/
#define LUA_QL(x) "'" x "'"
#define LUA_QS LUA_QL("%s")
/*
@@ LUA_IDSIZE gives the maximum size for the description of the source
@@ of a function in debug information.
** CHANGE it if you want a different size.
*/
#define LUA_IDSIZE 60
#ifndef _KERNEL
/*
@@ luai_writestring/luai_writeline define how 'print' prints its results.
** They are only used in libraries and the stand-alone program. (The #if
** avoids including 'stdio.h' everywhere.)
*/
#if defined(LUA_LIB) || defined(lua_c)
#include <stdio.h>
#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout))
#endif
#endif
/*
@@ luai_writestringerror defines how to print error messages.
** (A format string with one argument is enough for Lua...)
*/
#define luai_writestringerror(s,p) \
(fprintf(stderr, (s), (p)), fflush(stderr))
/*
@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is,
** strings that are internalized. (Cannot be smaller than reserved words
** or tags for metamethods, as these strings must be internalized;
** #("function") = 8, #("__newindex") = 10.)
*/
#define LUAI_MAXSHORTLEN 40
/* }================================================================== */
/*
@ -290,6 +295,18 @@
*/
#define LUA_COMPAT_BITLIB
/*
@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod.
*/
#define LUA_COMPAT_IPAIRS
/*
@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for
** manipulating other integer types (lua_pushunsigned, lua_tounsigned,
** luaL_checkint, luaL_checklong, etc.)
*/
#define LUA_COMPAT_APIINTCASTS
/*
@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a
@ -367,69 +384,6 @@
/*
@@ LUAI_BITSINT defines the number of bits in an int.
** CHANGE here if Lua cannot automatically detect the number of bits of
** your machine. Probably you do not need to change this.
*/
/* avoid overflows in comparison */
#if INT_MAX-20 < 32760 /* { */
#define LUAI_BITSINT 16
#elif INT_MAX > 2147483640L /* }{ */
/* int has at least 32 bits */
#define LUAI_BITSINT 32
#else /* }{ */
#error "you must define LUA_BITSINT with number of bits in an integer"
#endif /* } */
/*
@@ LUA_INT32 is an signed integer with exactly 32 bits.
@@ LUAI_UMEM is an unsigned integer big enough to count the total
@@ memory used by Lua.
@@ LUAI_MEM is a signed integer big enough to count the total memory
@@ used by Lua.
** CHANGE here if for some weird reason the default definitions are not
** good enough for your machine. Probably you do not need to change
** this.
*/
#if LUAI_BITSINT >= 32 /* { */
#define LUA_INT32 int
#define LUAI_UMEM size_t
#define LUAI_MEM ptrdiff_t
#else /* }{ */
/* 16-bit ints */
#define LUA_INT32 long
#define LUAI_UMEM unsigned long
#define LUAI_MEM long
#endif /* } */
/*
@@ LUAI_MAXSTACK limits the size of the Lua stack.
** CHANGE it if you need a different limit. This limit is arbitrary;
** its only purpose is to stop Lua from consuming unlimited stack
** space (and to reserve some numbers for pseudo-indices).
*/
#if LUAI_BITSINT >= 32
#define LUAI_MAXSTACK 1000000
#else
#define LUAI_MAXSTACK 15000
#endif
/* reserve some space for error handling */
#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000)
/*
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
** CHANGE it if it uses too much C-stack space.
*/
#define LUAL_BUFFERSIZE BUFSIZ
/*
** {==================================================================
** Configuration for Numbers.
@ -448,7 +402,7 @@
@@ LUA_NUMBER_FMT is the format for writing floats.
@@ lua_number2str converts a float to a string.
**
@@ l_mathop allows the addition of an 'l' or 'f' to all math operations
@@ l_mathop allows the addition of an 'l' or 'f' to all math operations.
**
@@ lua_str2number converts a decimal numeric string to a number.
*/
@ -500,34 +454,20 @@
#endif /* } */
#if defined(LUA_ANSI)
/* C89 does not support 'opf' variants for math functions */
#undef l_mathop
#define l_mathop(op) (lua_Number)op
#endif
#if defined(LUA_ANSI) || defined(_WIN32)
/* C89 and Windows do not support 'strtof'... */
#undef lua_str2number
#define lua_str2number(s,p) ((lua_Number)strtod((s), (p)))
#endif
#define l_floor(x) (l_mathop(floor)(x))
#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
/*
@@ lua_numtointeger converts a float number to an integer, or
@@ lua_numbertointeger converts a float number to an integer, or
** returns 0 if float is not within the range of a lua_Integer.
** (The range comparisons are tricky because of rounding. The tests
** here assume a two-complement representation, where MININTEGER always
** has an exact representation as a float; MAXINTEGER may not have one,
** and therefore its conversion to float may have an ill-defined value.)
*/
#define lua_numtointeger(n,p) \
#define lua_numbertointeger(n,p) \
((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
(n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
(*(p) = (LUA_INTEGER)(n), 1))
@ -542,11 +482,25 @@
/* the following operations need the math library */
#if defined(lobject_c) || defined(lvm_c)
#include <math.h>
/* floor division (defined as 'floor(a/b)') */
#define luai_numidiv(L,a,b) ((void)L, l_mathop(floor)(luai_numdiv(L,a,b)))
/*
** module: defined as 'a - floor(a/b)*b'; the previous definition gives
** NaN when 'b' is huge, but the result should be 'a'. 'fmod' gives the
** result of 'a - trunc(a/b)*b', and therefore must be corrected when
** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a
** non-integer negative result, which is equivalent to the test below
*/
#define luai_nummod(L,a,b,m) \
{ (m) = l_mathop(fmod)(a,b); if ((m) != 0 && (a)*(b) < 0) (m) += (b); }
{ (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); }
/* exponentiation */
#define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b))
#endif
#endif
#endif /*_KERNEL */
/* these are quite standard operations */
#if defined(LUA_CORE)
@ -562,14 +516,6 @@
#endif
/*
** The following macro checks whether an operation is not safe to be
** performed by the constant folder. It should result in zero only if
** the operation is safe.
*/
#define luai_numinvalidop(op,a,b) 0
/*
@@ LUA_INTEGER is the integer type used by Lua.
**
@ -581,7 +527,6 @@
@@ LUA_INTEGER_FMT is the format for writing integers.
@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.
@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.
@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED.
@@ lua_integer2str converts an integer to a string.
*/
@ -607,7 +552,6 @@
#define LUA_INTEGER int
#define LUA_INTEGER_FRMLEN ""
#define LUA_MAXUNSIGNED UINT_MAX
#define LUA_MAXINTEGER INT_MAX
#define LUA_MININTEGER INT_MIN
@ -616,52 +560,35 @@
#define LUA_INTEGER long
#define LUA_INTEGER_FRMLEN "l"
#define LUA_MAXUNSIGNED ULONG_MAX
#define LUA_MAXINTEGER LONG_MAX
#define LUA_MININTEGER LONG_MIN
#elif defined(LUA_INT_LONGLONG) /* }{ long long */
#if defined(_WIN32)
#define LUA_INTEGER __int64
#define LUA_INTEGER_FRMLEN "I64"
#define LUA_MAXUNSIGNED _UI64_MAX
#define LUA_MAXINTEGER _I64_MAX
#define LUA_MININTEGER _I64_MIN
#else
#if defined(LLONG_MAX) /* { */
/* use ISO C99 stuff */
#define LUA_INTEGER long long
#define LUA_INTEGER_FRMLEN "ll"
#define LUA_MAXUNSIGNED ULLONG_MAX
#define LUA_MAXINTEGER LLONG_MAX
#define LUA_MININTEGER LLONG_MIN
#endif
#elif defined(LUA_USE_WINDOWS) /* }{ */
/* in Windows, can use specific Windows types */
#elif defined(LUA_INT_SHORT) /* }{ short int */
/*
** this option is for tests only; it is not particularly useful and
** it does not pass the test suit.
*/
#define LUA_INTEGER __int64
#define LUA_INTEGER_FRMLEN "I64"
#define LUA_INTEGER short int
#define LUA_INTEGER_FRMLEN ""
#define LUA_MAXINTEGER _I64_MAX
#define LUA_MININTEGER _I64_MIN
#define LUA_MAXUNSIGNED ((LUA_UNSIGNED)USHRT_MAX)
#define LUA_MAXINTEGER SHRT_MAX
#define LUA_MININTEGER SHRT_MIN
#else /* }{ */
#undef LUAI_UACINT
#define LUAI_UACINT int
#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \
or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)"
#undef LUAI_MAXSTACK
#define LUAI_MAXSTACK 15000
#define l_castS2U(x) ((LUA_UNSIGNED)(unsigned short)(x))
#endif /* } */
#else /* }{ */
@ -672,6 +599,134 @@
/* }================================================================== */
/*
** {==================================================================
** Dependencies with C99
** ===================================================================
*/
/*
@@ lua_strx2number converts an hexadecimal numeric string to a number.
** In C99, 'strtod' does both conversions. Otherwise, you can
** leave 'lua_strx2number' undefined and Lua will provide its own
** implementation.
*/
#if !defined(LUA_USE_C89)
#define lua_strx2number(s,p) lua_str2number(s,p)
#endif
/*
@@ LUA_USE_AFORMAT allows '%a'/'%A' specifiers in 'string.format'
** Enable it if the C function 'printf' supports these specifiers.
** (C99 demands it and Windows also supports it.)
*/
#if !defined(LUA_USE_C89) || defined(LUA_USE_WINDOWS)
#define LUA_USE_AFORMAT
#endif
/*
** 'strtof' and 'opf' variants for math functions are not valid in
** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the
** availability of these variants. ('math.h' is already included in
** all files that use these macros.)
*/
#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF))
#undef l_mathop /* variants not available */
#undef lua_str2number
#define l_mathop(op) (lua_Number)op /* no variant */
#define lua_str2number(s,p) ((lua_Number)strtod((s), (p)))
#endif
/*
@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation
** functions. It must be a numerical type; Lua will use 'intptr_t' if
** available, otherwise it will use 'ptrdiff_t' (the nearest thing to
** 'intptr_t' in C89)
*/
#define LUA_KCONTEXT ptrdiff_t
#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
__STDC_VERSION__ >= 199901L
#include <stdint.h>
#if defined (INTPTR_MAX) /* even in C99 this type is optional */
#undef LUA_KCONTEXT
#define LUA_KCONTEXT intptr_t
#endif
#endif
/* }================================================================== */
/*
** {==================================================================
** Macros that affect the API and must be stable (that is, must be the
** same when you compile Lua and when you compile code that links to
** Lua). You probably do not want/need to change them.
** =====================================================================
*/
/*
@@ LUAI_MAXSTACK limits the size of the Lua stack.
** CHANGE it if you need a different limit. This limit is arbitrary;
** its only purpose is to stop Lua from consuming unlimited stack
** space (and to reserve some numbers for pseudo-indices).
*/
#if LUAI_BITSINT >= 32
#define LUAI_MAXSTACK 1000000
#else
#define LUAI_MAXSTACK 15000
#endif
/* reserve some space for error handling */
#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000)
/*
@@ LUA_EXTRASPACE defines the size of a raw memory area associated with
** a Lua state with very fast access.
** CHANGE it if you need a different size.
*/
#define LUA_EXTRASPACE (sizeof(void *))
/*
@@ LUA_IDSIZE gives the maximum size for the description of the source
@@ of a function in debug information.
** CHANGE it if you want a different size.
*/
#define LUA_IDSIZE 60
/*
@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is,
** strings that are internalized. (Cannot be smaller than reserved words
** or tags for metamethods, as these strings must be internalized;
** #("function") = 8, #("__newindex") = 10.)
*/
#define LUAI_MAXSHORTLEN 40
/*
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
** CHANGE it if it uses too much C-stack space.
*/
#define LUAL_BUFFERSIZE ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer)))
/* }================================================================== */
/*
@@ LUA_QL describes how error messages quote program elements.
** Lua does not use these macros anymore; they are here for
** compatibility only.
*/
#define LUA_QL(x) "'" x "'"
#define LUA_QS LUA_QL("%s")
/* =================================================================== */
@ -682,7 +737,8 @@
*/
#ifdef __NetBSD__
/* Lua integers */
/* Integer types */
#undef LUA_INTEGER
#undef LUA_INTEGER_FRMLEN
#undef LUA_UNSIGNED
@ -698,8 +754,10 @@
#define LUA_MININTEGER INTMAX_MIN
#ifndef _KERNEL
#include <stdint.h>
#else
#else /* _KERNEL */
#undef LUA_NUMBER
#undef LUA_NUMBER_FMT
@ -709,8 +767,10 @@
#define LUA_NUMBER_FMT LUA_INTEGER_FMT
#define lua_str2number(s,p) strtoimax((s),(p),10)
#undef lua_numbertointeger
#define lua_numbertointeger(n,p) (*(p) = (LUA_INTEGER)(n), 1)
/* setjmp.h */
#include <machine/types.h>
#define LUAI_THROW(L,c) longjmp(&((c)->b))
#define LUAI_TRY(L,c,a) if (setjmp(&((c)->b)) == 0) { a }
#define luai_jmpbuf label_t
@ -720,10 +780,9 @@
#define time(p) (time_uptime)
/* stdio.h */
#define luai_writestring(s,l) printf("%s", (s))
#define luai_writeline() printf("\n")
#define lua_writestring(s,l) printf("%s", (s))
#define lua_writeline() printf("\n")
#define BUFSIZ (1024)
#define sprintf(s,fmt,...) snprintf(s, sizeof(s), fmt, __VA_ARGS__)
/* string.h */
@ -731,7 +790,10 @@
/* stdlib.h */
#define abort() panic("Lua has aborted!")
#endif /* _KERNEL */
#endif /* __NetBSD__ */
#endif /* lconfig_h */
#endif /* _KERNEL */
#endif /* __NetBSD__ */
#endif

View File

@ -1,18 +1,21 @@
/* $NetBSD: lundump.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lundump.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lundump.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lundump.c,v 2.41 2014/11/02 19:19:04 roberto Exp
** load precompiled Lua chunks
** See Copyright Notice in lua.h
*/
#define lundump_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define lundump_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"

View File

@ -1,4 +1,4 @@
/* $NetBSD: lutf8lib.c,v 1.1.1.2 2015/02/02 02:01:09 lneto Exp $ */
/* $NetBSD: lutf8lib.c,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
** Id: lutf8lib.c,v 1.13 2014/11/02 19:19:04 roberto Exp
@ -12,9 +12,11 @@
#include "lprefix.h"
#ifndef _KERNEL
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#endif
#include "lua.h"

View File

@ -1,11 +1,16 @@
/* $NetBSD: lvm.c,v 1.3 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lvm.c,v 1.4 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lvm.c,v 1.3 2014/07/19 18:38:34 lneto Exp $
** Id: lvm.c,v 2.232 2014/12/27 20:30:38 roberto Exp
** Lua virtual machine
** See Copyright Notice in lua.h
*/
#define lvm_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <limits.h>
@ -14,9 +19,6 @@
#include <string.h>
#endif
#define lvm_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
@ -32,15 +34,20 @@
#include "lvm.h"
/*
** You can define LUA_FLOORN2I if you want to convert floats to integers
** by flooring them (instead of raising an error if they are not
** integral values)
*/
#if !defined(LUA_FLOORN2I)
#define LUA_FLOORN2I 0
#endif
/* limit for table tag-method chains (to avoid loops) */
#define MAXTAGLOOP 2000
/* maximum length of the conversion of a number to a string */
#define MAXNUMBER2STR 50
#ifndef _KERNEL
/*
** Similar to 'tonumber', but does not attempt to convert strings and
@ -62,52 +69,54 @@ static int tofloat (const TValue *obj, lua_Number *n) {
/*
** Try to convert a value to a float. Check 'isinteger' first, because
** in general the float case is already handled by the macro 'tonumber'.
** Try to convert a value to a float. The float case is already handled
** by the macro 'tonumber'.
*/
int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
TValue v;
again:
if (ttisinteger(obj)) {
*n = cast_num(ivalue(obj));
return 1;
}
#ifndef _KERNEL
else if (ttisfloat(obj)) {
*n = fltvalue(obj);
else if (cvt2num(obj) && /* string convertible to number? */
luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) {
*n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */
return 1;
}
#endif
else if (ttisstring(obj) && /* string convertible to number? */
luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) {
obj = &v;
goto again; /* convert result from 'luaO_str2num' to a float */
}
return 0; /* conversion failed */
else
return 0; /* conversion failed */
}
/*
** try to convert a value to an integer, rounding up if 'up' is true
** try to convert a value to an integer, rounding according to 'mode':
** mode == 0: accepts only integral values
** mode == 1: takes the floor of the number
** mode == 2: takes the ceil of the number
*/
static int tointeger_aux (const TValue *obj, lua_Integer *p, int up) {
static int tointeger_aux (const TValue *obj, lua_Integer *p, int mode) {
TValue v;
again:
#ifndef _KERNEL
if (ttisfloat(obj)) {
lua_Number n = fltvalue(obj);
n = (up ? -l_floor(-n) : l_floor(n));
return lua_numtointeger(n, p);
lua_Number f = l_floor(n);
if (n != f) { /* not an integral value? */
if (mode == 0) return 0; /* fails if mode demands integral value */
else if (mode > 1) /* needs ceil? */
f += 1; /* convert floor to ceil (remember: n != f) */
}
return lua_numbertointeger(f, p);
}
else if (ttisinteger(obj)) {
#else
UNUSED(up);
#else /* _KERNEL */
if (ttisinteger(obj)) {
UNUSED(mode);
#endif
*p = ivalue(obj);
return 1;
}
else if (ttisstring(obj) &&
else if (cvt2num(obj) &&
luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) {
obj = &v;
goto again; /* convert result from 'luaO_str2num' to an integer */
@ -117,43 +126,14 @@ static int tointeger_aux (const TValue *obj, lua_Integer *p, int up) {
/*
** try to convert a non-integer value to an integer, rounding down
** try to convert a value to an integer
*/
int luaV_tointeger_ (const TValue *obj, lua_Integer *p) {
return tointeger_aux(obj, p, 0);
return tointeger_aux(obj, p, LUA_FLOORN2I);
}
/*
** Convert a number object to a string
*/
int luaV_tostring (lua_State *L, StkId obj) {
if (!ttisnumber(obj))
return 0;
else {
char buff[MAXNUMBER2STR];
size_t len;
if (ttisinteger(obj))
len = lua_integer2str(buff, ivalue(obj));
else {
#ifndef _KERNEL
len = lua_number2str(buff, fltvalue(obj));
#if !defined(LUA_COMPAT_FLOATSTRING)
if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
buff[len++] = '.';
buff[len++] = '0'; /* adds '.0' to result */
}
#endif
#else
return 0;
#endif
}
setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
return 1;
}
}
/*
** Try to convert a 'for' limit to an integer, preserving the
** semantics of the loop.
@ -172,8 +152,7 @@ int luaV_tostring (lua_State *L, StkId obj) {
static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
int *stopnow) {
*stopnow = 0; /* usually, let loops run */
#ifndef _KERNEL
if (!tointeger_aux(obj, p, (step < 0))) { /* does not fit in integer? */
if (!tointeger_aux(obj, p, (step < 0 ? 2 : 1))) { /* not fit in integer? */
lua_Number n; /* try to convert to float */
if (!tonumber(obj, &n)) /* cannot convert to float? */
return 0; /* not a number */
@ -186,11 +165,9 @@ static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
if (step >= 0) *stopnow = 1;
}
}
#else
UNUSED(obj); UNUSED(p); UNUSED(step);
#endif
return 1;
}
#endif
/*
@ -201,7 +178,7 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
int loop; /* counter to avoid infinite loops */
for (loop = 0; loop < MAXTAGLOOP; loop++) {
const TValue *tm;
if (ttistable(t)) { /* `t' is a table? */
if (ttistable(t)) { /* 't' is a table? */
Table *h = hvalue(t);
const TValue *res = luaH_get(h, key); /* do a primitive get */
if (!ttisnil(res) || /* result is not nil? */
@ -231,7 +208,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
int loop; /* counter to avoid infinite loops */
for (loop = 0; loop < MAXTAGLOOP; loop++) {
const TValue *tm;
if (ttistable(t)) { /* `t' is a table? */
if (ttistable(t)) { /* 't' is a table? */
Table *h = hvalue(t);
TValue *oldval = cast(TValue *, luaH_get(h, key));
/* if previous value is not nil, there must be a previous entry
@ -260,7 +237,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
luaT_callTM(L, tm, t, key, val, 0);
return;
}
t = tm; /* else repeat assginment over 'tm' */
t = tm; /* else repeat assignment over 'tm' */
}
luaG_runerror(L, "settable chain too long; possible loop");
}
@ -275,20 +252,20 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
*/
static int l_strcmp (const TString *ls, const TString *rs) {
const char *l = getstr(ls);
size_t ll = ls->tsv.len;
size_t ll = ls->len;
const char *r = getstr(rs);
size_t lr = rs->tsv.len;
size_t lr = rs->len;
for (;;) { /* for each segment */
int temp = strcoll(l, r);
if (temp != 0) /* not equal? */
return temp; /* done */
else { /* strings are equal up to a '\0' */
size_t len = strlen(l); /* index of first `\0' in both strings */
size_t len = strlen(l); /* index of first '\0' in both strings */
if (len == lr) /* 'rs' is finished? */
return (len == ll) ? 0 : 1; /* check 'ls' */
else if (len == ll) /* 'ls' is finished? */
return -1; /* 'ls' is smaller than 'rs' ('rs' is not finished) */
/* both strings longer than `len'; go on comparing after the '\0' */
/* both strings longer than 'len'; go on comparing after the '\0' */
len++;
l += len; ll -= len; r += len; lr -= len;
}
@ -311,7 +288,7 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
return luai_numlt(nl, nr);
#endif
else if (ttisstring(l) && ttisstring(r)) /* both are strings? */
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0) /* no metamethod? */
luaG_ordererror(L, l, r); /* error */
return res;
@ -333,10 +310,10 @@ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
return luai_numle(nl, nr);
#endif
else if (ttisstring(l) && ttisstring(r)) /* both are strings? */
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */
return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0) /* first try 'le' */
return res;
else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */
else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0) /* else try 'lt' */
luaG_ordererror(L, l, r);
return !res;
}
@ -358,8 +335,8 @@ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
cast_void(tofloat(t1, &n1)); cast_void(tofloat(t2, &n2));
return luai_numeq(n1, n2);
}
#else
return 0;
#else /* _KERNEL */
return 0; /* numbers have only the integer variant */
#endif
}
/* values have same type and same variant */
@ -372,8 +349,8 @@ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
case LUA_TLCF: return fvalue(t1) == fvalue(t2);
case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2));
case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2));
case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
case LUA_TUSERDATA: {
if (uvalue(t1) == uvalue(t2)) return 1;
else if (L == NULL) return 0;
@ -401,7 +378,8 @@ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o)))
#define tostring(L,o) \
(ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
/*
** Main operation for concatenation: concat 'total' values in the stack,
@ -412,7 +390,7 @@ void luaV_concat (lua_State *L, int total) {
do {
StkId top = L->top;
int n = 2; /* number of elements handled in this pass (at least 2) */
if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1))
if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1))
luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);
else if (tsvalue(top-1)->len == 0) /* second operand is empty? */
cast_void(tostring(L, top - 2)); /* result is first operand */
@ -476,8 +454,10 @@ void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
/*
** Integer division; return 'm // n'. (Assume that C division with
** negative operands follows C99 behavior.)
** Integer division; return 'm // n', that is, floor(m/n).
** C division truncates its result (rounds towards zero).
** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
** otherwise 'floor(q) == trunc(q) - 1'.
*/
lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) {
if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */
@ -486,18 +466,18 @@ lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) {
return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */
}
else {
lua_Integer d = m / n; /* perform division */
if ((m ^ n) >= 0 || m % n == 0) /* same signal or no rest? */
return d;
else
return d - 1; /* correct 'div' for negative case */
lua_Integer q = m / n; /* perform C division */
if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */
q -= 1; /* correct result for different rounding */
return q;
}
}
/*
** Integer modulus; return 'm % n'. (Assume that C '%' with
** negative operands follows C99 behavior.)
** negative operands follows C99 behavior. See previous comment
** about luaV_div.)
*/
lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */
@ -507,10 +487,9 @@ lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
}
else {
lua_Integer r = m % n;
if (r == 0 || (m ^ n) >= 0) /* no rest or same signal? */
return r;
else
return r + n; /* correct 'mod' for negative case */
if (r != 0 && (m ^ n) < 0) /* 'm/n' would be non-integer negative? */
r += n; /* correct result for different rounding */
return r;
}
}
@ -576,7 +555,7 @@ static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
ncl->upvals[i]->refcount++;
/* new closure is white, so we do not need a barrier here */
}
if (!isblack(obj2gco(p))) /* cache will not break GC invariant? */
if (!isblack(p)) /* cache will not break GC invariant? */
p->cache = ncl; /* save it on cache for reuse */
}
@ -660,7 +639,7 @@ void luaV_finishOp (lua_State *L) {
/*
** some macros for common tasks in `luaV_execute'
** some macros for common tasks in 'luaV_execute'
*/
#if !defined luai_runtimecheck
@ -700,8 +679,8 @@ void luaV_finishOp (lua_State *L) {
#define vmdispatch(o) switch(o)
#define vmcase(l,b) case l: {b} break;
#define vmcasenb(l,b) case l: {b} /* nb = no break */
#define vmcase(l) case l:
#define vmbreak break
void luaV_execute (lua_State *L) {
CallInfo *ci = L->ci;
@ -721,58 +700,69 @@ void luaV_execute (lua_State *L) {
(--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
Protect(luaG_traceexec(L));
}
/* WARNING: several calls may realloc the stack and invalidate `ra' */
/* WARNING: several calls may realloc the stack and invalidate 'ra' */
ra = RA(i);
lua_assert(base == ci->u.l.base);
lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
vmdispatch (GET_OPCODE(i)) {
vmcase(OP_MOVE,
vmcase(OP_MOVE) {
setobjs2s(L, ra, RB(i));
)
vmcase(OP_LOADK,
vmbreak;
}
vmcase(OP_LOADK) {
TValue *rb = k + GETARG_Bx(i);
setobj2s(L, ra, rb);
)
vmcase(OP_LOADKX,
vmbreak;
}
vmcase(OP_LOADKX) {
TValue *rb;
lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
rb = k + GETARG_Ax(*ci->u.l.savedpc++);
setobj2s(L, ra, rb);
)
vmcase(OP_LOADBOOL,
vmbreak;
}
vmcase(OP_LOADBOOL) {
setbvalue(ra, GETARG_B(i));
if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */
)
vmcase(OP_LOADNIL,
vmbreak;
}
vmcase(OP_LOADNIL) {
int b = GETARG_B(i);
do {
setnilvalue(ra++);
} while (b--);
)
vmcase(OP_GETUPVAL,
vmbreak;
}
vmcase(OP_GETUPVAL) {
int b = GETARG_B(i);
setobj2s(L, ra, cl->upvals[b]->v);
)
vmcase(OP_GETTABUP,
vmbreak;
}
vmcase(OP_GETTABUP) {
int b = GETARG_B(i);
Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
)
vmcase(OP_GETTABLE,
vmbreak;
}
vmcase(OP_GETTABLE) {
Protect(luaV_gettable(L, RB(i), RKC(i), ra));
)
vmcase(OP_SETTABUP,
vmbreak;
}
vmcase(OP_SETTABUP) {
int a = GETARG_A(i);
Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));
)
vmcase(OP_SETUPVAL,
vmbreak;
}
vmcase(OP_SETUPVAL) {
UpVal *uv = cl->upvals[GETARG_B(i)];
setobj(L, uv->v, ra);
luaC_upvalbarrier(L, uv);
)
vmcase(OP_SETTABLE,
vmbreak;
}
vmcase(OP_SETTABLE) {
Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
)
vmcase(OP_NEWTABLE,
vmbreak;
}
vmcase(OP_NEWTABLE) {
int b = GETARG_B(i);
int c = GETARG_C(i);
Table *t = luaH_new(L);
@ -780,65 +770,79 @@ void luaV_execute (lua_State *L) {
if (b != 0 || c != 0)
luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
checkGC(L, ra + 1);
)
vmcase(OP_SELF,
vmbreak;
}
vmcase(OP_SELF) {
StkId rb = RB(i);
setobjs2s(L, ra+1, rb);
Protect(luaV_gettable(L, rb, RKC(i), ra));
)
vmcase(OP_ADD,
vmbreak;
}
vmcase(OP_ADD) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
#ifndef _KERNEL
lua_Number nb; lua_Number nc;
#endif
if (ttisinteger(rb) && ttisinteger(rc)) {
lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
setivalue(ra, intop(+, ib, ic));
}
#ifndef _KERNEL
else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
setfltvalue(ra, luai_numadd(L, nb, nc));
}
#else /* _KERNEL */
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, intop(+, ib, ic));
}
#endif
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_ADD)); }
)
vmcase(OP_SUB,
vmbreak;
}
vmcase(OP_SUB) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
#ifndef _KERNEL
lua_Number nb; lua_Number nc;
#endif
if (ttisinteger(rb) && ttisinteger(rc)) {
lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
setivalue(ra, intop(-, ib, ic));
}
#ifndef _KERNEL
else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
setfltvalue(ra, luai_numsub(L, nb, nc));
}
#else /* _KERNEL */
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, intop(-, ib, ic));
}
#endif
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SUB)); }
)
vmcase(OP_MUL,
vmbreak;
}
vmcase(OP_MUL) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
#ifndef _KERNEL
lua_Number nb; lua_Number nc;
#endif
if (ttisinteger(rb) && ttisinteger(rc)) {
lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
setivalue(ra, intop(*, ib, ic));
}
#ifndef _KERNEL
else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
setfltvalue(ra, luai_nummul(L, nb, nc));
}
#else /* _KERNEL */
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, intop(*, ib, ic));
}
#endif
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MUL)); }
)
vmbreak;
}
#ifndef _KERNEL
vmcase(OP_DIV, /* float division (always with floats) */
vmcase(OP_DIV) { /* float division (always with floats) */
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Number nb; lua_Number nc;
@ -846,18 +850,10 @@ void luaV_execute (lua_State *L) {
setfltvalue(ra, luai_numdiv(L, nb, nc));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); }
)
vmbreak;
}
#endif
vmcase(OP_IDIV, /* integer division */
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, luaV_div(L, ib, ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }
)
vmcase(OP_BAND,
vmcase(OP_BAND) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
@ -865,8 +861,9 @@ void luaV_execute (lua_State *L) {
setivalue(ra, intop(&, ib, ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); }
)
vmcase(OP_BOR,
vmbreak;
}
vmcase(OP_BOR) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
@ -874,8 +871,9 @@ void luaV_execute (lua_State *L) {
setivalue(ra, intop(|, ib, ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); }
)
vmcase(OP_BXOR,
vmbreak;
}
vmcase(OP_BXOR) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
@ -883,8 +881,9 @@ void luaV_execute (lua_State *L) {
setivalue(ra, intop(^, ib, ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); }
)
vmcase(OP_SHL,
vmbreak;
}
vmcase(OP_SHL) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
@ -892,8 +891,9 @@ void luaV_execute (lua_State *L) {
setivalue(ra, luaV_shiftl(ib, ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); }
)
vmcase(OP_SHR,
vmbreak;
}
vmcase(OP_SHR) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Integer ib; lua_Integer ic;
@ -901,28 +901,54 @@ void luaV_execute (lua_State *L) {
setivalue(ra, luaV_shiftl(ib, -ic));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); }
)
vmcase(OP_MOD,
vmbreak;
}
vmcase(OP_MOD) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
#ifndef _KERNEL
lua_Number nb; lua_Number nc;
#endif
if (ttisinteger(rb) && ttisinteger(rc)) {
lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
setivalue(ra, luaV_mod(L, ib, ic));
}
#ifndef _KERNEL
else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
lua_Number m;
luai_nummod(L, nb, nc, m);
setfltvalue(ra, m);
}
#else /* _KERNEL */
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, luaV_mod(L, ib, ic));
}
#endif
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); }
)
vmbreak;
}
vmcase(OP_IDIV) { /* floor division */
TValue *rb = RKB(i);
TValue *rc = RKC(i);
#ifndef _KERNEL
vmcase(OP_POW,
lua_Number nb; lua_Number nc;
if (ttisinteger(rb) && ttisinteger(rc)) {
lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
setivalue(ra, luaV_div(L, ib, ic));
}
else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
setfltvalue(ra, luai_numidiv(L, nb, nc));
}
#else /* _KERNEL */
lua_Integer ib; lua_Integer ic;
if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
setivalue(ra, luaV_div(L, ib, ic));
}
#endif
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }
vmbreak;
}
#ifndef _KERNEL
vmcase(OP_POW) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
lua_Number nb; lua_Number nc;
@ -930,27 +956,32 @@ void luaV_execute (lua_State *L) {
setfltvalue(ra, luai_numpow(L, nb, nc));
}
else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_POW)); }
)
vmbreak;
}
#endif
vmcase(OP_UNM,
vmcase(OP_UNM) {
TValue *rb = RB(i);
#ifndef _KERNEL
lua_Number nb;
#endif
if (ttisinteger(rb)) {
lua_Integer ib = ivalue(rb);
setivalue(ra, intop(-, 0, ib));
}
#ifndef _KERNEL
else if (tonumber(rb, &nb)) {
setfltvalue(ra, luai_numunm(L, nb));
}
#else /* _KERNEL */
lua_Integer ib;
if (tointeger(rb, &ib)) {
setivalue(ra, intop(-, 0, ib));
}
#endif
else {
Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
}
)
vmcase(OP_BNOT,
vmbreak;
}
vmcase(OP_BNOT) {
TValue *rb = RB(i);
lua_Integer ib;
if (tointeger(rb, &ib)) {
@ -959,16 +990,19 @@ void luaV_execute (lua_State *L) {
else {
Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
}
)
vmcase(OP_NOT,
vmbreak;
}
vmcase(OP_NOT) {
TValue *rb = RB(i);
int res = l_isfalse(rb); /* next assignment may change this value */
setbvalue(ra, res);
)
vmcase(OP_LEN,
vmbreak;
}
vmcase(OP_LEN) {
Protect(luaV_objlen(L, ra, RB(i)));
)
vmcase(OP_CONCAT,
vmbreak;
}
vmcase(OP_CONCAT) {
int b = GETARG_B(i);
int c = GETARG_C(i);
StkId rb;
@ -979,11 +1013,13 @@ void luaV_execute (lua_State *L) {
setobjs2s(L, ra, rb);
checkGC(L, (ra >= rb ? ra + 1 : rb));
L->top = ci->top; /* restore top */
)
vmcase(OP_JMP,
vmbreak;
}
vmcase(OP_JMP) {
dojump(ci, i, 0);
)
vmcase(OP_EQ,
vmbreak;
}
vmcase(OP_EQ) {
TValue *rb = RKB(i);
TValue *rc = RKC(i);
Protect(
@ -992,30 +1028,34 @@ void luaV_execute (lua_State *L) {
else
donextjump(ci);
)
)
vmcase(OP_LT,
vmbreak;
}
vmcase(OP_LT) {
Protect(
if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
ci->u.l.savedpc++;
else
donextjump(ci);
)
)
vmcase(OP_LE,
vmbreak;
}
vmcase(OP_LE) {
Protect(
if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
ci->u.l.savedpc++;
else
donextjump(ci);
)
)
vmcase(OP_TEST,
vmbreak;
}
vmcase(OP_TEST) {
if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
ci->u.l.savedpc++;
else
donextjump(ci);
)
vmcase(OP_TESTSET,
vmbreak;
}
vmcase(OP_TESTSET) {
TValue *rb = RB(i);
if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
ci->u.l.savedpc++;
@ -1023,8 +1063,9 @@ void luaV_execute (lua_State *L) {
setobjs2s(L, ra, rb);
donextjump(ci);
}
)
vmcase(OP_CALL,
vmbreak;
}
vmcase(OP_CALL) {
int b = GETARG_B(i);
int nresults = GETARG_C(i) - 1;
if (b != 0) L->top = ra+b; /* else previous instruction set top */
@ -1037,8 +1078,9 @@ void luaV_execute (lua_State *L) {
ci->callstatus |= CIST_REENTRY;
goto newframe; /* restart luaV_execute over new Lua function */
}
)
vmcase(OP_TAILCALL,
vmbreak;
}
vmcase(OP_TAILCALL) {
int b = GETARG_B(i);
if (b != 0) L->top = ra+b; /* else previous instruction set top */
lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
@ -1066,8 +1108,9 @@ void luaV_execute (lua_State *L) {
lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
goto newframe; /* restart luaV_execute over new Lua function */
}
)
vmcasenb(OP_RETURN,
vmbreak;
}
vmcase(OP_RETURN) {
int b = GETARG_B(i);
if (b != 0) L->top = ra+b-1;
if (cl->p->sizep > 0) luaF_close(L, base);
@ -1081,9 +1124,11 @@ void luaV_execute (lua_State *L) {
lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
goto newframe; /* restart luaV_execute over new Lua function */
}
)
vmcase(OP_FORLOOP,
}
vmcase(OP_FORLOOP) {
#ifndef _KERNEL
if (ttisinteger(ra)) { /* integer loop? */
#endif
lua_Integer step = ivalue(ra + 2);
lua_Integer idx = ivalue(ra) + step; /* increment index */
lua_Integer limit = ivalue(ra + 1);
@ -1092,8 +1137,8 @@ void luaV_execute (lua_State *L) {
setivalue(ra, idx); /* update internal index... */
setivalue(ra + 3, idx); /* ...and external index */
}
}
#ifndef _KERNEL
}
else { /* floating loop */
lua_Number step = fltvalue(ra + 2);
lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */
@ -1106,12 +1151,14 @@ void luaV_execute (lua_State *L) {
}
}
#endif
)
vmcase(OP_FORPREP,
vmbreak;
}
vmcase(OP_FORPREP) {
TValue *init = ra;
TValue *plimit = ra + 1;
TValue *pstep = ra + 2;
lua_Integer ilimit;
#ifndef _KERNEL
int stopnow;
if (ttisinteger(init) && ttisinteger(pstep) &&
forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) {
@ -1120,23 +1167,34 @@ void luaV_execute (lua_State *L) {
setivalue(plimit, ilimit);
setivalue(init, initv - ivalue(pstep));
}
#ifndef _KERNEL
else { /* try making all values floats */
lua_Number ninit; lua_Number nlimit; lua_Number nstep;
if (!tonumber(plimit, &nlimit))
luaG_runerror(L, LUA_QL("for") " limit must be a number");
luaG_runerror(L, "'for' limit must be a number");
setfltvalue(plimit, nlimit);
if (!tonumber(pstep, &nstep))
luaG_runerror(L, LUA_QL("for") " step must be a number");
luaG_runerror(L, "'for' step must be a number");
setfltvalue(pstep, nstep);
if (!tonumber(init, &ninit))
luaG_runerror(L, LUA_QL("for") " initial value must be a number");
luaG_runerror(L, "'for' initial value must be a number");
setfltvalue(init, luai_numsub(L, ninit, nstep));
}
#else /* _KERNEL */
lua_Integer initv; lua_Integer step;
if (!tointeger(plimit, &ilimit))
luaG_runerror(L, "'for' limit must be a number");
setivalue(plimit, ilimit);
if (!tointeger(pstep, &step))
luaG_runerror(L, "'for' step must be a number");
setivalue(pstep, step);
if (!tointeger(init, &initv))
luaG_runerror(L, "'for' initial value must be a number");
setivalue(init, initv - step);
#endif
ci->u.l.savedpc += GETARG_sBx(i);
)
vmcasenb(OP_TFORCALL,
vmbreak;
}
vmcase(OP_TFORCALL) {
StkId cb = ra + 3; /* call base */
setobjs2s(L, cb+2, ra+2);
setobjs2s(L, cb+1, ra+1);
@ -1148,18 +1206,19 @@ void luaV_execute (lua_State *L) {
ra = RA(i);
lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
goto l_tforloop;
)
vmcase(OP_TFORLOOP,
}
vmcase(OP_TFORLOOP) {
l_tforloop:
if (!ttisnil(ra + 1)) { /* continue loop? */
setobjs2s(L, ra, ra + 1); /* save control variable */
ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
}
)
vmcase(OP_SETLIST,
vmbreak;
}
vmcase(OP_SETLIST) {
int n = GETARG_B(i);
int c = GETARG_C(i);
int last;
unsigned int last;
Table *h;
if (n == 0) n = cast_int(L->top - ra) - 1;
if (c == 0) {
@ -1177,8 +1236,9 @@ void luaV_execute (lua_State *L) {
luaC_barrierback(L, h, val);
}
L->top = ci->top; /* correct top (in case of previous open call) */
)
vmcase(OP_CLOSURE,
vmbreak;
}
vmcase(OP_CLOSURE) {
Proto *p = cl->p->p[GETARG_Bx(i)];
LClosure *ncl = getcached(p, cl->upvals, base); /* cached closure */
if (ncl == NULL) /* no match? */
@ -1186,8 +1246,9 @@ void luaV_execute (lua_State *L) {
else
setclLvalue(L, ra, ncl); /* push cashed closure */
checkGC(L, ra + 1);
)
vmcase(OP_VARARG,
vmbreak;
}
vmcase(OP_VARARG) {
int b = GETARG_B(i) - 1;
int j;
int n = cast_int(base - ci->func) - cl->p->numparams - 1;
@ -1205,10 +1266,12 @@ void luaV_execute (lua_State *L) {
setnilvalue(ra + j);
}
}
)
vmcase(OP_EXTRAARG,
vmbreak;
}
vmcase(OP_EXTRAARG) {
lua_assert(0);
)
vmbreak;
}
}
}
}

View File

@ -1,7 +1,7 @@
/* $NetBSD: lvm.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lvm.h,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lvm.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lvm.h,v 2.34 2014/08/01 17:24:02 roberto Exp
** Lua virtual machine
** See Copyright Notice in lua.h
*/
@ -15,10 +15,24 @@
#include "ltm.h"
#if !defined(LUA_NOCVTN2S)
#define cvt2str(o) ttisnumber(o)
#else
#define cvt2str(o) 0 /* no conversion from numbers to strings */
#endif
#if !defined(LUA_NOCVTS2N)
#define cvt2num(o) ttisstring(o)
#else
#define cvt2num(o) 0 /* no conversion from strings to numbers */
#endif
#ifndef _KERNEL
#define tonumber(o,n) \
(ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
#else
#else /* _KERNEL */
#define tonumber tointeger
#endif
@ -35,7 +49,6 @@ LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
LUAI_FUNC int luaV_tointeger_ (const TValue *obj, lua_Integer *p);
LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
StkId val);
LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,

View File

@ -1,19 +1,21 @@
/* $NetBSD: lzio.c,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/* $NetBSD: lzio.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
/*
** $Id: lzio.c,v 1.2 2014/07/19 18:38:34 lneto Exp $
** Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp
** Buffered streams
** See Copyright Notice in lua.h
*/
#define lzio_c
#define LUA_CORE
#include "lprefix.h"
#ifndef _KERNEL
#include <string.h>
#endif
#define lzio_c
#define LUA_CORE
#include "lua.h"
#include "llimits.h"

View File

@ -1,7 +1,5 @@
/* $NetBSD: lzio.h,v 1.2 2014/07/19 18:38:34 lneto Exp $ */
/*
** $Id: lzio.h,v 1.2 2014/07/19 18:38:34 lneto Exp $
** $Id: lzio.h,v 1.3 2015/02/02 14:03:05 lneto Exp $
** Buffered streams
** See Copyright Notice in lua.h
*/
@ -39,7 +37,8 @@ typedef struct Mbuffer {
#define luaZ_resizebuffer(L, buff, size) \
(luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \
(buff)->buffsize, size), \
(buff)->buffsize = size)
#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)

View File

@ -1,4 +1,4 @@
/* $NetBSD: syslog.c,v 1.1 2013/11/12 14:32:03 mbalmer Exp $ */
/* $NetBSD: syslog.c,v 1.2 2015/02/02 14:03:05 lneto Exp $ */
/*
* Copyright (c) 2013 Marc Balmer <marc@msys.ch>
@ -55,7 +55,7 @@ syslog_openlog(lua_State *L)
static int
syslog_syslog(lua_State *L)
{
syslog(luaL_checkint(L, 1), "%s", luaL_checkstring(L, 2));
syslog((int) luaL_checkinteger(L, 1), "%s", luaL_checkstring(L, 2));
return 0;
}
@ -69,7 +69,7 @@ syslog_closelog(lua_State *L)
static int
syslog_setlogmask(lua_State *L)
{
lua_pushinteger(L, setlogmask(luaL_checkint(L, 1)));
lua_pushinteger(L, setlogmask((int) luaL_checkinteger(L, 1)));
return 1;
}

View File

@ -1,10 +1,11 @@
# $NetBSD: Makefile,v 1.3 2014/07/19 18:38:35 lneto Exp $
# $NetBSD: Makefile,v 1.4 2015/02/02 14:03:05 lneto Exp $
.include "../Makefile.inc"
KMOD= luapmf
SRCS= luapmf.c
CPPFLAGS+= -I${S}/../external/mit/lua/dist/src
CPPFLAGS+= -I${S}/../external/mit/lua/dist/src \
-I${S}/sys
.include <bsd.kmodule.mk>

View File

@ -1,10 +1,11 @@
# $NetBSD: Makefile,v 1.2 2014/07/19 18:38:35 lneto Exp $
# $NetBSD: Makefile,v 1.3 2015/02/02 14:03:05 lneto Exp $
.include "../Makefile.inc"
KMOD= luasystm
SRCS= luasystm.c
CPPFLAGS+= -I${S}/../external/mit/lua/dist/src
CPPFLAGS+= -I${S}/../external/mit/lua/dist/src \
-I${S}/sys
.include <bsd.kmodule.mk>