text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
/*
** $Id: lfunc.h $
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
#ifndef lfunc_h
#define lfunc_h
#include "lobject.h"
#define sizeCclosure(n) (cast_int(offsetof(CClosure, upvalue)) + \
cast_int(sizeof(TValue)) * (n))
#define sizeLclosure(n) (cast_int(offsetof(LClosure, upvals)) + \
cast_int(sizeof(TValue *)) * (n))
/* test whether thread is in 'twups' list */
#define isintwups(L) (L->twups != L)
/*
** maximum number of upvalues in a closure (both C and Lua). (Value
** must fit in a VM register.)
*/
#define MAXUPVAL 255
#define upisopen(up) ((up)->v != &(up)->u.value)
#define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v))
/*
** maximum number of misses before giving up the cache of closures
** in prototypes
*/
#define MAXMISS 10
/*
** Special "status" for 'luaF_close'
*/
/* close upvalues without running their closing methods */
#define NOCLOSINGMETH (-1)
/* close upvalues running all closing methods in protected mode */
#define CLOSEPROTECT (-2)
LUAI_FUNC Proto *luaF_newproto (lua_State *L);
LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals);
LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals);
LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level);
LUAI_FUNC int luaF_close (lua_State *L, StkId level, int status);
LUAI_FUNC void luaF_unlinkupval (UpVal *uv);
LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
int pc);
#endif
| xLua/build/lua-5.4.1/src/lfunc.h/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lfunc.h",
"repo_id": "xLua",
"token_count": 732
} | 2,100 |
/*
** $Id: lopcodes.h $
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
#ifndef lopcodes_h
#define lopcodes_h
#include "llimits.h"
/*===========================================================================
We assume that instructions are unsigned 32-bit integers.
All instructions have an opcode in the first 7 bits.
Instructions can have the following formats:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
iABC C(8) | B(8) |k| A(8) | Op(7) |
iABx Bx(17) | A(8) | Op(7) |
iAsBx sBx (signed)(17) | A(8) | Op(7) |
iAx Ax(25) | Op(7) |
isJ sJ(25) | Op(7) |
A signed argument is represented in excess K: the represented value is
the written unsigned value minus K, where K is half the maximum for the
corresponding unsigned argument.
===========================================================================*/
enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */
/*
** size and position of opcode arguments.
*/
#define SIZE_C 8
#define SIZE_B 8
#define SIZE_Bx (SIZE_C + SIZE_B + 1)
#define SIZE_A 8
#define SIZE_Ax (SIZE_Bx + SIZE_A)
#define SIZE_sJ (SIZE_Bx + SIZE_A)
#define SIZE_OP 7
#define POS_OP 0
#define POS_A (POS_OP + SIZE_OP)
#define POS_k (POS_A + SIZE_A)
#define POS_B (POS_k + 1)
#define POS_C (POS_B + SIZE_B)
#define POS_Bx POS_k
#define POS_Ax POS_A
#define POS_sJ POS_A
/*
** limits for opcode arguments.
** we use (signed) 'int' to manipulate most arguments,
** so they must fit in ints.
*/
/* Check whether type 'int' has at least 'b' bits ('b' < 32) */
#define L_INTHASBITS(b) ((UINT_MAX >> ((b) - 1)) >= 1)
#if L_INTHASBITS(SIZE_Bx)
#define MAXARG_Bx ((1<<SIZE_Bx)-1)
#else
#define MAXARG_Bx MAX_INT
#endif
#define OFFSET_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */
#if L_INTHASBITS(SIZE_Ax)
#define MAXARG_Ax ((1<<SIZE_Ax)-1)
#else
#define MAXARG_Ax MAX_INT
#endif
#if L_INTHASBITS(SIZE_sJ)
#define MAXARG_sJ ((1 << SIZE_sJ) - 1)
#else
#define MAXARG_sJ MAX_INT
#endif
#define OFFSET_sJ (MAXARG_sJ >> 1)
#define MAXARG_A ((1<<SIZE_A)-1)
#define MAXARG_B ((1<<SIZE_B)-1)
#define MAXARG_C ((1<<SIZE_C)-1)
#define OFFSET_sC (MAXARG_C >> 1)
#define int2sC(i) ((i) + OFFSET_sC)
#define sC2int(i) ((i) - OFFSET_sC)
/* 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' */
#define MASK0(n,p) (~MASK1(n,p))
/*
** the following macros help to manipulate instructions
*/
#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
#define checkopm(i,m) (getOpMode(GET_OPCODE(i)) == m)
#define getarg(i,pos,size) (cast_int(((i)>>(pos)) & MASK1(size,0)))
#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \
((cast(Instruction, v)<<pos)&MASK1(size,pos))))
#define GETARG_A(i) getarg(i, POS_A, SIZE_A)
#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)
#define GETARG_B(i) check_exp(checkopm(i, iABC), getarg(i, POS_B, SIZE_B))
#define GETARG_sB(i) sC2int(GETARG_B(i))
#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)
#define GETARG_C(i) check_exp(checkopm(i, iABC), getarg(i, POS_C, SIZE_C))
#define GETARG_sC(i) sC2int(GETARG_C(i))
#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)
#define TESTARG_k(i) check_exp(checkopm(i, iABC), (cast_int(((i) & (1u << POS_k)))))
#define GETARG_k(i) check_exp(checkopm(i, iABC), getarg(i, POS_k, 1))
#define SETARG_k(i,v) setarg(i, v, POS_k, 1)
#define GETARG_Bx(i) check_exp(checkopm(i, iABx), getarg(i, POS_Bx, SIZE_Bx))
#define SETARG_Bx(i,v) setarg(i, v, POS_Bx, SIZE_Bx)
#define GETARG_Ax(i) check_exp(checkopm(i, iAx), getarg(i, POS_Ax, SIZE_Ax))
#define SETARG_Ax(i,v) setarg(i, v, POS_Ax, SIZE_Ax)
#define GETARG_sBx(i) \
check_exp(checkopm(i, iAsBx), getarg(i, POS_Bx, SIZE_Bx) - OFFSET_sBx)
#define SETARG_sBx(i,b) SETARG_Bx((i),cast_uint((b)+OFFSET_sBx))
#define GETARG_sJ(i) \
check_exp(checkopm(i, isJ), getarg(i, POS_sJ, SIZE_sJ) - OFFSET_sJ)
#define SETARG_sJ(i,j) \
setarg(i, cast_uint((j)+OFFSET_sJ), POS_sJ, SIZE_sJ)
#define CREATE_ABCk(o,a,b,c,k) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, b)<<POS_B) \
| (cast(Instruction, c)<<POS_C) \
| (cast(Instruction, k)<<POS_k))
#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, bc)<<POS_Bx))
#define CREATE_Ax(o,a) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_Ax))
#define CREATE_sJ(o,j,k) ((cast(Instruction, o) << POS_OP) \
| (cast(Instruction, j) << POS_sJ) \
| (cast(Instruction, k) << POS_k))
#if !defined(MAXINDEXRK) /* (for debugging only) */
#define MAXINDEXRK MAXARG_B
#endif
/*
** invalid register that fits in 8 bits
*/
#define NO_REG MAXARG_A
/*
** R[x] - register
** K[x] - constant (in constant table)
** RK(x) == if k(i) then K[x] else R[x]
*/
/*
** grep "ORDER OP" if you change these enums
*/
typedef enum {
/*----------------------------------------------------------------------
name args description
------------------------------------------------------------------------*/
OP_MOVE,/* A B R[A] := R[B] */
OP_LOADI,/* A sBx R[A] := sBx */
OP_LOADF,/* A sBx R[A] := (lua_Number)sBx */
OP_LOADK,/* A Bx R[A] := K[Bx] */
OP_LOADKX,/* A R[A] := K[extra arg] */
OP_LOADFALSE,/* A R[A] := false */
OP_LFALSESKIP,/*A R[A] := false; pc++ */
OP_LOADTRUE,/* A R[A] := true */
OP_LOADNIL,/* A B R[A], R[A+1], ..., R[A+B] := nil */
OP_GETUPVAL,/* A B R[A] := UpValue[B] */
OP_SETUPVAL,/* A B UpValue[B] := R[A] */
OP_GETTABUP,/* A B C R[A] := UpValue[B][K[C]:string] */
OP_GETTABLE,/* A B C R[A] := R[B][R[C]] */
OP_GETI,/* A B C R[A] := R[B][C] */
OP_GETFIELD,/* A B C R[A] := R[B][K[C]:string] */
OP_SETTABUP,/* A B C UpValue[A][K[B]:string] := RK(C) */
OP_SETTABLE,/* A B C R[A][R[B]] := RK(C) */
OP_SETI,/* A B C R[A][B] := RK(C) */
OP_SETFIELD,/* A B C R[A][K[B]:string] := RK(C) */
OP_NEWTABLE,/* A B C k R[A] := {} */
OP_SELF,/* A B C R[A+1] := R[B]; R[A] := R[B][RK(C):string] */
OP_ADDI,/* A B sC R[A] := R[B] + sC */
OP_ADDK,/* A B C R[A] := R[B] + K[C] */
OP_SUBK,/* A B C R[A] := R[B] - K[C] */
OP_MULK,/* A B C R[A] := R[B] * K[C] */
OP_MODK,/* A B C R[A] := R[B] % K[C] */
OP_POWK,/* A B C R[A] := R[B] ^ K[C] */
OP_DIVK,/* A B C R[A] := R[B] / K[C] */
OP_IDIVK,/* A B C R[A] := R[B] // K[C] */
OP_BANDK,/* A B C R[A] := R[B] & K[C]:integer */
OP_BORK,/* A B C R[A] := R[B] | K[C]:integer */
OP_BXORK,/* A B C R[A] := R[B] ~ K[C]:integer */
OP_SHRI,/* A B sC R[A] := R[B] >> sC */
OP_SHLI,/* A B sC R[A] := sC << R[B] */
OP_ADD,/* A B C R[A] := R[B] + R[C] */
OP_SUB,/* A B C R[A] := R[B] - R[C] */
OP_MUL,/* A B C R[A] := R[B] * R[C] */
OP_MOD,/* A B C R[A] := R[B] % R[C] */
OP_POW,/* A B C R[A] := R[B] ^ R[C] */
OP_DIV,/* A B C R[A] := R[B] / R[C] */
OP_IDIV,/* A B C R[A] := R[B] // R[C] */
OP_BAND,/* A B C R[A] := R[B] & R[C] */
OP_BOR,/* A B C R[A] := R[B] | R[C] */
OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */
OP_SHL,/* A B C R[A] := R[B] << R[C] */
OP_SHR,/* A B C R[A] := R[B] >> R[C] */
OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] */
OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */
OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */
OP_UNM,/* A B R[A] := -R[B] */
OP_BNOT,/* A B R[A] := ~R[B] */
OP_NOT,/* A B R[A] := not R[B] */
OP_LEN,/* A B R[A] := length of R[B] */
OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */
OP_CLOSE,/* A close all upvalues >= R[A] */
OP_TBC,/* A mark variable A "to be closed" */
OP_JMP,/* sJ pc += sJ */
OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */
OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */
OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */
OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */
OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */
OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */
OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */
OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */
OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */
OP_TEST,/* A k if (not R[A] == k) then pc++ */
OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] */
OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */
OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */
OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] (see note) */
OP_RETURN0,/* return */
OP_RETURN1,/* A return R[A] */
OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */
OP_FORPREP,/* A Bx <check values and prepare counters>;
if not to run then pc+=Bx+1; */
OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */
OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */
OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */
OP_SETLIST,/* A B C k R[A][(C-1)*FPF+i] := R[A+i], 1 <= i <= B */
OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */
OP_VARARG,/* A C R[A], R[A+1], ..., R[A+C-2] = vararg */
OP_VARARGPREP,/*A (adjust vararg parameters) */
OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
} OpCode;
#define NUM_OPCODES ((int)(OP_EXTRAARG) + 1)
/*===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then
'top' is set to last_result+1, so next open instruction (OP_CALL,
OP_RETURN*, OP_SETLIST) may use 'top'.
(*) In OP_VARARG, if (C == 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_LOADKX and OP_NEWTABLE, the next instruction is always
OP_EXTRAARG.
(*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then
real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the
bits of C).
(*) In OP_NEWTABLE, B is log2 of the hash size (which is always a
power of 2) plus 1, or zero for size zero. If not k, the array size
is C. Otherwise, the array size is EXTRAARG _ C.
(*) For comparisons, k specifies what condition the test should accept
(true or false).
(*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped
(the constant is the first operand).
(*) All 'skips' (pc++) assume that next instruction is a jump.
(*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the
function builds upvalues, which may need to be closed. C > 0 means
the function is vararg, so that its 'func' must be corrected before
returning; in this case, (C - 1) is its number of fixed parameters.
(*) In comparisons with an immediate operand, C signals whether the
original operand was a float. (It must be corrected in case of
metamethods.)
===========================================================================*/
/*
** masks for instruction properties. The format is:
** bits 0-2: op mode
** bit 3: instruction set register A
** bit 4: operator is a test (next instruction must be a jump)
** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0)
** bit 6: instruction sets 'L->top' for next instruction (when C == 0)
** bit 7: instruction is an MM instruction (call a metamethod)
*/
LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7))
#define testAMode(m) (luaP_opmodes[m] & (1 << 3))
#define testTMode(m) (luaP_opmodes[m] & (1 << 4))
#define testITMode(m) (luaP_opmodes[m] & (1 << 5))
#define testOTMode(m) (luaP_opmodes[m] & (1 << 6))
#define testMMMode(m) (luaP_opmodes[m] & (1 << 7))
/* "out top" (set top for next instruction) */
#define isOT(i) \
((testOTMode(GET_OPCODE(i)) && GETARG_C(i) == 0) || \
GET_OPCODE(i) == OP_TAILCALL)
/* "in top" (uses top from previous instruction) */
#define isIT(i) (testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0)
#define opmode(mm,ot,it,t,a,m) \
(((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m))
/* number of list items to accumulate before a SETLIST instruction */
#define LFIELDS_PER_FLUSH 50
#endif
| xLua/build/lua-5.4.1/src/lopcodes.h/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lopcodes.h",
"repo_id": "xLua",
"token_count": 6410
} | 2,101 |
/*
** $Id: lua.c $
** Lua stand-alone interpreter
** See Copyright Notice in lua.h
*/
#define lua_c
#include "lprefix.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#if !defined(LUA_PROGNAME)
#define LUA_PROGNAME "lua"
#endif
#if !defined(LUA_INIT_VAR)
#define LUA_INIT_VAR "LUA_INIT"
#endif
#define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX
static lua_State *globalL = NULL;
static const char *progname = LUA_PROGNAME;
/*
** Hook set by signal function to stop the interpreter.
*/
static void lstop (lua_State *L, lua_Debug *ar) {
(void)ar; /* unused arg. */
lua_sethook(L, NULL, 0, 0); /* reset hook */
luaL_error(L, "interrupted!");
}
/*
** Function to be called at a C signal. Because a C signal cannot
** just change a Lua state (as there is no proper synchronization),
** this function only sets a hook that, when called, will stop the
** interpreter.
*/
static void laction (int i) {
int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;
signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
lua_sethook(globalL, lstop, flag, 1);
}
static void print_usage (const char *badoption) {
lua_writestringerror("%s: ", progname);
if (badoption[1] == 'e' || badoption[1] == 'l')
lua_writestringerror("'%s' needs argument\n", badoption);
else
lua_writestringerror("unrecognized option '%s'\n", badoption);
lua_writestringerror(
"usage: %s [options] [script [args]]\n"
"Available options are:\n"
" -e stat execute string 'stat'\n"
" -i enter interactive mode after executing 'script'\n"
" -l name require library 'name' into global 'name'\n"
" -v show version information\n"
" -E ignore environment variables\n"
" -W turn warnings on\n"
" -- stop handling options\n"
" - stop handling options and execute stdin\n"
,
progname);
}
/*
** Prints an error message, adding the program name in front of it
** (if present)
*/
static void l_message (const char *pname, const char *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. 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_tostring(L, -1);
l_message(progname, msg);
lua_pop(L, 1); /* remove message */
}
return status;
}
/*
** Message handler used to run all chunks
*/
static int msghandler (lua_State *L) {
const char *msg = lua_tostring(L, 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 */
}
/*
** Interface to 'lua_pcall', which sets appropriate message function
** and C-signal handler. Used to run all chunks.
*/
static int docall (lua_State *L, int narg, int nres) {
int status;
int base = lua_gettop(L) - narg; /* function index */
lua_pushcfunction(L, msghandler); /* push message handler */
lua_insert(L, base); /* put it under function and args */
globalL = L; /* to be available to 'laction' */
signal(SIGINT, laction); /* set C-signal handler */
status = lua_pcall(L, narg, nres, base);
signal(SIGINT, SIG_DFL); /* reset C-signal handler */
lua_remove(L, base); /* remove message handler from the stack */
return status;
}
static void print_version (void) {
lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
lua_writeline();
}
/*
** Create the 'arg' table, which stores all arguments from the
** command line ('argv'). It should be aligned so that, at index 0,
** it has 'argv[script]', which is the script name. The arguments
** to the script (everything after 'script') go to positive indices;
** other arguments (before the script name) go to negative indices.
** If there is no script name, assume interpreter's name as base.
*/
static void createargtable (lua_State *L, char **argv, int argc, int script) {
int i, narg;
if (script == argc) script = 0; /* no script name? */
narg = argc - (script + 1); /* number of positive indices */
lua_createtable(L, narg, script + 1);
for (i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i - script);
}
lua_setglobal(L, "arg");
}
static int dochunk (lua_State *L, int status) {
if (status == LUA_OK) status = docall(L, 0, 0);
return report(L, status);
}
static int dofile (lua_State *L, const char *name) {
return dochunk(L, luaL_loadfile(L, name));
}
static int dostring (lua_State *L, const char *s, const char *name) {
return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
}
/*
** Calls 'require(name)' and stores the result in a global variable
** with the given name.
*/
static int dolibrary (lua_State *L, const char *name) {
int status;
lua_getglobal(L, "require");
lua_pushstring(L, name);
status = docall(L, 1, 1); /* call 'require(name)' */
if (status == LUA_OK)
lua_setglobal(L, name); /* global[name] = require return */
return report(L, status);
}
/*
** Push on the stack the contents of table 'arg' from 1 to #arg
*/
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++)
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 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) {
int n = pushargs(L); /* push arguments to script */
status = docall(L, n, LUA_MULTRET);
}
return report(L, status);
}
/* bits of various argument indicators in 'args' */
#define has_error 1 /* bad option */
#define has_i 2 /* -i */
#define has_v 4 /* -v */
#define has_e 8 /* -e */
#define has_E 16 /* -E */
/*
** Traverses all arguments from 'argv', returning a mask with those
** needed before running any Lua code (or an error code if it finds
** any invalid argument). 'first' returns the first not-handled argument
** (either the script name or a bad argument in case of error).
*/
static int collectargs (char **argv, int *first) {
int args = 0;
int i;
for (i = 1; argv[i] != NULL; i++) {
*first = i;
if (argv[i][0] != '-') /* not an option? */
return args; /* stop handling options */
switch (argv[i][1]) { /* else check option */
case '-': /* '--' */
if (argv[i][2] != '\0') /* extra characters after '--'? */
return has_error; /* invalid option */
*first = i + 1;
return args;
case '\0': /* '-' */
return args; /* script "name" is '-' */
case 'E':
if (argv[i][2] != '\0') /* extra characters? */
return has_error; /* invalid option */
args |= has_E;
break;
case 'W':
if (argv[i][2] != '\0') /* extra characters? */
return has_error; /* invalid option */
break;
case 'i':
args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
case 'v':
if (argv[i][2] != '\0') /* extra characters? */
return has_error; /* invalid option */
args |= has_v;
break;
case 'e':
args |= has_e; /* FALLTHROUGH */
case 'l': /* both options need an argument */
if (argv[i][2] == '\0') { /* no concatenated argument? */
i++; /* try next 'argv' */
if (argv[i] == NULL || argv[i][0] == '-')
return has_error; /* no next argument or it is another option */
}
break;
default: /* invalid option */
return has_error;
}
}
*first = i; /* no script name */
return args;
}
/*
** Processes options 'e' and 'l', which involve running Lua code, and
** 'W', which also affects the state.
** Returns 0 if some code raises an error.
*/
static int runargs (lua_State *L, char **argv, int n) {
int i;
for (i = 1; i < n; i++) {
int option = argv[i][1];
lua_assert(argv[i][0] == '-'); /* already checked */
switch (option) {
case 'e': case 'l': {
int status;
const char *extra = argv[i] + 2; /* both options need an argument */
if (*extra == '\0') extra = argv[++i];
lua_assert(extra != NULL);
status = (option == 'e')
? dostring(L, extra, "=(command line)")
: dolibrary(L, extra);
if (status != LUA_OK) return 0;
break;
}
case 'W':
lua_warning(L, "@on", 0); /* warnings on */
break;
}
}
return 1;
}
static int handle_luainit (lua_State *L) {
const char *name = "=" LUA_INITVARVERSION;
const char *init = getenv(name + 1);
if (init == NULL) {
name = "=" LUA_INIT_VAR;
init = getenv(name + 1); /* try alternative name */
}
if (init == NULL) return LUA_OK;
else if (init[0] == '@')
return dofile(L, init+1);
else
return dostring(L, init, name);
}
/*
** {==================================================================
** Read-Eval-Print Loop (REPL)
** ===================================================================
*/
#if !defined(LUA_PROMPT)
#define LUA_PROMPT "> "
#define LUA_PROMPT2 ">> "
#endif
#if !defined(LUA_MAXINPUT)
#define LUA_MAXINPUT 512
#endif
/*
** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
** is, whether we're running lua interactively).
*/
#if !defined(lua_stdin_is_tty) /* { */
#if defined(LUA_USE_POSIX) /* { */
#include <unistd.h>
#define lua_stdin_is_tty() isatty(0)
#elif defined(LUA_USE_WINDOWS) /* }{ */
#include <io.h>
#include <windows.h>
#define lua_stdin_is_tty() _isatty(_fileno(stdin))
#else /* }{ */
/* ISO C definition */
#define lua_stdin_is_tty() 1 /* assume stdin is a tty */
#endif /* } */
#endif /* } */
/*
** lua_readline defines how to show a prompt and then read a line from
** the standard input.
** lua_saveline defines how to "save" a read line in a "history".
** lua_freeline defines how to free a line read by lua_readline.
*/
#if !defined(lua_readline) /* { */
#if defined(LUA_USE_READLINE) /* { */
#include <readline/readline.h>
#include <readline/history.h>
#define lua_initreadline(L) ((void)L, rl_readline_name="lua")
#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
#define lua_saveline(L,line) ((void)L, add_history(line))
#define lua_freeline(L,b) ((void)L, free(b))
#else /* }{ */
#define lua_initreadline(L) ((void)L)
#define lua_readline(L,b,p) \
((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
#define lua_saveline(L,line) { (void)L; (void)line; }
#define lua_freeline(L,b) { (void)L; (void)b; }
#endif /* } */
#endif /* } */
/*
** Returns the string to be used as a prompt by the interpreter.
*/
static const char *get_prompt (lua_State *L, int firstline) {
const char *p;
lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
p = lua_tostring(L, -1);
if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
return p;
}
/* mark in error messages for incomplete statements */
#define EOFMARK "<eof>"
#define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
/*
** Check whether 'status' signals a syntax error and the error
** message at the top of the stack ends with the above mark for
** incomplete statements.
*/
static int incomplete (lua_State *L, int status) {
if (status == LUA_ERRSYNTAX) {
size_t lmsg;
const char *msg = lua_tolstring(L, -1, &lmsg);
if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
lua_pop(L, 1);
return 1;
}
}
return 0; /* else... */
}
/*
** Prompt the user, read a line, and push it into the Lua stack.
*/
static int pushline (lua_State *L, int firstline) {
char buffer[LUA_MAXINPUT];
char *b = buffer;
size_t l;
const char *prmt = get_prompt(L, firstline);
int readstatus = lua_readline(L, b, prmt);
if (readstatus == 0)
return 0; /* no input (prompt will be popped by caller) */
lua_pop(L, 1); /* remove prompt */
l = strlen(b);
if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
b[--l] = '\0'; /* remove it */
if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
else
lua_pushlstring(L, b, l);
lua_freeline(L, b);
return 1;
}
/*
** Try to compile line on the stack as 'return <line>;'; on return, stack
** has either compiled chunk or original line (if compilation failed).
*/
static int addreturn (lua_State *L) {
const char *line = lua_tostring(L, -1); /* original line */
const char *retline = lua_pushfstring(L, "return %s;", line);
int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
if (status == LUA_OK) {
lua_remove(L, -2); /* remove modified line */
if (line[0] != '\0') /* non empty? */
lua_saveline(L, line); /* keep history */
}
else
lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
return status;
}
/*
** Read multiple lines until a complete Lua statement
*/
static int multiline (lua_State *L) {
for (;;) { /* repeat until gets a complete statement */
size_t len;
const char *line = lua_tolstring(L, 1, &len); /* get what it has */
int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
if (!incomplete(L, status) || !pushline(L, 0)) {
lua_saveline(L, line); /* keep history */
return status; /* cannot or should not try to add continuation line */
}
lua_pushliteral(L, "\n"); /* add newline... */
lua_insert(L, -2); /* ...between the two lines */
lua_concat(L, 3); /* join them */
}
}
/*
** Read a line and try to load (compile) it first as an expression (by
** adding "return " in front of it) and second as a statement. Return
** the final status of load/call with the resulting function (if any)
** in the top of the stack.
*/
static int loadline (lua_State *L) {
int status;
lua_settop(L, 0);
if (!pushline(L, 1))
return -1; /* no input */
if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
status = multiline(L); /* try as command, maybe with continuation lines */
lua_remove(L, 1); /* remove line from the stack */
lua_assert(lua_gettop(L) == 1);
return status;
}
/*
** Prints (calling the Lua 'print' function) any values on the stack
*/
static void l_print (lua_State *L) {
int n = lua_gettop(L);
if (n > 0) { /* any result to be printed? */
luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
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 'print' (%s)",
lua_tostring(L, -1)));
}
}
/*
** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
** print any results.
*/
static void doREPL (lua_State *L) {
int status;
const char *oldprogname = progname;
progname = NULL; /* no 'progname' on errors in interactive mode */
lua_initreadline(L);
while ((status = loadline(L)) != -1) {
if (status == LUA_OK)
status = docall(L, 0, LUA_MULTRET);
if (status == LUA_OK) l_print(L);
else report(L, status);
}
lua_settop(L, 0); /* clear stack */
lua_writeline();
progname = oldprogname;
}
/* }================================================================== */
/*
** Main body of stand-alone interpreter (to be called in protected mode).
** Reads the options and handles them all.
*/
static int pmain (lua_State *L) {
int argc = (int)lua_tointeger(L, 1);
char **argv = (char **)lua_touserdata(L, 2);
int script;
int args = collectargs(argv, &script);
luaL_checkversion(L); /* check that interpreter has correct version */
if (argv[0] && argv[0][0]) progname = argv[0];
if (args == has_error) { /* bad arg? */
print_usage(argv[script]); /* 'script' has index of bad arg. */
return 0;
}
if (args & has_v) /* option '-v'? */
print_version();
if (args & has_E) { /* option '-E'? */
lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
}
luaL_openlibs(L); /* open standard libraries */
createargtable(L, argv, argc, script); /* create table 'arg' */
lua_gc(L, LUA_GCGEN, 0, 0); /* GC in generational mode */
if (!(args & has_E)) { /* no option '-E'? */
if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
return 0; /* error running LUA_INIT */
}
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) != LUA_OK)
return 0;
if (args & has_i) /* -i option? */
doREPL(L); /* do read-eval-print loop */
else if (script == argc && !(args & (has_e | has_v))) { /* no arguments? */
if (lua_stdin_is_tty()) { /* running in interactive mode? */
print_version();
doREPL(L); /* do read-eval-print loop */
}
else dofile(L, NULL); /* executes stdin as a file */
}
lua_pushboolean(L, 1); /* signal no errors */
return 1;
}
int main (int argc, char **argv) {
int status, result;
lua_State *L = luaL_newstate(); /* create state */
if (L == NULL) {
l_message(argv[0], "cannot create state: not enough memory");
return EXIT_FAILURE;
}
lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
lua_pushinteger(L, argc); /* 1st argument */
lua_pushlightuserdata(L, argv); /* 2nd argument */
status = lua_pcall(L, 2, 1, 0); /* do the call */
result = lua_toboolean(L, -1); /* get result */
report(L, status);
lua_close(L);
return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| xLua/build/lua-5.4.1/src/lua.c/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lua.c",
"repo_id": "xLua",
"token_count": 7504
} | 2,102 |
mkdir build64 & pushd build64
cmake -DLUAC_COMPATIBLE_FORMAT=ON -G "Visual Studio 14 2015 Win64" ..
IF %ERRORLEVEL% NEQ 0 cmake -DLUAC_COMPATIBLE_FORMAT=ON -G "Visual Studio 15 2017 Win64" ..
popd
cmake --build build64 --config Release
pause | xLua/build/luac/make_win64.bat/0 | {
"file_path": "xLua/build/luac/make_win64.bat",
"repo_id": "xLua",
"token_count": 89
} | 2,103 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Frequently Asked Questions (FAQ)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Author" content="Mike Pall">
<meta name="Copyright" content="Copyright (C) 2005-2016, Mike Pall">
<meta name="Language" content="en">
<link rel="stylesheet" type="text/css" href="bluequad.css" media="screen">
<link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print">
<style type="text/css">
dd { margin-left: 1.5em; }
</style>
</head>
<body>
<div id="site">
<a href="http://luajit.org"><span>Lua<span id="logo">JIT</span></span></a>
</div>
<div id="head">
<h1>Frequently Asked Questions (FAQ)</h1>
</div>
<div id="nav">
<ul><li>
<a href="luajit.html">LuaJIT</a>
<ul><li>
<a href="http://luajit.org/download.html">Download <span class="ext">»</span></a>
</li><li>
<a href="install.html">Installation</a>
</li><li>
<a href="running.html">Running</a>
</li></ul>
</li><li>
<a href="extensions.html">Extensions</a>
<ul><li>
<a href="ext_ffi.html">FFI Library</a>
<ul><li>
<a href="ext_ffi_tutorial.html">FFI Tutorial</a>
</li><li>
<a href="ext_ffi_api.html">ffi.* API</a>
</li><li>
<a href="ext_ffi_semantics.html">FFI Semantics</a>
</li></ul>
</li><li>
<a href="ext_jit.html">jit.* Library</a>
</li><li>
<a href="ext_c_api.html">Lua/C API</a>
</li><li>
<a href="ext_profiler.html">Profiler</a>
</li></ul>
</li><li>
<a href="status.html">Status</a>
<ul><li>
<a href="changes.html">Changes</a>
</li></ul>
</li><li>
<a class="current" href="faq.html">FAQ</a>
</li><li>
<a href="http://luajit.org/performance.html">Performance <span class="ext">»</span></a>
</li><li>
<a href="http://wiki.luajit.org/">Wiki <span class="ext">»</span></a>
</li><li>
<a href="http://luajit.org/list.html">Mailing List <span class="ext">»</span></a>
</li></ul>
</div>
<div id="main">
<dl>
<dt>Q: Where can I learn more about LuaJIT and Lua?</dt>
<dd>
<ul style="padding: 0;">
<li>The <a href="http://luajit.org/list.html"><span class="ext">»</span> LuaJIT mailing list</a> focuses on topics
related to LuaJIT.</li>
<li>The <a href="http://wiki.luajit.org/"><span class="ext">»</span> LuaJIT wiki</a> gathers community
resources about LuaJIT.</li>
<li>News about Lua itself can be found at the
<a href="http://www.lua.org/lua-l.html"><span class="ext">»</span> Lua mailing list</a>.
The mailing list archives are worth checking out for older postings
about LuaJIT.</li>
<li>The <a href="http://lua.org"><span class="ext">»</span> main Lua.org site</a> has complete
<a href="http://www.lua.org/docs.html"><span class="ext">»</span> documentation</a> of the language
and links to books and papers about Lua.</li>
<li>The community-managed <a href="http://lua-users.org/wiki/"><span class="ext">»</span> Lua Wiki</a>
has information about diverse topics.</li>
</ul>
</dl>
<dl>
<dt>Q: Where can I learn more about the compiler technology used by LuaJIT?</dt>
<dd>
I'm planning to write more documentation about the internals of LuaJIT.
In the meantime, please use the following Google Scholar searches
to find relevant papers:<br>
Search for: <a href="http://scholar.google.com/scholar?q=Trace+Compiler"><span class="ext">»</span> Trace Compiler</a><br>
Search for: <a href="http://scholar.google.com/scholar?q=JIT+Compiler"><span class="ext">»</span> JIT Compiler</a><br>
Search for: <a href="http://scholar.google.com/scholar?q=Dynamic+Language+Optimizations"><span class="ext">»</span> Dynamic Language Optimizations</a><br>
Search for: <a href="http://scholar.google.com/scholar?q=SSA+Form"><span class="ext">»</span> SSA Form</a><br>
Search for: <a href="http://scholar.google.com/scholar?q=Linear+Scan+Register+Allocation"><span class="ext">»</span> Linear Scan Register Allocation</a><br>
Here is a list of the <a href="http://article.gmane.org/gmane.comp.lang.lua.general/58908"><span class="ext">»</span> innovative features in LuaJIT</a>.<br>
And, you know, reading the source is of course the only way to enlightenment. :-)
</dd>
</dl>
<dl>
<dt>Q: Why do I get this error: "attempt to index global 'arg' (a nil value)"?<br>
Q: My vararg functions fail after switching to LuaJIT!</dt>
<dd>LuaJIT is compatible to the Lua 5.1 language standard. It doesn't
support the implicit <tt>arg</tt> parameter for old-style vararg
functions from Lua 5.0.<br>Please convert your code to the
<a href="http://www.lua.org/manual/5.1/manual.html#2.5.9"><span class="ext">»</span> Lua 5.1
vararg syntax</a>.</dd>
</dl>
<dl>
<dt>Q: Why do I get this error: "bad FPU precision"?<br>
<dt>Q: I get weird behavior after initializing Direct3D.<br>
<dt>Q: Some FPU operations crash after I load a Delphi DLL.<br>
</dt>
<dd>
DirectX/Direct3D (up to version 9) sets the x87 FPU to single-precision
mode by default. This violates the Windows ABI and interferes with the
operation of many programs — LuaJIT is affected, too. Please make
sure you always use the <tt>D3DCREATE_FPU_PRESERVE</tt> flag when
initializing Direct3D.<br>
Direct3D version 10 or higher do not show this behavior anymore.
Consider testing your application with older versions, too.<br>
Similarly, the Borland/Delphi runtime modifies the FPU control word and
enables FP exceptions. Of course this violates the Windows ABI, too.
Please check the Delphi docs for the Set8087CW method.
</dl>
<dl>
<dt>Q: Sometimes Ctrl-C fails to stop my Lua program. Why?</dt>
<dd>The interrupt signal handler sets a Lua debug hook. But this is
currently ignored by compiled code (this will eventually be fixed). If
your program is running in a tight loop and never falls back to the
interpreter, the debug hook never runs and can't throw the
"interrupted!" error.<br> In the meantime you have to press Ctrl-C
twice to get stop your program. That's similar to when it's stuck
running inside a C function under the Lua interpreter.</dd>
</dl>
<dl>
<dt>Q: Why doesn't my favorite power-patch for Lua apply against LuaJIT?</dt>
<dd>Because it's a completely redesigned VM and has very little code
in common with Lua anymore. Also, if the patch introduces changes to
the Lua semantics, these would need to be reflected everywhere in the
VM, from the interpreter up to all stages of the compiler.<br> Please
use only standard Lua language constructs. For many common needs you
can use source transformations or use wrapper or proxy functions.
The compiler will happily optimize away such indirections.</dd>
</dl>
<dl>
<dt>Q: Lua runs everywhere. Why doesn't LuaJIT support my CPU?</dt>
<dd>Because it's a compiler — it needs to generate native
machine code. This means the code generator must be ported to each
architecture. And the fast interpreter is written in assembler and
must be ported, too. This is quite an undertaking.<br>
The <a href="install.html">install documentation</a> shows the supported
architectures. Other architectures will follow based on sufficient user
demand and/or sponsoring.</dd>
</dl>
<dl>
<dt>Q: When will feature X be added? When will the next version be released?</dt>
<dd>When it's ready.<br>
C'mon, it's open source — I'm doing it on my own time and you're
getting it for free. You can either contribute a patch or sponsor
the development of certain features, if they are important to you.
</dd>
</dl>
<br class="flush">
</div>
<div id="foot">
<hr class="hide">
Copyright © 2005-2016 Mike Pall
<span class="noprint">
·
<a href="contact.html">Contact</a>
</span>
</div>
</body>
</html>
| xLua/build/luajit-2.1.0b2/doc/faq.html/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/doc/faq.html",
"repo_id": "xLua",
"token_count": 2661
} | 2,104 |
/*
** DynASM x86 encoding engine.
** Copyright (C) 2005-2016 Mike Pall. All rights reserved.
** Released under the MIT license. See dynasm.lua for full copyright notice.
*/
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#define DASM_ARCH "x86"
#ifndef DASM_EXTERN
#define DASM_EXTERN(a,b,c,d) 0
#endif
/* Action definitions. DASM_STOP must be 255. */
enum {
DASM_DISP = 233,
DASM_IMM_S, DASM_IMM_B, DASM_IMM_W, DASM_IMM_D, DASM_IMM_WB, DASM_IMM_DB,
DASM_VREG, DASM_SPACE, DASM_SETLABEL, DASM_REL_A, DASM_REL_LG, DASM_REL_PC,
DASM_IMM_LG, DASM_IMM_PC, DASM_LABEL_LG, DASM_LABEL_PC, DASM_ALIGN,
DASM_EXTERN, DASM_ESC, DASM_MARK, DASM_SECTION, DASM_STOP
};
/* Maximum number of section buffer positions for a single dasm_put() call. */
#define DASM_MAXSECPOS 25
/* DynASM encoder status codes. Action list offset or number are or'ed in. */
#define DASM_S_OK 0x00000000
#define DASM_S_NOMEM 0x01000000
#define DASM_S_PHASE 0x02000000
#define DASM_S_MATCH_SEC 0x03000000
#define DASM_S_RANGE_I 0x11000000
#define DASM_S_RANGE_SEC 0x12000000
#define DASM_S_RANGE_LG 0x13000000
#define DASM_S_RANGE_PC 0x14000000
#define DASM_S_RANGE_VREG 0x15000000
#define DASM_S_UNDEF_L 0x21000000
#define DASM_S_UNDEF_PC 0x22000000
/* Macros to convert positions (8 bit section + 24 bit index). */
#define DASM_POS2IDX(pos) ((pos)&0x00ffffff)
#define DASM_POS2BIAS(pos) ((pos)&0xff000000)
#define DASM_SEC2POS(sec) ((sec)<<24)
#define DASM_POS2SEC(pos) ((pos)>>24)
#define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos))
/* Action list type. */
typedef const unsigned char *dasm_ActList;
/* Per-section structure. */
typedef struct dasm_Section {
int *rbuf; /* Biased buffer pointer (negative section bias). */
int *buf; /* True buffer pointer. */
size_t bsize; /* Buffer size in bytes. */
int pos; /* Biased buffer position. */
int epos; /* End of biased buffer position - max single put. */
int ofs; /* Byte offset into section. */
} dasm_Section;
/* Core structure holding the DynASM encoding state. */
struct dasm_State {
size_t psize; /* Allocated size of this structure. */
dasm_ActList actionlist; /* Current actionlist pointer. */
int *lglabels; /* Local/global chain/pos ptrs. */
size_t lgsize;
int *pclabels; /* PC label chains/pos ptrs. */
size_t pcsize;
void **globals; /* Array of globals (bias -10). */
dasm_Section *section; /* Pointer to active section. */
size_t codesize; /* Total size of all code sections. */
int maxsection; /* 0 <= sectionidx < maxsection. */
int status; /* Status code. */
dasm_Section sections[1]; /* All sections. Alloc-extended. */
};
/* The size of the core structure depends on the max. number of sections. */
#define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section))
/* Initialize DynASM state. */
void dasm_init(Dst_DECL, int maxsection)
{
dasm_State *D;
size_t psz = 0;
int i;
Dst_REF = NULL;
DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection));
D = Dst_REF;
D->psize = psz;
D->lglabels = NULL;
D->lgsize = 0;
D->pclabels = NULL;
D->pcsize = 0;
D->globals = NULL;
D->maxsection = maxsection;
for (i = 0; i < maxsection; i++) {
D->sections[i].buf = NULL; /* Need this for pass3. */
D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i);
D->sections[i].bsize = 0;
D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */
}
}
/* Free DynASM state. */
void dasm_free(Dst_DECL)
{
dasm_State *D = Dst_REF;
int i;
for (i = 0; i < D->maxsection; i++)
if (D->sections[i].buf)
DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize);
if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize);
if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize);
DASM_M_FREE(Dst, D, D->psize);
}
/* Setup global label array. Must be called before dasm_setup(). */
void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl)
{
dasm_State *D = Dst_REF;
D->globals = gl - 10; /* Negative bias to compensate for locals. */
DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int));
}
/* Grow PC label array. Can be called after dasm_setup(), too. */
void dasm_growpc(Dst_DECL, unsigned int maxpc)
{
dasm_State *D = Dst_REF;
size_t osz = D->pcsize;
DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int));
memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz);
}
/* Setup encoder. */
void dasm_setup(Dst_DECL, const void *actionlist)
{
dasm_State *D = Dst_REF;
int i;
D->actionlist = (dasm_ActList)actionlist;
D->status = DASM_S_OK;
D->section = &D->sections[0];
memset((void *)D->lglabels, 0, D->lgsize);
if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize);
for (i = 0; i < D->maxsection; i++) {
D->sections[i].pos = DASM_SEC2POS(i);
D->sections[i].ofs = 0;
}
}
#ifdef DASM_CHECKS
#define CK(x, st) \
do { if (!(x)) { \
D->status = DASM_S_##st|(int)(p-D->actionlist-1); return; } } while (0)
#define CKPL(kind, st) \
do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \
D->status=DASM_S_RANGE_##st|(int)(p-D->actionlist-1); return; } } while (0)
#else
#define CK(x, st) ((void)0)
#define CKPL(kind, st) ((void)0)
#endif
/* Pass 1: Store actions and args, link branches/labels, estimate offsets. */
void dasm_put(Dst_DECL, int start, ...)
{
va_list ap;
dasm_State *D = Dst_REF;
dasm_ActList p = D->actionlist + start;
dasm_Section *sec = D->section;
int pos = sec->pos, ofs = sec->ofs, mrm = -1;
int *b;
if (pos >= sec->epos) {
DASM_M_GROW(Dst, int, sec->buf, sec->bsize,
sec->bsize + 2*DASM_MAXSECPOS*sizeof(int));
sec->rbuf = sec->buf - DASM_POS2BIAS(pos);
sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos);
}
b = sec->rbuf;
b[pos++] = start;
va_start(ap, start);
while (1) {
int action = *p++;
if (action < DASM_DISP) {
ofs++;
} else if (action <= DASM_REL_A) {
int n = va_arg(ap, int);
b[pos++] = n;
switch (action) {
case DASM_DISP:
if (n == 0) { if (mrm < 0) mrm = p[-2]; if ((mrm&7) != 5) break; }
case DASM_IMM_DB: if (((n+128)&-256) == 0) goto ob;
case DASM_REL_A: /* Assumes ptrdiff_t is int. !x64 */
case DASM_IMM_D: ofs += 4; break;
case DASM_IMM_S: CK(((n+128)&-256) == 0, RANGE_I); goto ob;
case DASM_IMM_B: CK((n&-256) == 0, RANGE_I); ob: ofs++; break;
case DASM_IMM_WB: if (((n+128)&-256) == 0) goto ob;
case DASM_IMM_W: CK((n&-65536) == 0, RANGE_I); ofs += 2; break;
case DASM_SPACE: p++; ofs += n; break;
case DASM_SETLABEL: b[pos-2] = -0x40000000; break; /* Neg. label ofs. */
case DASM_VREG: CK((n&-16) == 0 && (n != 4 || (*p>>5) != 2), RANGE_VREG);
if (*p < 0x40 && p[1] == DASM_DISP) mrm = n;
if (*p < 0x20 && (n&7) == 4) ofs++;
switch ((*p++ >> 3) & 3) {
case 3: n |= b[pos-3];
case 2: n |= b[pos-2];
case 1: if (n <= 7) { b[pos-1] |= 0x10; ofs--; }
}
continue;
}
mrm = -1;
} else {
int *pl, n;
switch (action) {
case DASM_REL_LG:
case DASM_IMM_LG:
n = *p++; pl = D->lglabels + n;
/* Bkwd rel or global. */
if (n <= 246) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; }
pl -= 246; n = *pl;
if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */
goto linkrel;
case DASM_REL_PC:
case DASM_IMM_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC);
putrel:
n = *pl;
if (n < 0) { /* Label exists. Get label pos and store it. */
b[pos] = -n;
} else {
linkrel:
b[pos] = n; /* Else link to rel chain, anchored at label. */
*pl = pos;
}
pos++;
ofs += 4; /* Maximum offset needed. */
if (action == DASM_REL_LG || action == DASM_REL_PC)
b[pos++] = ofs; /* Store pass1 offset estimate. */
break;
case DASM_LABEL_LG: pl = D->lglabels + *p++; CKPL(lg, LG); goto putlabel;
case DASM_LABEL_PC: pl = D->pclabels + va_arg(ap, int); CKPL(pc, PC);
putlabel:
n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */
while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; }
*pl = -pos; /* Label exists now. */
b[pos++] = ofs; /* Store pass1 offset estimate. */
break;
case DASM_ALIGN:
ofs += *p++; /* Maximum alignment needed (arg is 2**n-1). */
b[pos++] = ofs; /* Store pass1 offset estimate. */
break;
case DASM_EXTERN: p += 2; ofs += 4; break;
case DASM_ESC: p++; ofs++; break;
case DASM_MARK: mrm = p[-2]; break;
case DASM_SECTION:
n = *p; CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n];
case DASM_STOP: goto stop;
}
}
}
stop:
va_end(ap);
sec->pos = pos;
sec->ofs = ofs;
}
#undef CK
/* Pass 2: Link sections, shrink branches/aligns, fix label offsets. */
int dasm_link(Dst_DECL, size_t *szp)
{
dasm_State *D = Dst_REF;
int secnum;
int ofs = 0;
#ifdef DASM_CHECKS
*szp = 0;
if (D->status != DASM_S_OK) return D->status;
{
int pc;
for (pc = 0; pc*sizeof(int) < D->pcsize; pc++)
if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc;
}
#endif
{ /* Handle globals not defined in this translation unit. */
int idx;
for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) {
int n = D->lglabels[idx];
/* Undefined label: Collapse rel chain and replace with marker (< 0). */
while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; }
}
}
/* Combine all code sections. No support for data sections (yet). */
for (secnum = 0; secnum < D->maxsection; secnum++) {
dasm_Section *sec = D->sections + secnum;
int *b = sec->rbuf;
int pos = DASM_SEC2POS(secnum);
int lastpos = sec->pos;
while (pos != lastpos) {
dasm_ActList p = D->actionlist + b[pos++];
while (1) {
int op, action = *p++;
switch (action) {
case DASM_REL_LG: p++; op = p[-3]; goto rel_pc;
case DASM_REL_PC: op = p[-2]; rel_pc: {
int shrink = op == 0xe9 ? 3 : ((op&0xf0) == 0x80 ? 4 : 0);
if (shrink) { /* Shrinkable branch opcode? */
int lofs, lpos = b[pos];
if (lpos < 0) goto noshrink; /* Ext global? */
lofs = *DASM_POS2PTR(D, lpos);
if (lpos > pos) { /* Fwd label: add cumulative section offsets. */
int i;
for (i = secnum; i < DASM_POS2SEC(lpos); i++)
lofs += D->sections[i].ofs;
} else {
lofs -= ofs; /* Bkwd label: unfix offset. */
}
lofs -= b[pos+1]; /* Short branch ok? */
if (lofs >= -128-shrink && lofs <= 127) ofs -= shrink; /* Yes. */
else { noshrink: shrink = 0; } /* No, cannot shrink op. */
}
b[pos+1] = shrink;
pos += 2;
break;
}
case DASM_SPACE: case DASM_IMM_LG: case DASM_VREG: p++;
case DASM_DISP: case DASM_IMM_S: case DASM_IMM_B: case DASM_IMM_W:
case DASM_IMM_D: case DASM_IMM_WB: case DASM_IMM_DB:
case DASM_SETLABEL: case DASM_REL_A: case DASM_IMM_PC: pos++; break;
case DASM_LABEL_LG: p++;
case DASM_LABEL_PC: b[pos++] += ofs; break; /* Fix label offset. */
case DASM_ALIGN: ofs -= (b[pos++]+ofs)&*p++; break; /* Adjust ofs. */
case DASM_EXTERN: p += 2; break;
case DASM_ESC: p++; break;
case DASM_MARK: break;
case DASM_SECTION: case DASM_STOP: goto stop;
}
}
stop: (void)0;
}
ofs += sec->ofs; /* Next section starts right after current section. */
}
D->codesize = ofs; /* Total size of all code sections */
*szp = ofs;
return DASM_S_OK;
}
#define dasmb(x) *cp++ = (unsigned char)(x)
#ifndef DASM_ALIGNED_WRITES
#define dasmw(x) \
do { *((unsigned short *)cp) = (unsigned short)(x); cp+=2; } while (0)
#define dasmd(x) \
do { *((unsigned int *)cp) = (unsigned int)(x); cp+=4; } while (0)
#else
#define dasmw(x) do { dasmb(x); dasmb((x)>>8); } while (0)
#define dasmd(x) do { dasmw(x); dasmw((x)>>16); } while (0)
#endif
/* Pass 3: Encode sections. */
int dasm_encode(Dst_DECL, void *buffer)
{
dasm_State *D = Dst_REF;
unsigned char *base = (unsigned char *)buffer;
unsigned char *cp = base;
int secnum;
/* Encode all code sections. No support for data sections (yet). */
for (secnum = 0; secnum < D->maxsection; secnum++) {
dasm_Section *sec = D->sections + secnum;
int *b = sec->buf;
int *endb = sec->rbuf + sec->pos;
while (b != endb) {
dasm_ActList p = D->actionlist + *b++;
unsigned char *mark = NULL;
while (1) {
int action = *p++;
int n = (action >= DASM_DISP && action <= DASM_ALIGN) ? *b++ : 0;
switch (action) {
case DASM_DISP: if (!mark) mark = cp; {
unsigned char *mm = mark;
if (*p != DASM_IMM_DB && *p != DASM_IMM_WB) mark = NULL;
if (n == 0) { int mrm = mm[-1]&7; if (mrm == 4) mrm = mm[0]&7;
if (mrm != 5) { mm[-1] -= 0x80; break; } }
if (((n+128) & -256) != 0) goto wd; else mm[-1] -= 0x40;
}
case DASM_IMM_S: case DASM_IMM_B: wb: dasmb(n); break;
case DASM_IMM_DB: if (((n+128)&-256) == 0) {
db: if (!mark) mark = cp; mark[-2] += 2; mark = NULL; goto wb;
} else mark = NULL;
case DASM_IMM_D: wd: dasmd(n); break;
case DASM_IMM_WB: if (((n+128)&-256) == 0) goto db; else mark = NULL;
case DASM_IMM_W: dasmw(n); break;
case DASM_VREG: {
int t = *p++;
unsigned char *ex = cp - (t&7);
if ((n & 8) && t < 0xa0) {
if (*ex & 0x80) ex[1] ^= 0x20 << (t>>6); else *ex ^= 1 << (t>>6);
n &= 7;
} else if (n & 0x10) {
if (*ex & 0x80) {
*ex = 0xc5; ex[1] = (ex[1] & 0x80) | ex[2]; ex += 2;
}
while (++ex < cp) ex[-1] = *ex;
if (mark) mark--;
cp--;
n &= 7;
}
if (t >= 0xc0) n <<= 4;
else if (t >= 0x40) n <<= 3;
else if (n == 4 && t < 0x20) { cp[-1] ^= n; *cp++ = 0x20; }
cp[-1] ^= n;
break;
}
case DASM_REL_LG: p++; if (n >= 0) goto rel_pc;
b++; n = (int)(ptrdiff_t)D->globals[-n];
case DASM_REL_A: rel_a: n -= (int)(ptrdiff_t)(cp+4); goto wd; /* !x64 */
case DASM_REL_PC: rel_pc: {
int shrink = *b++;
int *pb = DASM_POS2PTR(D, n); if (*pb < 0) { n = pb[1]; goto rel_a; }
n = *pb - ((int)(cp-base) + 4-shrink);
if (shrink == 0) goto wd;
if (shrink == 4) { cp--; cp[-1] = *cp-0x10; } else cp[-1] = 0xeb;
goto wb;
}
case DASM_IMM_LG:
p++; if (n < 0) { n = (int)(ptrdiff_t)D->globals[-n]; goto wd; }
case DASM_IMM_PC: {
int *pb = DASM_POS2PTR(D, n);
n = *pb < 0 ? pb[1] : (*pb + (int)(ptrdiff_t)base);
goto wd;
}
case DASM_LABEL_LG: {
int idx = *p++;
if (idx >= 10)
D->globals[idx] = (void *)(base + (*p == DASM_SETLABEL ? *b : n));
break;
}
case DASM_LABEL_PC: case DASM_SETLABEL: break;
case DASM_SPACE: { int fill = *p++; while (n--) *cp++ = fill; break; }
case DASM_ALIGN:
n = *p++;
while (((cp-base) & n)) *cp++ = 0x90; /* nop */
break;
case DASM_EXTERN: n = DASM_EXTERN(Dst, cp, p[1], *p); p += 2; goto wd;
case DASM_MARK: mark = cp; break;
case DASM_ESC: action = *p++;
default: *cp++ = action; break;
case DASM_SECTION: case DASM_STOP: goto stop;
}
}
stop: (void)0;
}
}
if (base + D->codesize != cp) /* Check for phase errors. */
return DASM_S_PHASE;
return DASM_S_OK;
}
/* Get PC label offset. */
int dasm_getpclabel(Dst_DECL, unsigned int pc)
{
dasm_State *D = Dst_REF;
if (pc*sizeof(int) < D->pcsize) {
int pos = D->pclabels[pc];
if (pos < 0) return *DASM_POS2PTR(D, -pos);
if (pos > 0) return -1; /* Undefined. */
}
return -2; /* Unused or out of range. */
}
#ifdef DASM_CHECKS
/* Optional sanity checker to call between isolated encoding steps. */
int dasm_checkstep(Dst_DECL, int secmatch)
{
dasm_State *D = Dst_REF;
if (D->status == DASM_S_OK) {
int i;
for (i = 1; i <= 9; i++) {
if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_L|i; break; }
D->lglabels[i] = 0;
}
}
if (D->status == DASM_S_OK && secmatch >= 0 &&
D->section != &D->sections[secmatch])
D->status = DASM_S_MATCH_SEC|(int)(D->section-D->sections);
return D->status;
}
#endif
| xLua/build/luajit-2.1.0b2/dynasm/dasm_x86.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/dynasm/dasm_x86.h",
"repo_id": "xLua",
"token_count": 7572
} | 2,105 |
----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2016 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
int _CRT_glob = 0;
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| xLua/build/luajit-2.1.0b2/src/host/genminilua.lua/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/host/genminilua.lua",
"repo_id": "xLua",
"token_count": 5521
} | 2,106 |
/*
** Base and coroutine library.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
**
** Major portions taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#include <stdio.h>
#define lib_base_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_debug.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_meta.h"
#include "lj_state.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#include "lj_cconv.h"
#endif
#include "lj_bc.h"
#include "lj_ff.h"
#include "lj_dispatch.h"
#include "lj_char.h"
#include "lj_strscan.h"
#include "lj_strfmt.h"
#include "lj_lib.h"
/* -- Base library: checks ------------------------------------------------ */
#define LJLIB_MODULE_base
LJLIB_ASM(assert) LJLIB_REC(.)
{
GCstr *s;
lj_lib_checkany(L, 1);
s = lj_lib_optstr(L, 2);
if (s)
lj_err_callermsg(L, strdata(s));
else
lj_err_caller(L, LJ_ERR_ASSERT);
return FFH_UNREACHABLE;
}
/* ORDER LJ_T */
LJLIB_PUSH("nil")
LJLIB_PUSH("boolean")
LJLIB_PUSH(top-1) /* boolean */
LJLIB_PUSH("userdata")
LJLIB_PUSH("string")
LJLIB_PUSH("upval")
LJLIB_PUSH("thread")
LJLIB_PUSH("proto")
LJLIB_PUSH("function")
LJLIB_PUSH("trace")
LJLIB_PUSH("cdata")
LJLIB_PUSH("table")
LJLIB_PUSH(top-9) /* userdata */
LJLIB_PUSH("number")
LJLIB_ASM_(type) LJLIB_REC(.)
/* Recycle the lj_lib_checkany(L, 1) from assert. */
/* -- Base library: iterators --------------------------------------------- */
/* This solves a circular dependency problem -- change FF_next_N as needed. */
LJ_STATIC_ASSERT((int)FF_next == FF_next_N);
LJLIB_ASM(next)
{
lj_lib_checktab(L, 1);
return FFH_UNREACHABLE;
}
#if LJ_52 || LJ_HASFFI
static int ffh_pairs(lua_State *L, MMS mm)
{
TValue *o = lj_lib_checkany(L, 1);
cTValue *mo = lj_meta_lookup(L, o, mm);
if ((LJ_52 || tviscdata(o)) && !tvisnil(mo)) {
L->top = o+1; /* Only keep one argument. */
copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
return FFH_TAILCALL;
} else {
if (!tvistab(o)) lj_err_argt(L, 1, LUA_TTABLE);
if (LJ_FR2) { copyTV(L, o-1, o); o--; }
setfuncV(L, o-1, funcV(lj_lib_upvalue(L, 1)));
if (mm == MM_pairs) setnilV(o+1); else setintV(o+1, 0);
return FFH_RES(3);
}
}
#else
#define ffh_pairs(L, mm) (lj_lib_checktab(L, 1), FFH_UNREACHABLE)
#endif
LJLIB_PUSH(lastcl)
LJLIB_ASM(pairs) LJLIB_REC(xpairs 0)
{
return ffh_pairs(L, MM_pairs);
}
LJLIB_NOREGUV LJLIB_ASM(ipairs_aux) LJLIB_REC(.)
{
lj_lib_checktab(L, 1);
lj_lib_checkint(L, 2);
return FFH_UNREACHABLE;
}
LJLIB_PUSH(lastcl)
LJLIB_ASM(ipairs) LJLIB_REC(xpairs 1)
{
return ffh_pairs(L, MM_ipairs);
}
/* -- Base library: getters and setters ----------------------------------- */
LJLIB_ASM_(getmetatable) LJLIB_REC(.)
/* Recycle the lj_lib_checkany(L, 1) from assert. */
LJLIB_ASM(setmetatable) LJLIB_REC(.)
{
GCtab *t = lj_lib_checktab(L, 1);
GCtab *mt = lj_lib_checktabornil(L, 2);
if (!tvisnil(lj_meta_lookup(L, L->base, MM_metatable)))
lj_err_caller(L, LJ_ERR_PROTMT);
setgcref(t->metatable, obj2gco(mt));
if (mt) { lj_gc_objbarriert(L, t, mt); }
settabV(L, L->base-1-LJ_FR2, t);
return FFH_RES(1);
}
LJLIB_CF(getfenv) LJLIB_REC(.)
{
GCfunc *fn;
cTValue *o = L->base;
if (!(o < L->top && tvisfunc(o))) {
int level = lj_lib_optint(L, 1, 1);
o = lj_debug_frame(L, level, &level);
if (o == NULL)
lj_err_arg(L, 1, LJ_ERR_INVLVL);
if (LJ_FR2) o--;
}
fn = &gcval(o)->fn;
settabV(L, L->top++, isluafunc(fn) ? tabref(fn->l.env) : tabref(L->env));
return 1;
}
LJLIB_CF(setfenv)
{
GCfunc *fn;
GCtab *t = lj_lib_checktab(L, 2);
cTValue *o = L->base;
if (!(o < L->top && tvisfunc(o))) {
int level = lj_lib_checkint(L, 1);
if (level == 0) {
/* NOBARRIER: A thread (i.e. L) is never black. */
setgcref(L->env, obj2gco(t));
return 0;
}
o = lj_debug_frame(L, level, &level);
if (o == NULL)
lj_err_arg(L, 1, LJ_ERR_INVLVL);
if (LJ_FR2) o--;
}
fn = &gcval(o)->fn;
if (!isluafunc(fn))
lj_err_caller(L, LJ_ERR_SETFENV);
setgcref(fn->l.env, obj2gco(t));
lj_gc_objbarrier(L, obj2gco(fn), t);
setfuncV(L, L->top++, fn);
return 1;
}
LJLIB_ASM(rawget) LJLIB_REC(.)
{
lj_lib_checktab(L, 1);
lj_lib_checkany(L, 2);
return FFH_UNREACHABLE;
}
LJLIB_CF(rawset) LJLIB_REC(.)
{
lj_lib_checktab(L, 1);
lj_lib_checkany(L, 2);
L->top = 1+lj_lib_checkany(L, 3);
lua_rawset(L, 1);
return 1;
}
LJLIB_CF(rawequal) LJLIB_REC(.)
{
cTValue *o1 = lj_lib_checkany(L, 1);
cTValue *o2 = lj_lib_checkany(L, 2);
setboolV(L->top-1, lj_obj_equal(o1, o2));
return 1;
}
#if LJ_52
LJLIB_CF(rawlen) LJLIB_REC(.)
{
cTValue *o = L->base;
int32_t len;
if (L->top > o && tvisstr(o))
len = (int32_t)strV(o)->len;
else
len = (int32_t)lj_tab_len(lj_lib_checktab(L, 1));
setintV(L->top-1, len);
return 1;
}
#endif
LJLIB_CF(unpack)
{
GCtab *t = lj_lib_checktab(L, 1);
int32_t n, i = lj_lib_optint(L, 2, 1);
int32_t e = (L->base+3-1 < L->top && !tvisnil(L->base+3-1)) ?
lj_lib_checkint(L, 3) : (int32_t)lj_tab_len(t);
if (i > e) return 0;
n = e - i + 1;
if (n <= 0 || !lua_checkstack(L, n))
lj_err_caller(L, LJ_ERR_UNPACK);
do {
cTValue *tv = lj_tab_getint(t, i);
if (tv) {
copyTV(L, L->top++, tv);
} else {
setnilV(L->top++);
}
} while (i++ < e);
return n;
}
LJLIB_CF(select) LJLIB_REC(.)
{
int32_t n = (int32_t)(L->top - L->base);
if (n >= 1 && tvisstr(L->base) && *strVdata(L->base) == '#') {
setintV(L->top-1, n-1);
return 1;
} else {
int32_t i = lj_lib_checkint(L, 1);
if (i < 0) i = n + i; else if (i > n) i = n;
if (i < 1)
lj_err_arg(L, 1, LJ_ERR_IDXRNG);
return n - i;
}
}
/* -- Base library: conversions ------------------------------------------- */
LJLIB_ASM(tonumber) LJLIB_REC(.)
{
int32_t base = lj_lib_optint(L, 2, 10);
if (base == 10) {
TValue *o = lj_lib_checkany(L, 1);
if (lj_strscan_numberobj(o)) {
copyTV(L, L->base-1-LJ_FR2, o);
return FFH_RES(1);
}
#if LJ_HASFFI
if (tviscdata(o)) {
CTState *cts = ctype_cts(L);
CType *ct = lj_ctype_rawref(cts, cdataV(o)->ctypeid);
if (ctype_isenum(ct->info)) ct = ctype_child(cts, ct);
if (ctype_isnum(ct->info) || ctype_iscomplex(ct->info)) {
if (LJ_DUALNUM && ctype_isinteger_or_bool(ct->info) &&
ct->size <= 4 && !(ct->size == 4 && (ct->info & CTF_UNSIGNED))) {
int32_t i;
lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o, 0);
setintV(L->base-1-LJ_FR2, i);
return FFH_RES(1);
}
lj_cconv_ct_tv(cts, ctype_get(cts, CTID_DOUBLE),
(uint8_t *)&(L->base-1-LJ_FR2)->n, o, 0);
return FFH_RES(1);
}
}
#endif
} else {
const char *p = strdata(lj_lib_checkstr(L, 1));
char *ep;
unsigned long ul;
if (base < 2 || base > 36)
lj_err_arg(L, 2, LJ_ERR_BASERNG);
ul = strtoul(p, &ep, base);
if (p != ep) {
while (lj_char_isspace((unsigned char)(*ep))) ep++;
if (*ep == '\0') {
if (LJ_DUALNUM && LJ_LIKELY(ul < 0x80000000u))
setintV(L->base-1-LJ_FR2, (int32_t)ul);
else
setnumV(L->base-1-LJ_FR2, (lua_Number)ul);
return FFH_RES(1);
}
}
}
setnilV(L->base-1-LJ_FR2);
return FFH_RES(1);
}
LJLIB_ASM(tostring) LJLIB_REC(.)
{
TValue *o = lj_lib_checkany(L, 1);
cTValue *mo;
L->top = o+1; /* Only keep one argument. */
if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {
copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
return FFH_TAILCALL;
}
lj_gc_check(L);
setstrV(L, L->base-1-LJ_FR2, lj_strfmt_obj(L, L->base));
return FFH_RES(1);
}
/* -- Base library: throw and catch errors -------------------------------- */
LJLIB_CF(error)
{
int32_t level = lj_lib_optint(L, 2, 1);
lua_settop(L, 1);
if (lua_isstring(L, 1) && level > 0) {
luaL_where(L, level);
lua_pushvalue(L, 1);
lua_concat(L, 2);
}
return lua_error(L);
}
LJLIB_ASM(pcall) LJLIB_REC(.)
{
lj_lib_checkany(L, 1);
lj_lib_checkfunc(L, 2); /* For xpcall only. */
return FFH_UNREACHABLE;
}
LJLIB_ASM_(xpcall) LJLIB_REC(.)
/* -- Base library: load Lua code ----------------------------------------- */
static int load_aux(lua_State *L, int status, int envarg)
{
if (status == 0) {
if (tvistab(L->base+envarg-1)) {
GCfunc *fn = funcV(L->top-1);
GCtab *t = tabV(L->base+envarg-1);
setgcref(fn->c.env, obj2gco(t));
lj_gc_objbarrier(L, fn, t);
}
return 1;
} else {
setnilV(L->top-2);
return 2;
}
}
LJLIB_CF(loadfile)
{
GCstr *fname = lj_lib_optstr(L, 1);
GCstr *mode = lj_lib_optstr(L, 2);
int status;
lua_settop(L, 3); /* Ensure env arg exists. */
status = luaL_loadfilex(L, fname ? strdata(fname) : NULL,
mode ? strdata(mode) : NULL);
return load_aux(L, status, 3);
}
static const char *reader_func(lua_State *L, void *ud, size_t *size)
{
UNUSED(ud);
luaL_checkstack(L, 2, "too many nested functions");
copyTV(L, L->top++, L->base);
lua_call(L, 0, 1); /* Call user-supplied function. */
L->top--;
if (tvisnil(L->top)) {
*size = 0;
return NULL;
} else if (tvisstr(L->top) || tvisnumber(L->top)) {
copyTV(L, L->base+4, L->top); /* Anchor string in reserved stack slot. */
return lua_tolstring(L, 5, size);
} else {
lj_err_caller(L, LJ_ERR_RDRSTR);
return NULL;
}
}
LJLIB_CF(load)
{
GCstr *name = lj_lib_optstr(L, 2);
GCstr *mode = lj_lib_optstr(L, 3);
int status;
if (L->base < L->top && (tvisstr(L->base) || tvisnumber(L->base))) {
GCstr *s = lj_lib_checkstr(L, 1);
lua_settop(L, 4); /* Ensure env arg exists. */
status = luaL_loadbufferx(L, strdata(s), s->len, strdata(name ? name : s),
mode ? strdata(mode) : NULL);
} else {
lj_lib_checkfunc(L, 1);
lua_settop(L, 5); /* Reserve a slot for the string from the reader. */
status = lua_loadx(L, reader_func, NULL, name ? strdata(name) : "=(load)",
mode ? strdata(mode) : NULL);
}
return load_aux(L, status, 4);
}
LJLIB_CF(loadstring)
{
return lj_cf_load(L);
}
LJLIB_CF(dofile)
{
GCstr *fname = lj_lib_optstr(L, 1);
setnilV(L->top);
L->top = L->base+1;
if (luaL_loadfile(L, fname ? strdata(fname) : NULL) != 0)
lua_error(L);
lua_call(L, 0, LUA_MULTRET);
return (int)(L->top - L->base) - 1;
}
/* -- Base library: GC control -------------------------------------------- */
LJLIB_CF(gcinfo)
{
setintV(L->top++, (int32_t)(G(L)->gc.total >> 10));
return 1;
}
LJLIB_CF(collectgarbage)
{
int opt = lj_lib_checkopt(L, 1, LUA_GCCOLLECT, /* ORDER LUA_GC* */
"\4stop\7restart\7collect\5count\1\377\4step\10setpause\12setstepmul\1\377\11isrunning");
int32_t data = lj_lib_optint(L, 2, 0);
if (opt == LUA_GCCOUNT) {
setnumV(L->top, (lua_Number)G(L)->gc.total/1024.0);
} else {
int res = lua_gc(L, opt, data);
if (opt == LUA_GCSTEP || opt == LUA_GCISRUNNING)
setboolV(L->top, res);
else
setintV(L->top, res);
}
L->top++;
return 1;
}
/* -- Base library: miscellaneous functions ------------------------------- */
LJLIB_PUSH(top-2) /* Upvalue holds weak table. */
LJLIB_CF(newproxy)
{
lua_settop(L, 1);
lua_newuserdata(L, 0);
if (lua_toboolean(L, 1) == 0) { /* newproxy(): without metatable. */
return 1;
} else if (lua_isboolean(L, 1)) { /* newproxy(true): with metatable. */
lua_newtable(L);
lua_pushvalue(L, -1);
lua_pushboolean(L, 1);
lua_rawset(L, lua_upvalueindex(1)); /* Remember mt in weak table. */
} else { /* newproxy(proxy): inherit metatable. */
int validproxy = 0;
if (lua_getmetatable(L, 1)) {
lua_rawget(L, lua_upvalueindex(1));
validproxy = lua_toboolean(L, -1);
lua_pop(L, 1);
}
if (!validproxy)
lj_err_arg(L, 1, LJ_ERR_NOPROXY);
lua_getmetatable(L, 1);
}
lua_setmetatable(L, 2);
return 1;
}
LJLIB_PUSH("tostring")
LJLIB_CF(print)
{
ptrdiff_t i, nargs = L->top - L->base;
cTValue *tv = lj_tab_getstr(tabref(L->env), strV(lj_lib_upvalue(L, 1)));
int shortcut;
if (tv && !tvisnil(tv)) {
copyTV(L, L->top++, tv);
} else {
setstrV(L, L->top++, strV(lj_lib_upvalue(L, 1)));
lua_gettable(L, LUA_GLOBALSINDEX);
tv = L->top-1;
}
shortcut = (tvisfunc(tv) && funcV(tv)->c.ffid == FF_tostring);
for (i = 0; i < nargs; i++) {
cTValue *o = &L->base[i];
const char *str;
size_t size;
MSize len;
if (shortcut && (str = lj_strfmt_wstrnum(L, o, &len)) != NULL) {
size = len;
} else {
copyTV(L, L->top+1, o);
copyTV(L, L->top, L->top-1);
L->top += 2;
lua_call(L, 1, 1);
str = lua_tolstring(L, -1, &size);
if (!str)
lj_err_caller(L, LJ_ERR_PRTOSTR);
L->top--;
}
if (i)
putchar('\t');
fwrite(str, 1, size, stdout);
}
putchar('\n');
return 0;
}
LJLIB_PUSH(top-3)
LJLIB_SET(_VERSION)
#include "lj_libdef.h"
/* -- Coroutine library --------------------------------------------------- */
#define LJLIB_MODULE_coroutine
LJLIB_CF(coroutine_status)
{
const char *s;
lua_State *co;
if (!(L->top > L->base && tvisthread(L->base)))
lj_err_arg(L, 1, LJ_ERR_NOCORO);
co = threadV(L->base);
if (co == L) s = "running";
else if (co->status == LUA_YIELD) s = "suspended";
else if (co->status != 0) s = "dead";
else if (co->base > tvref(co->stack)+1+LJ_FR2) s = "normal";
else if (co->top == co->base) s = "dead";
else s = "suspended";
lua_pushstring(L, s);
return 1;
}
LJLIB_CF(coroutine_running)
{
#if LJ_52
int ismain = lua_pushthread(L);
setboolV(L->top++, ismain);
return 2;
#else
if (lua_pushthread(L))
setnilV(L->top++);
return 1;
#endif
}
LJLIB_CF(coroutine_create)
{
lua_State *L1;
if (!(L->base < L->top && tvisfunc(L->base)))
lj_err_argt(L, 1, LUA_TFUNCTION);
L1 = lua_newthread(L);
setfuncV(L, L1->top++, funcV(L->base));
return 1;
}
LJLIB_ASM(coroutine_yield)
{
lj_err_caller(L, LJ_ERR_CYIELD);
return FFH_UNREACHABLE;
}
static int ffh_resume(lua_State *L, lua_State *co, int wrap)
{
if (co->cframe != NULL || co->status > LUA_YIELD ||
(co->status == 0 && co->top == co->base)) {
ErrMsg em = co->cframe ? LJ_ERR_CORUN : LJ_ERR_CODEAD;
if (wrap) lj_err_caller(L, em);
setboolV(L->base-1-LJ_FR2, 0);
setstrV(L, L->base-LJ_FR2, lj_err_str(L, em));
return FFH_RES(2);
}
lj_state_growstack(co, (MSize)(L->top - L->base));
return FFH_RETRY;
}
LJLIB_ASM(coroutine_resume)
{
if (!(L->top > L->base && tvisthread(L->base)))
lj_err_arg(L, 1, LJ_ERR_NOCORO);
return ffh_resume(L, threadV(L->base), 0);
}
LJLIB_NOREG LJLIB_ASM(coroutine_wrap_aux)
{
return ffh_resume(L, threadV(lj_lib_upvalue(L, 1)), 1);
}
/* Inline declarations. */
LJ_ASMF void lj_ff_coroutine_wrap_aux(void);
#if !(LJ_TARGET_MIPS && defined(ljamalg_c))
LJ_FUNCA_NORET void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L,
lua_State *co);
#endif
/* Error handler, called from assembler VM. */
void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L, lua_State *co)
{
co->top--; copyTV(L, L->top, co->top); L->top++;
if (tvisstr(L->top-1))
lj_err_callermsg(L, strVdata(L->top-1));
else
lj_err_run(L);
}
/* Forward declaration. */
static void setpc_wrap_aux(lua_State *L, GCfunc *fn);
LJLIB_CF(coroutine_wrap)
{
GCfunc *fn;
lj_cf_coroutine_create(L);
fn = lj_lib_pushcc(L, lj_ffh_coroutine_wrap_aux, FF_coroutine_wrap_aux, 1);
setpc_wrap_aux(L, fn);
return 1;
}
#include "lj_libdef.h"
/* Fix the PC of wrap_aux. Really ugly workaround. */
static void setpc_wrap_aux(lua_State *L, GCfunc *fn)
{
setmref(fn->c.pc, &L2GG(L)->bcff[lj_lib_init_coroutine[1]+2]);
}
/* ------------------------------------------------------------------------ */
static void newproxy_weaktable(lua_State *L)
{
/* NOBARRIER: The table is new (marked white). */
GCtab *t = lj_tab_new(L, 0, 1);
settabV(L, L->top++, t);
setgcref(t->metatable, obj2gco(t));
setstrV(L, lj_tab_setstr(L, t, lj_str_newlit(L, "__mode")),
lj_str_newlit(L, "kv"));
t->nomm = (uint8_t)(~(1u<<MM_mode));
}
LUALIB_API int luaopen_base(lua_State *L)
{
/* NOBARRIER: Table and value are the same. */
GCtab *env = tabref(L->env);
settabV(L, lj_tab_setstr(L, env, lj_str_newlit(L, "_G")), env);
lua_pushliteral(L, LUA_VERSION); /* top-3. */
newproxy_weaktable(L); /* top-2. */
LJ_LIB_REG(L, "_G", base);
LJ_LIB_REG(L, LUA_COLIBNAME, coroutine);
return 2;
}
| xLua/build/luajit-2.1.0b2/src/lib_base.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lib_base.c",
"repo_id": "xLua",
"token_count": 8230
} | 2,107 |
/*
** Target architecture selection.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_ARCH_H
#define _LJ_ARCH_H
#include "lua.h"
/* Target endianess. */
#define LUAJIT_LE 0
#define LUAJIT_BE 1
/* Target architectures. */
#define LUAJIT_ARCH_X86 1
#define LUAJIT_ARCH_x86 1
#define LUAJIT_ARCH_X64 2
#define LUAJIT_ARCH_x64 2
#define LUAJIT_ARCH_ARM 3
#define LUAJIT_ARCH_arm 3
#define LUAJIT_ARCH_ARM64 4
#define LUAJIT_ARCH_arm64 4
#define LUAJIT_ARCH_PPC 5
#define LUAJIT_ARCH_ppc 5
#define LUAJIT_ARCH_MIPS 6
#define LUAJIT_ARCH_mips 6
/* Target OS. */
#define LUAJIT_OS_OTHER 0
#define LUAJIT_OS_WINDOWS 1
#define LUAJIT_OS_LINUX 2
#define LUAJIT_OS_OSX 3
#define LUAJIT_OS_BSD 4
#define LUAJIT_OS_POSIX 5
/* Select native target if no target defined. */
#ifndef LUAJIT_TARGET
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
#define LUAJIT_TARGET LUAJIT_ARCH_X86
#elif defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
#define LUAJIT_TARGET LUAJIT_ARCH_X64
#elif defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM)
#define LUAJIT_TARGET LUAJIT_ARCH_ARM
#elif defined(__aarch64__)
#define LUAJIT_TARGET LUAJIT_ARCH_ARM64
#elif defined(__ppc__) || defined(__ppc) || defined(__PPC__) || defined(__PPC) || defined(__powerpc__) || defined(__powerpc) || defined(__POWERPC__) || defined(__POWERPC) || defined(_M_PPC)
#define LUAJIT_TARGET LUAJIT_ARCH_PPC
#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(__MIPS)
#define LUAJIT_TARGET LUAJIT_ARCH_MIPS
#else
#error "No support for this architecture (yet)"
#endif
#endif
/* Select native OS if no target OS defined. */
#ifndef LUAJIT_OS
#if defined(_WIN32) && !defined(_XBOX_VER)
#define LUAJIT_OS LUAJIT_OS_WINDOWS
#elif defined(__linux__)
#define LUAJIT_OS LUAJIT_OS_LINUX
#elif defined(__MACH__) && defined(__APPLE__)
#define LUAJIT_OS LUAJIT_OS_OSX
#elif (defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
defined(__NetBSD__) || defined(__OpenBSD__) || \
defined(__DragonFly__)) && !defined(__ORBIS__)
#define LUAJIT_OS LUAJIT_OS_BSD
#elif (defined(__sun__) && defined(__svr4__)) || defined(__CYGWIN__)
#define LUAJIT_OS LUAJIT_OS_POSIX
#else
#define LUAJIT_OS LUAJIT_OS_OTHER
#endif
#endif
/* Set target OS properties. */
#if LUAJIT_OS == LUAJIT_OS_WINDOWS
#define LJ_OS_NAME "Windows"
#elif LUAJIT_OS == LUAJIT_OS_LINUX
#define LJ_OS_NAME "Linux"
#elif LUAJIT_OS == LUAJIT_OS_OSX
#define LJ_OS_NAME "OSX"
#elif LUAJIT_OS == LUAJIT_OS_BSD
#define LJ_OS_NAME "BSD"
#elif LUAJIT_OS == LUAJIT_OS_POSIX
#define LJ_OS_NAME "POSIX"
#else
#define LJ_OS_NAME "Other"
#endif
#define LJ_TARGET_WINDOWS (LUAJIT_OS == LUAJIT_OS_WINDOWS)
#define LJ_TARGET_LINUX (LUAJIT_OS == LUAJIT_OS_LINUX)
#define LJ_TARGET_OSX (LUAJIT_OS == LUAJIT_OS_OSX)
#define LJ_TARGET_IOS (LJ_TARGET_OSX && (LUAJIT_TARGET == LUAJIT_ARCH_ARM || LUAJIT_TARGET == LUAJIT_ARCH_ARM64))
#define LJ_TARGET_POSIX (LUAJIT_OS > LUAJIT_OS_WINDOWS)
#if LJ_TARGET_IOS
#define LJ_TARGET_DLOPEN 0
#else
#define LJ_TARGET_DLOPEN LJ_TARGET_POSIX
#endif
#ifdef __CELLOS_LV2__
#define LJ_TARGET_PS3 1
#define LJ_TARGET_CONSOLE 1
#endif
#ifdef __ORBIS__
#define LJ_TARGET_PS4 1
#define LJ_TARGET_CONSOLE 1
#undef NULL
#define NULL ((void*)0)
#endif
#ifdef __psp2__
#define LJ_TARGET_PSVITA 1
#define LJ_TARGET_CONSOLE 1
#endif
#if _XBOX_VER >= 200
#define LJ_TARGET_XBOX360 1
#define LJ_TARGET_CONSOLE 1
#endif
#ifdef _DURANGO
#define LJ_TARGET_XBOXONE 1
#define LJ_TARGET_CONSOLE 1
#define LJ_TARGET_GC64 1
#endif
#define LJ_NUMMODE_SINGLE 0 /* Single-number mode only. */
#define LJ_NUMMODE_SINGLE_DUAL 1 /* Default to single-number mode. */
#define LJ_NUMMODE_DUAL 2 /* Dual-number mode only. */
#define LJ_NUMMODE_DUAL_SINGLE 3 /* Default to dual-number mode. */
/* Set target architecture properties. */
#if LUAJIT_TARGET == LUAJIT_ARCH_X86
#define LJ_ARCH_NAME "x86"
#define LJ_ARCH_BITS 32
#define LJ_ARCH_ENDIAN LUAJIT_LE
#if LJ_TARGET_WINDOWS || __CYGWIN__
#define LJ_ABI_WIN 1
#else
#define LJ_ABI_WIN 0
#endif
#define LJ_TARGET_X86 1
#define LJ_TARGET_X86ORX64 1
#define LJ_TARGET_EHRETREG 0
#define LJ_TARGET_MASKSHIFT 1
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNALIGNED 1
#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL
#elif LUAJIT_TARGET == LUAJIT_ARCH_X64
#define LJ_ARCH_NAME "x64"
#define LJ_ARCH_BITS 64
#define LJ_ARCH_ENDIAN LUAJIT_LE
#if LJ_TARGET_WINDOWS || __CYGWIN__
#define LJ_ABI_WIN 1
#else
#define LJ_ABI_WIN 0
#endif
#define LJ_TARGET_X64 1
#define LJ_TARGET_X86ORX64 1
#define LJ_TARGET_EHRETREG 0
#define LJ_TARGET_JUMPRANGE 31 /* +-2^31 = +-2GB */
#define LJ_TARGET_MASKSHIFT 1
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNALIGNED 1
#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL
#ifdef LUAJIT_ENABLE_GC64
#define LJ_TARGET_GC64 1
#endif
#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM
#define LJ_ARCH_NAME "arm"
#define LJ_ARCH_BITS 32
#define LJ_ARCH_ENDIAN LUAJIT_LE
#if !defined(LJ_ARCH_HASFPU) && __SOFTFP__
#define LJ_ARCH_HASFPU 0
#endif
#if !defined(LJ_ABI_SOFTFP) && !__ARM_PCS_VFP
#define LJ_ABI_SOFTFP 1
#endif
#define LJ_ABI_EABI 1
#define LJ_TARGET_ARM 1
#define LJ_TARGET_EHRETREG 0
#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */
#define LJ_TARGET_MASKSHIFT 0
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */
#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL
#if __ARM_ARCH____ARM_ARCH_8__ || __ARM_ARCH_8A__
#define LJ_ARCH_VERSION 80
#elif __ARM_ARCH_7__ || __ARM_ARCH_7A__ || __ARM_ARCH_7R__ || __ARM_ARCH_7S__ || __ARM_ARCH_7VE__
#define LJ_ARCH_VERSION 70
#elif __ARM_ARCH_6T2__
#define LJ_ARCH_VERSION 61
#elif __ARM_ARCH_6__ || __ARM_ARCH_6J__ || __ARM_ARCH_6K__ || __ARM_ARCH_6Z__ || __ARM_ARCH_6ZK__
#define LJ_ARCH_VERSION 60
#else
#define LJ_ARCH_VERSION 50
#endif
#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM64
#define LJ_ARCH_NAME "arm64"
#define LJ_ARCH_BITS 64
#define LJ_ARCH_ENDIAN LUAJIT_LE
#define LJ_TARGET_ARM64 1
#define LJ_TARGET_EHRETREG 0
#define LJ_TARGET_JUMPRANGE 27 /* +-2^27 = +-128MB */
#define LJ_TARGET_MASKSHIFT 1
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */
#define LJ_TARGET_GC64 1
#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL
#define LJ_ARCH_NOJIT 1 /* NYI */
#define LJ_ARCH_VERSION 80
#elif LUAJIT_TARGET == LUAJIT_ARCH_PPC
#ifndef LJ_ARCH_ENDIAN
#if __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__
#define LJ_ARCH_ENDIAN LUAJIT_LE
#else
#define LJ_ARCH_ENDIAN LUAJIT_BE
#endif
#endif
#if _LP64
#define LJ_ARCH_BITS 64
#if LJ_ARCH_ENDIAN == LUAJIT_LE
#define LJ_ARCH_NAME "ppc64le"
#else
#define LJ_ARCH_NAME "ppc64"
#endif
#else
#define LJ_ARCH_BITS 32
#define LJ_ARCH_NAME "ppc"
#endif
#define LJ_TARGET_PPC 1
#define LJ_TARGET_EHRETREG 3
#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */
#define LJ_TARGET_MASKSHIFT 0
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */
#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL_SINGLE
#if LJ_TARGET_CONSOLE
#define LJ_ARCH_PPC32ON64 1
#define LJ_ARCH_NOFFI 1
#elif LJ_ARCH_BITS == 64
#define LJ_ARCH_PPC64 1
#define LJ_TARGET_GC64 1
#define LJ_ARCH_NOJIT 1 /* NYI */
#endif
#if _ARCH_PWR7
#define LJ_ARCH_VERSION 70
#elif _ARCH_PWR6
#define LJ_ARCH_VERSION 60
#elif _ARCH_PWR5X
#define LJ_ARCH_VERSION 51
#elif _ARCH_PWR5
#define LJ_ARCH_VERSION 50
#elif _ARCH_PWR4
#define LJ_ARCH_VERSION 40
#else
#define LJ_ARCH_VERSION 0
#endif
#if _ARCH_PPCSQ
#define LJ_ARCH_SQRT 1
#endif
#if _ARCH_PWR5X
#define LJ_ARCH_ROUND 1
#endif
#if __PPU__
#define LJ_ARCH_CELL 1
#endif
#if LJ_TARGET_XBOX360
#define LJ_ARCH_XENON 1
#endif
#elif LUAJIT_TARGET == LUAJIT_ARCH_MIPS
#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL)
#define LJ_ARCH_NAME "mipsel"
#define LJ_ARCH_ENDIAN LUAJIT_LE
#else
#define LJ_ARCH_NAME "mips"
#define LJ_ARCH_ENDIAN LUAJIT_BE
#endif
#if !defined(LJ_ARCH_HASFPU)
#ifdef __mips_soft_float
#define LJ_ARCH_HASFPU 0
#else
#define LJ_ARCH_HASFPU 1
#endif
#endif
/* Temporarily disable features until the code has been merged. */
#if !defined(LUAJIT_NO_UNWIND) && __GNU_COMPACT_EH__
#define LUAJIT_NO_UNWIND 1
#endif
#if !defined(LJ_ABI_SOFTFP)
#ifdef __mips_soft_float
#define LJ_ABI_SOFTFP 1
#else
#define LJ_ABI_SOFTFP 0
#endif
#endif
#define LJ_ARCH_BITS 32
#define LJ_TARGET_MIPS 1
#define LJ_TARGET_EHRETREG 4
#define LJ_TARGET_JUMPRANGE 27 /* 2*2^27 = 256MB-aligned region */
#define LJ_TARGET_MASKSHIFT 1
#define LJ_TARGET_MASKROT 1
#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */
#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL
#if _MIPS_ARCH_MIPS32R2
#define LJ_ARCH_VERSION 20
#else
#define LJ_ARCH_VERSION 10
#endif
#else
#error "No target architecture defined"
#endif
#ifndef LJ_PAGESIZE
#define LJ_PAGESIZE 4096
#endif
/* Check for minimum required compiler versions. */
#if defined(__GNUC__)
#if LJ_TARGET_X86
#if (__GNUC__ < 3) || ((__GNUC__ == 3) && __GNUC_MINOR__ < 4)
#error "Need at least GCC 3.4 or newer"
#endif
#elif LJ_TARGET_X64
#if __GNUC__ < 4
#error "Need at least GCC 4.0 or newer"
#endif
#elif LJ_TARGET_ARM
#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 2)
#error "Need at least GCC 4.2 or newer"
#endif
#elif LJ_TARGET_ARM64
#if __clang__
#if (__clang_major__ < 3) || ((__clang_major__ == 3) && __clang_minor__ < 5)
#error "Need at least Clang 3.5 or newer"
#endif
#else
#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 8)
#error "Need at least GCC 4.8 or newer"
#endif
#endif
#elif !LJ_TARGET_PS3
#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 3)
#error "Need at least GCC 4.3 or newer"
#endif
#endif
#endif
/* Check target-specific constraints. */
#ifndef _BUILDVM_H
#if LJ_TARGET_X64
#if __USING_SJLJ_EXCEPTIONS__
#error "Need a C compiler with native exception handling on x64"
#endif
#elif LJ_TARGET_ARM
#if defined(__ARMEB__)
#error "No support for big-endian ARM"
#endif
#if __ARM_ARCH_6M__ || __ARM_ARCH_7M__ || __ARM_ARCH_7EM__
#error "No support for Cortex-M CPUs"
#endif
#if !(__ARM_EABI__ || LJ_TARGET_IOS)
#error "Only ARM EABI or iOS 3.0+ ABI is supported"
#endif
#elif LJ_TARGET_ARM64
#if defined(__AARCH64EB__)
#error "No support for big-endian ARM64"
#endif
#if defined(_ILP32)
#error "No support for ILP32 model on ARM64"
#endif
#elif LJ_TARGET_PPC
#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE)
#error "No support for PowerPC CPUs without double-precision FPU"
#endif
#if !LJ_ARCH_PPC64 && LJ_ARCH_ENDIAN == LUAJIT_LE
#error "No support for little-endian PPC32"
#endif
#if LJ_ARCH_PPC64
#error "No support for PowerPC 64 bit mode (yet)"
#endif
#ifdef __NO_FPRS__
#error "No support for PPC/e500 anymore (use LuaJIT 2.0)"
#endif
#elif LJ_TARGET_MIPS
#if defined(_LP64)
#error "No support for MIPS64"
#endif
#endif
#endif
/* Enable or disable the dual-number mode for the VM. */
#if (LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE && LUAJIT_NUMMODE == 2) || \
(LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL && LUAJIT_NUMMODE == 1)
#error "No support for this number mode on this architecture"
#endif
#if LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL || \
(LJ_ARCH_NUMMODE == LJ_NUMMODE_DUAL_SINGLE && LUAJIT_NUMMODE != 1) || \
(LJ_ARCH_NUMMODE == LJ_NUMMODE_SINGLE_DUAL && LUAJIT_NUMMODE == 2)
#define LJ_DUALNUM 1
#else
#define LJ_DUALNUM 0
#endif
#if LJ_TARGET_IOS || LJ_TARGET_CONSOLE
/* Runtime code generation is restricted on iOS. Complain to Apple, not me. */
/* Ditto for the consoles. Complain to Sony or MS, not me. */
#ifndef LUAJIT_ENABLE_JIT
#define LJ_OS_NOJIT 1
#endif
#endif
/* 64 bit GC references. */
#if LJ_TARGET_GC64
#define LJ_GC64 1
#else
#define LJ_GC64 0
#endif
/* 2-slot frame info. */
#if LJ_GC64
#define LJ_FR2 1
#else
#define LJ_FR2 0
#endif
/* Disable or enable the JIT compiler. */
#if defined(LUAJIT_DISABLE_JIT) || defined(LJ_ARCH_NOJIT) || defined(LJ_OS_NOJIT) || LJ_FR2 || LJ_GC64
#define LJ_HASJIT 0
#else
#define LJ_HASJIT 1
#endif
/* Disable or enable the FFI extension. */
#if defined(LUAJIT_DISABLE_FFI) || defined(LJ_ARCH_NOFFI)
#define LJ_HASFFI 0
#else
#define LJ_HASFFI 1
#endif
#if defined(LUAJIT_DISABLE_PROFILE)
#define LJ_HASPROFILE 0
#elif LJ_TARGET_POSIX
#define LJ_HASPROFILE 1
#define LJ_PROFILE_SIGPROF 1
#elif LJ_TARGET_PS3
#define LJ_HASPROFILE 1
#define LJ_PROFILE_PTHREAD 1
#elif LJ_TARGET_WINDOWS || LJ_TARGET_XBOX360
#define LJ_HASPROFILE 1
#define LJ_PROFILE_WTHREAD 1
#else
#define LJ_HASPROFILE 0
#endif
#ifndef LJ_ARCH_HASFPU
#define LJ_ARCH_HASFPU 1
#endif
#ifndef LJ_ABI_SOFTFP
#define LJ_ABI_SOFTFP 0
#endif
#define LJ_SOFTFP (!LJ_ARCH_HASFPU)
#if LJ_ARCH_ENDIAN == LUAJIT_BE
#define LJ_LE 0
#define LJ_BE 1
#define LJ_ENDIAN_SELECT(le, be) be
#define LJ_ENDIAN_LOHI(lo, hi) hi lo
#else
#define LJ_LE 1
#define LJ_BE 0
#define LJ_ENDIAN_SELECT(le, be) le
#define LJ_ENDIAN_LOHI(lo, hi) lo hi
#endif
#if LJ_ARCH_BITS == 32
#define LJ_32 1
#define LJ_64 0
#else
#define LJ_32 0
#define LJ_64 1
#endif
#ifndef LJ_TARGET_UNALIGNED
#define LJ_TARGET_UNALIGNED 0
#endif
/* Various workarounds for embedded operating systems or weak C runtimes. */
#if defined(__ANDROID__) || defined(__symbian__) || LJ_TARGET_XBOX360 || LJ_TARGET_WINDOWS
#define LUAJIT_NO_LOG2
#endif
#if defined(__symbian__) || LJ_TARGET_WINDOWS
#define LUAJIT_NO_EXP2
#endif
#if LJ_TARGET_CONSOLE || (LJ_TARGET_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)
#define LJ_NO_SYSTEM 1
#endif
#if defined(LUAJIT_NO_UNWIND) || defined(__symbian__) || LJ_TARGET_IOS || LJ_TARGET_PS3 || LJ_TARGET_PS4
#define LJ_NO_UNWIND 1
#endif
/* Compatibility with Lua 5.1 vs. 5.2. */
#ifdef LUAJIT_ENABLE_LUA52COMPAT
#define LJ_52 1
#else
#define LJ_52 0
#endif
#endif
| xLua/build/luajit-2.1.0b2/src/lj_arch.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_arch.h",
"repo_id": "xLua",
"token_count": 6527
} | 2,108 |
/*
** FFI C call handling.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#include "lj_obj.h"
#if LJ_HASFFI
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_tab.h"
#include "lj_ctype.h"
#include "lj_cconv.h"
#include "lj_cdata.h"
#include "lj_ccall.h"
#include "lj_trace.h"
/* Target-specific handling of register arguments. */
#if LJ_TARGET_X86
/* -- x86 calling conventions --------------------------------------------- */
#if LJ_ABI_WIN
#define CCALL_HANDLE_STRUCTRET \
/* Return structs bigger than 8 by reference (on stack only). */ \
cc->retref = (sz > 8); \
if (cc->retref) cc->stack[nsp++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET CCALL_HANDLE_STRUCTRET
#else
#if LJ_TARGET_OSX
#define CCALL_HANDLE_STRUCTRET \
/* Return structs of size 1, 2, 4 or 8 in registers. */ \
cc->retref = !(sz == 1 || sz == 2 || sz == 4 || sz == 8); \
if (cc->retref) { \
if (ngpr < maxgpr) \
cc->gpr[ngpr++] = (GPRArg)dp; \
else \
cc->stack[nsp++] = (GPRArg)dp; \
} else { /* Struct with single FP field ends up in FPR. */ \
cc->resx87 = ccall_classify_struct(cts, ctr); \
}
#define CCALL_HANDLE_STRUCTRET2 \
if (cc->resx87) sp = (uint8_t *)&cc->fpr[0]; \
memcpy(dp, sp, ctr->size);
#else
#define CCALL_HANDLE_STRUCTRET \
cc->retref = 1; /* Return all structs by reference (in reg or on stack). */ \
if (ngpr < maxgpr) \
cc->gpr[ngpr++] = (GPRArg)dp; \
else \
cc->stack[nsp++] = (GPRArg)dp;
#endif
#define CCALL_HANDLE_COMPLEXRET \
/* Return complex float in GPRs and complex double by reference. */ \
cc->retref = (sz > 8); \
if (cc->retref) { \
if (ngpr < maxgpr) \
cc->gpr[ngpr++] = (GPRArg)dp; \
else \
cc->stack[nsp++] = (GPRArg)dp; \
}
#endif
#define CCALL_HANDLE_COMPLEXRET2 \
if (!cc->retref) \
*(int64_t *)dp = *(int64_t *)sp; /* Copy complex float from GPRs. */
#define CCALL_HANDLE_STRUCTARG \
ngpr = maxgpr; /* Pass all structs by value on the stack. */
#define CCALL_HANDLE_COMPLEXARG \
isfp = 1; /* Pass complex by value on stack. */
#define CCALL_HANDLE_REGARG \
if (!isfp) { /* Only non-FP values may be passed in registers. */ \
if (n > 1) { /* Anything > 32 bit is passed on the stack. */ \
if (!LJ_ABI_WIN) ngpr = maxgpr; /* Prevent reordering. */ \
} else if (ngpr + 1 <= maxgpr) { \
dp = &cc->gpr[ngpr]; \
ngpr += n; \
goto done; \
} \
}
#elif LJ_TARGET_X64 && LJ_ABI_WIN
/* -- Windows/x64 calling conventions ------------------------------------- */
#define CCALL_HANDLE_STRUCTRET \
/* Return structs of size 1, 2, 4 or 8 in a GPR. */ \
cc->retref = !(sz == 1 || sz == 2 || sz == 4 || sz == 8); \
if (cc->retref) cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET CCALL_HANDLE_STRUCTRET
#define CCALL_HANDLE_COMPLEXRET2 \
if (!cc->retref) \
*(int64_t *)dp = *(int64_t *)sp; /* Copy complex float from GPRs. */
#define CCALL_HANDLE_STRUCTARG \
/* Pass structs of size 1, 2, 4 or 8 in a GPR by value. */ \
if (!(sz == 1 || sz == 2 || sz == 4 || sz == 8)) { \
rp = cdataptr(lj_cdata_new(cts, did, sz)); \
sz = CTSIZE_PTR; /* Pass all other structs by reference. */ \
}
#define CCALL_HANDLE_COMPLEXARG \
/* Pass complex float in a GPR and complex double by reference. */ \
if (sz != 2*sizeof(float)) { \
rp = cdataptr(lj_cdata_new(cts, did, sz)); \
sz = CTSIZE_PTR; \
}
/* Windows/x64 argument registers are strictly positional (use ngpr). */
#define CCALL_HANDLE_REGARG \
if (isfp) { \
if (ngpr < maxgpr) { dp = &cc->fpr[ngpr++]; nfpr = ngpr; goto done; } \
} else { \
if (ngpr < maxgpr) { dp = &cc->gpr[ngpr++]; goto done; } \
}
#elif LJ_TARGET_X64
/* -- POSIX/x64 calling conventions --------------------------------------- */
#define CCALL_HANDLE_STRUCTRET \
int rcl[2]; rcl[0] = rcl[1] = 0; \
if (ccall_classify_struct(cts, ctr, rcl, 0)) { \
cc->retref = 1; /* Return struct by reference. */ \
cc->gpr[ngpr++] = (GPRArg)dp; \
} else { \
cc->retref = 0; /* Return small structs in registers. */ \
}
#define CCALL_HANDLE_STRUCTRET2 \
int rcl[2]; rcl[0] = rcl[1] = 0; \
ccall_classify_struct(cts, ctr, rcl, 0); \
ccall_struct_ret(cc, rcl, dp, ctr->size);
#define CCALL_HANDLE_COMPLEXRET \
/* Complex values are returned in one or two FPRs. */ \
cc->retref = 0;
#define CCALL_HANDLE_COMPLEXRET2 \
if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPR. */ \
*(int64_t *)dp = cc->fpr[0].l[0]; \
} else { /* Copy non-contiguous complex double from FPRs. */ \
((int64_t *)dp)[0] = cc->fpr[0].l[0]; \
((int64_t *)dp)[1] = cc->fpr[1].l[0]; \
}
#define CCALL_HANDLE_STRUCTARG \
int rcl[2]; rcl[0] = rcl[1] = 0; \
if (!ccall_classify_struct(cts, d, rcl, 0)) { \
cc->nsp = nsp; cc->ngpr = ngpr; cc->nfpr = nfpr; \
if (ccall_struct_arg(cc, cts, d, rcl, o, narg)) goto err_nyi; \
nsp = cc->nsp; ngpr = cc->ngpr; nfpr = cc->nfpr; \
continue; \
} /* Pass all other structs by value on stack. */
#define CCALL_HANDLE_COMPLEXARG \
isfp = 2; /* Pass complex in FPRs or on stack. Needs postprocessing. */
#define CCALL_HANDLE_REGARG \
if (isfp) { /* Try to pass argument in FPRs. */ \
int n2 = ctype_isvector(d->info) ? 1 : n; \
if (nfpr + n2 <= CCALL_NARG_FPR) { \
dp = &cc->fpr[nfpr]; \
nfpr += n2; \
goto done; \
} \
} else { /* Try to pass argument in GPRs. */ \
/* Note that reordering is explicitly allowed in the x64 ABI. */ \
if (n <= 2 && ngpr + n <= maxgpr) { \
dp = &cc->gpr[ngpr]; \
ngpr += n; \
goto done; \
} \
}
#elif LJ_TARGET_ARM
/* -- ARM calling conventions --------------------------------------------- */
#if LJ_ABI_SOFTFP
#define CCALL_HANDLE_STRUCTRET \
/* Return structs of size <= 4 in a GPR. */ \
cc->retref = !(sz <= 4); \
if (cc->retref) cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET \
cc->retref = 1; /* Return all complex values by reference. */ \
cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET2 \
UNUSED(dp); /* Nothing to do. */
#define CCALL_HANDLE_STRUCTARG \
/* Pass all structs by value in registers and/or on the stack. */
#define CCALL_HANDLE_COMPLEXARG \
/* Pass complex by value in 2 or 4 GPRs. */
#define CCALL_HANDLE_REGARG_FP1
#define CCALL_HANDLE_REGARG_FP2
#else
#define CCALL_HANDLE_STRUCTRET \
cc->retref = !ccall_classify_struct(cts, ctr, ct); \
if (cc->retref) cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_STRUCTRET2 \
if (ccall_classify_struct(cts, ctr, ct) > 1) sp = (uint8_t *)&cc->fpr[0]; \
memcpy(dp, sp, ctr->size);
#define CCALL_HANDLE_COMPLEXRET \
if (!(ct->info & CTF_VARARG)) cc->retref = 0; /* Return complex in FPRs. */
#define CCALL_HANDLE_COMPLEXRET2 \
if (!(ct->info & CTF_VARARG)) memcpy(dp, &cc->fpr[0], ctr->size);
#define CCALL_HANDLE_STRUCTARG \
isfp = (ccall_classify_struct(cts, d, ct) > 1);
/* Pass all structs by value in registers and/or on the stack. */
#define CCALL_HANDLE_COMPLEXARG \
isfp = 1; /* Pass complex by value in FPRs or on stack. */
#define CCALL_HANDLE_REGARG_FP1 \
if (isfp && !(ct->info & CTF_VARARG)) { \
if ((d->info & CTF_ALIGN) > CTALIGN_PTR) { \
if (nfpr + (n >> 1) <= CCALL_NARG_FPR) { \
dp = &cc->fpr[nfpr]; \
nfpr += (n >> 1); \
goto done; \
} \
} else { \
if (sz > 1 && fprodd != nfpr) fprodd = 0; \
if (fprodd) { \
if (2*nfpr+n <= 2*CCALL_NARG_FPR+1) { \
dp = (void *)&cc->fpr[fprodd-1].f[1]; \
nfpr += (n >> 1); \
if ((n & 1)) fprodd = 0; else fprodd = nfpr-1; \
goto done; \
} \
} else { \
if (2*nfpr+n <= 2*CCALL_NARG_FPR) { \
dp = (void *)&cc->fpr[nfpr]; \
nfpr += (n >> 1); \
if ((n & 1)) fprodd = ++nfpr; else fprodd = 0; \
goto done; \
} \
} \
} \
fprodd = 0; /* No reordering after the first FP value is on stack. */ \
} else {
#define CCALL_HANDLE_REGARG_FP2 }
#endif
#define CCALL_HANDLE_REGARG \
CCALL_HANDLE_REGARG_FP1 \
if ((d->info & CTF_ALIGN) > CTALIGN_PTR) { \
if (ngpr < maxgpr) \
ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
} \
if (ngpr < maxgpr) { \
dp = &cc->gpr[ngpr]; \
if (ngpr + n > maxgpr) { \
nsp += ngpr + n - maxgpr; /* Assumes contiguous gpr/stack fields. */ \
if (nsp > CCALL_MAXSTACK) goto err_nyi; /* Too many arguments. */ \
ngpr = maxgpr; \
} else { \
ngpr += n; \
} \
goto done; \
} CCALL_HANDLE_REGARG_FP2
#define CCALL_HANDLE_RET \
if ((ct->info & CTF_VARARG)) sp = (uint8_t *)&cc->gpr[0];
#elif LJ_TARGET_ARM64
/* -- ARM64 calling conventions ------------------------------------------- */
#define CCALL_HANDLE_STRUCTRET \
cc->retref = !ccall_classify_struct(cts, ctr); \
if (cc->retref) cc->retp = dp;
#define CCALL_HANDLE_STRUCTRET2 \
unsigned int cl = ccall_classify_struct(cts, ctr); \
if ((cl & 4)) { /* Combine float HFA from separate registers. */ \
CTSize i = (cl >> 8) - 1; \
do { ((uint32_t *)dp)[i] = cc->fpr[i].u32; } while (i--); \
} else { \
if (cl > 1) sp = (uint8_t *)&cc->fpr[0]; \
memcpy(dp, sp, ctr->size); \
}
#define CCALL_HANDLE_COMPLEXRET \
/* Complex values are returned in one or two FPRs. */ \
cc->retref = 0;
#define CCALL_HANDLE_COMPLEXRET2 \
if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \
((float *)dp)[0] = cc->fpr[0].f; \
((float *)dp)[1] = cc->fpr[1].f; \
} else { /* Copy complex double from FPRs. */ \
((double *)dp)[0] = cc->fpr[0].d; \
((double *)dp)[1] = cc->fpr[1].d; \
}
#define CCALL_HANDLE_STRUCTARG \
unsigned int cl = ccall_classify_struct(cts, d); \
if (cl == 0) { /* Pass struct by reference. */ \
rp = cdataptr(lj_cdata_new(cts, did, sz)); \
sz = CTSIZE_PTR; \
} else if (cl > 1) { /* Pass struct in FPRs or on stack. */ \
isfp = (cl & 4) ? 2 : 1; \
} /* else: Pass struct in GPRs or on stack. */
#define CCALL_HANDLE_COMPLEXARG \
/* Pass complex by value in separate (!) FPRs or on stack. */ \
isfp = ctr->size == 2*sizeof(float) ? 2 : 1;
#define CCALL_HANDLE_REGARG \
if (LJ_TARGET_IOS && isva) { \
/* IOS: All variadic arguments are on the stack. */ \
} else if (isfp) { /* Try to pass argument in FPRs. */ \
int n2 = ctype_isvector(d->info) ? 1 : n*isfp; \
if (nfpr + n2 <= CCALL_NARG_FPR) { \
dp = &cc->fpr[nfpr]; \
nfpr += n2; \
goto done; \
} else { \
nfpr = CCALL_NARG_FPR; /* Prevent reordering. */ \
if (LJ_TARGET_IOS && d->size < 8) goto err_nyi; \
} \
} else { /* Try to pass argument in GPRs. */ \
if (!LJ_TARGET_IOS && (d->info & CTF_ALIGN) > CTALIGN_PTR) \
ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
if (ngpr + n <= maxgpr) { \
dp = &cc->gpr[ngpr]; \
ngpr += n; \
goto done; \
} else { \
ngpr = maxgpr; /* Prevent reordering. */ \
if (LJ_TARGET_IOS && d->size < 8) goto err_nyi; \
} \
}
#elif LJ_TARGET_PPC
/* -- PPC calling conventions --------------------------------------------- */
#define CCALL_HANDLE_STRUCTRET \
cc->retref = 1; /* Return all structs by reference. */ \
cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET \
/* Complex values are returned in 2 or 4 GPRs. */ \
cc->retref = 0;
#define CCALL_HANDLE_COMPLEXRET2 \
memcpy(dp, sp, ctr->size); /* Copy complex from GPRs. */
#define CCALL_HANDLE_STRUCTARG \
rp = cdataptr(lj_cdata_new(cts, did, sz)); \
sz = CTSIZE_PTR; /* Pass all structs by reference. */
#define CCALL_HANDLE_COMPLEXARG \
/* Pass complex by value in 2 or 4 GPRs. */
#define CCALL_HANDLE_REGARG \
if (isfp) { /* Try to pass argument in FPRs. */ \
if (nfpr + 1 <= CCALL_NARG_FPR) { \
dp = &cc->fpr[nfpr]; \
nfpr += 1; \
d = ctype_get(cts, CTID_DOUBLE); /* FPRs always hold doubles. */ \
goto done; \
} \
} else { /* Try to pass argument in GPRs. */ \
if (n > 1) { \
lua_assert(n == 2 || n == 4); /* int64_t or complex (float). */ \
if (ctype_isinteger(d->info)) \
ngpr = (ngpr + 1u) & ~1u; /* Align int64_t to regpair. */ \
else if (ngpr + n > maxgpr) \
ngpr = maxgpr; /* Prevent reordering. */ \
} \
if (ngpr + n <= maxgpr) { \
dp = &cc->gpr[ngpr]; \
ngpr += n; \
goto done; \
} \
}
#define CCALL_HANDLE_RET \
if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
ctr = ctype_get(cts, CTID_DOUBLE); /* FPRs always hold doubles. */
#elif LJ_TARGET_MIPS
/* -- MIPS calling conventions -------------------------------------------- */
#define CCALL_HANDLE_STRUCTRET \
cc->retref = 1; /* Return all structs by reference. */ \
cc->gpr[ngpr++] = (GPRArg)dp;
#define CCALL_HANDLE_COMPLEXRET \
/* Complex values are returned in 1 or 2 FPRs. */ \
cc->retref = 0;
#if LJ_ABI_SOFTFP
#define CCALL_HANDLE_COMPLEXRET2 \
if (ctr->size == 2*sizeof(float)) { /* Copy complex float from GPRs. */ \
((intptr_t *)dp)[0] = cc->gpr[0]; \
((intptr_t *)dp)[1] = cc->gpr[1]; \
} else { /* Copy complex double from GPRs. */ \
((intptr_t *)dp)[0] = cc->gpr[0]; \
((intptr_t *)dp)[1] = cc->gpr[1]; \
((intptr_t *)dp)[2] = cc->gpr[2]; \
((intptr_t *)dp)[3] = cc->gpr[3]; \
}
#else
#define CCALL_HANDLE_COMPLEXRET2 \
if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \
((float *)dp)[0] = cc->fpr[0].f; \
((float *)dp)[1] = cc->fpr[1].f; \
} else { /* Copy complex double from FPRs. */ \
((double *)dp)[0] = cc->fpr[0].d; \
((double *)dp)[1] = cc->fpr[1].d; \
}
#endif
#define CCALL_HANDLE_STRUCTARG \
/* Pass all structs by value in registers and/or on the stack. */
#define CCALL_HANDLE_COMPLEXARG \
/* Pass complex by value in 2 or 4 GPRs. */
#define CCALL_HANDLE_GPR \
if ((d->info & CTF_ALIGN) > CTALIGN_PTR) \
ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
if (ngpr < maxgpr) { \
dp = &cc->gpr[ngpr]; \
if (ngpr + n > maxgpr) { \
nsp += ngpr + n - maxgpr; /* Assumes contiguous gpr/stack fields. */ \
if (nsp > CCALL_MAXSTACK) goto err_nyi; /* Too many arguments. */ \
ngpr = maxgpr; \
} else { \
ngpr += n; \
} \
goto done; \
}
#if !LJ_ABI_SOFTFP /* MIPS32 hard-float */
#define CCALL_HANDLE_REGARG \
if (isfp && nfpr < CCALL_NARG_FPR && !(ct->info & CTF_VARARG)) { \
/* Try to pass argument in FPRs. */ \
dp = n == 1 ? (void *)&cc->fpr[nfpr].f : (void *)&cc->fpr[nfpr].d; \
nfpr++; ngpr += n; \
goto done; \
} else { /* Try to pass argument in GPRs. */ \
nfpr = CCALL_NARG_FPR; \
CCALL_HANDLE_GPR \
}
#else /* MIPS32 soft-float */
#define CCALL_HANDLE_REGARG CCALL_HANDLE_GPR
#endif
#if !LJ_ABI_SOFTFP
/* On MIPS64 soft-float, position of float return values is endian-dependant. */
#define CCALL_HANDLE_RET \
if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
sp = (uint8_t *)&cc->fpr[0].f;
#endif
#else
#error "Missing calling convention definitions for this architecture"
#endif
#ifndef CCALL_HANDLE_STRUCTRET2
#define CCALL_HANDLE_STRUCTRET2 \
memcpy(dp, sp, ctr->size); /* Copy struct return value from GPRs. */
#endif
/* -- x86 OSX ABI struct classification ----------------------------------- */
#if LJ_TARGET_X86 && LJ_TARGET_OSX
/* Check for struct with single FP field. */
static int ccall_classify_struct(CTState *cts, CType *ct)
{
CTSize sz = ct->size;
if (!(sz == sizeof(float) || sz == sizeof(double))) return 0;
if ((ct->info & CTF_UNION)) return 0;
while (ct->sib) {
ct = ctype_get(cts, ct->sib);
if (ctype_isfield(ct->info)) {
CType *sct = ctype_rawchild(cts, ct);
if (ctype_isfp(sct->info)) {
if (sct->size == sz)
return (sz >> 2); /* Return 1 for float or 2 for double. */
} else if (ctype_isstruct(sct->info)) {
if (sct->size)
return ccall_classify_struct(cts, sct);
} else {
break;
}
} else if (ctype_isbitfield(ct->info)) {
break;
} else if (ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
CType *sct = ctype_rawchild(cts, ct);
if (sct->size)
return ccall_classify_struct(cts, sct);
}
}
return 0;
}
#endif
/* -- x64 struct classification ------------------------------------------- */
#if LJ_TARGET_X64 && !LJ_ABI_WIN
/* Register classes for x64 struct classification. */
#define CCALL_RCL_INT 1
#define CCALL_RCL_SSE 2
#define CCALL_RCL_MEM 4
/* NYI: classify vectors. */
static int ccall_classify_struct(CTState *cts, CType *ct, int *rcl, CTSize ofs);
/* Classify a C type. */
static void ccall_classify_ct(CTState *cts, CType *ct, int *rcl, CTSize ofs)
{
if (ctype_isarray(ct->info)) {
CType *cct = ctype_rawchild(cts, ct);
CTSize eofs, esz = cct->size, asz = ct->size;
for (eofs = 0; eofs < asz; eofs += esz)
ccall_classify_ct(cts, cct, rcl, ofs+eofs);
} else if (ctype_isstruct(ct->info)) {
ccall_classify_struct(cts, ct, rcl, ofs);
} else {
int cl = ctype_isfp(ct->info) ? CCALL_RCL_SSE : CCALL_RCL_INT;
lua_assert(ctype_hassize(ct->info));
if ((ofs & (ct->size-1))) cl = CCALL_RCL_MEM; /* Unaligned. */
rcl[(ofs >= 8)] |= cl;
}
}
/* Recursively classify a struct based on its fields. */
static int ccall_classify_struct(CTState *cts, CType *ct, int *rcl, CTSize ofs)
{
if (ct->size > 16) return CCALL_RCL_MEM; /* Too big, gets memory class. */
while (ct->sib) {
CTSize fofs;
ct = ctype_get(cts, ct->sib);
fofs = ofs+ct->size;
if (ctype_isfield(ct->info))
ccall_classify_ct(cts, ctype_rawchild(cts, ct), rcl, fofs);
else if (ctype_isbitfield(ct->info))
rcl[(fofs >= 8)] |= CCALL_RCL_INT; /* NYI: unaligned bitfields? */
else if (ctype_isxattrib(ct->info, CTA_SUBTYPE))
ccall_classify_struct(cts, ctype_rawchild(cts, ct), rcl, fofs);
}
return ((rcl[0]|rcl[1]) & CCALL_RCL_MEM); /* Memory class? */
}
/* Try to split up a small struct into registers. */
static int ccall_struct_reg(CCallState *cc, GPRArg *dp, int *rcl)
{
MSize ngpr = cc->ngpr, nfpr = cc->nfpr;
uint32_t i;
for (i = 0; i < 2; i++) {
lua_assert(!(rcl[i] & CCALL_RCL_MEM));
if ((rcl[i] & CCALL_RCL_INT)) { /* Integer class takes precedence. */
if (ngpr >= CCALL_NARG_GPR) return 1; /* Register overflow. */
cc->gpr[ngpr++] = dp[i];
} else if ((rcl[i] & CCALL_RCL_SSE)) {
if (nfpr >= CCALL_NARG_FPR) return 1; /* Register overflow. */
cc->fpr[nfpr++].l[0] = dp[i];
}
}
cc->ngpr = ngpr; cc->nfpr = nfpr;
return 0; /* Ok. */
}
/* Pass a small struct argument. */
static int ccall_struct_arg(CCallState *cc, CTState *cts, CType *d, int *rcl,
TValue *o, int narg)
{
GPRArg dp[2];
dp[0] = dp[1] = 0;
/* Convert to temp. struct. */
lj_cconv_ct_tv(cts, d, (uint8_t *)dp, o, CCF_ARG(narg));
if (ccall_struct_reg(cc, dp, rcl)) { /* Register overflow? Pass on stack. */
MSize nsp = cc->nsp, n = rcl[1] ? 2 : 1;
if (nsp + n > CCALL_MAXSTACK) return 1; /* Too many arguments. */
cc->nsp = nsp + n;
memcpy(&cc->stack[nsp], dp, n*CTSIZE_PTR);
}
return 0; /* Ok. */
}
/* Combine returned small struct. */
static void ccall_struct_ret(CCallState *cc, int *rcl, uint8_t *dp, CTSize sz)
{
GPRArg sp[2];
MSize ngpr = 0, nfpr = 0;
uint32_t i;
for (i = 0; i < 2; i++) {
if ((rcl[i] & CCALL_RCL_INT)) { /* Integer class takes precedence. */
sp[i] = cc->gpr[ngpr++];
} else if ((rcl[i] & CCALL_RCL_SSE)) {
sp[i] = cc->fpr[nfpr++].l[0];
}
}
memcpy(dp, sp, sz);
}
#endif
/* -- ARM hard-float ABI struct classification ---------------------------- */
#if LJ_TARGET_ARM && !LJ_ABI_SOFTFP
/* Classify a struct based on its fields. */
static unsigned int ccall_classify_struct(CTState *cts, CType *ct, CType *ctf)
{
CTSize sz = ct->size;
unsigned int r = 0, n = 0, isu = (ct->info & CTF_UNION);
if ((ctf->info & CTF_VARARG)) goto noth;
while (ct->sib) {
CType *sct;
ct = ctype_get(cts, ct->sib);
if (ctype_isfield(ct->info)) {
sct = ctype_rawchild(cts, ct);
if (ctype_isfp(sct->info)) {
r |= sct->size;
if (!isu) n++; else if (n == 0) n = 1;
} else if (ctype_iscomplex(sct->info)) {
r |= (sct->size >> 1);
if (!isu) n += 2; else if (n < 2) n = 2;
} else if (ctype_isstruct(sct->info)) {
goto substruct;
} else {
goto noth;
}
} else if (ctype_isbitfield(ct->info)) {
goto noth;
} else if (ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
sct = ctype_rawchild(cts, ct);
substruct:
if (sct->size > 0) {
unsigned int s = ccall_classify_struct(cts, sct, ctf);
if (s <= 1) goto noth;
r |= (s & 255);
if (!isu) n += (s >> 8); else if (n < (s >>8)) n = (s >> 8);
}
}
}
if ((r == 4 || r == 8) && n <= 4)
return r + (n << 8);
noth: /* Not a homogeneous float/double aggregate. */
return (sz <= 4); /* Return structs of size <= 4 in a GPR. */
}
#endif
/* -- ARM64 ABI struct classification ------------------------------------- */
#if LJ_TARGET_ARM64
/* Classify a struct based on its fields. */
static unsigned int ccall_classify_struct(CTState *cts, CType *ct)
{
CTSize sz = ct->size;
unsigned int r = 0, n = 0, isu = (ct->info & CTF_UNION);
while (ct->sib) {
CType *sct;
ct = ctype_get(cts, ct->sib);
if (ctype_isfield(ct->info)) {
sct = ctype_rawchild(cts, ct);
if (ctype_isfp(sct->info)) {
r |= sct->size;
if (!isu) n++; else if (n == 0) n = 1;
} else if (ctype_iscomplex(sct->info)) {
r |= (sct->size >> 1);
if (!isu) n += 2; else if (n < 2) n = 2;
} else if (ctype_isstruct(sct->info)) {
goto substruct;
} else {
goto noth;
}
} else if (ctype_isbitfield(ct->info)) {
goto noth;
} else if (ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
sct = ctype_rawchild(cts, ct);
substruct:
if (sct->size > 0) {
unsigned int s = ccall_classify_struct(cts, sct);
if (s <= 1) goto noth;
r |= (s & 255);
if (!isu) n += (s >> 8); else if (n < (s >>8)) n = (s >> 8);
}
}
}
if ((r == 4 || r == 8) && n <= 4)
return r + (n << 8);
noth: /* Not a homogeneous float/double aggregate. */
return (sz <= 16); /* Return structs of size <= 16 in GPRs. */
}
#endif
/* -- Common C call handling ---------------------------------------------- */
/* Infer the destination CTypeID for a vararg argument. */
CTypeID lj_ccall_ctid_vararg(CTState *cts, cTValue *o)
{
if (tvisnumber(o)) {
return CTID_DOUBLE;
} else if (tviscdata(o)) {
CTypeID id = cdataV(o)->ctypeid;
CType *s = ctype_get(cts, id);
if (ctype_isrefarray(s->info)) {
return lj_ctype_intern(cts,
CTINFO(CT_PTR, CTALIGN_PTR|ctype_cid(s->info)), CTSIZE_PTR);
} else if (ctype_isstruct(s->info) || ctype_isfunc(s->info)) {
/* NYI: how to pass a struct by value in a vararg argument? */
return lj_ctype_intern(cts, CTINFO(CT_PTR, CTALIGN_PTR|id), CTSIZE_PTR);
} else if (ctype_isfp(s->info) && s->size == sizeof(float)) {
return CTID_DOUBLE;
} else {
return id;
}
} else if (tvisstr(o)) {
return CTID_P_CCHAR;
} else if (tvisbool(o)) {
return CTID_BOOL;
} else {
return CTID_P_VOID;
}
}
/* Setup arguments for C call. */
static int ccall_set_args(lua_State *L, CTState *cts, CType *ct,
CCallState *cc)
{
int gcsteps = 0;
TValue *o, *top = L->top;
CTypeID fid;
CType *ctr;
MSize maxgpr, ngpr = 0, nsp = 0, narg;
#if CCALL_NARG_FPR
MSize nfpr = 0;
#if LJ_TARGET_ARM
MSize fprodd = 0;
#endif
#endif
/* Clear unused regs to get some determinism in case of misdeclaration. */
memset(cc->gpr, 0, sizeof(cc->gpr));
#if CCALL_NUM_FPR
memset(cc->fpr, 0, sizeof(cc->fpr));
#endif
#if LJ_TARGET_X86
/* x86 has several different calling conventions. */
cc->resx87 = 0;
switch (ctype_cconv(ct->info)) {
case CTCC_FASTCALL: maxgpr = 2; break;
case CTCC_THISCALL: maxgpr = 1; break;
default: maxgpr = 0; break;
}
#else
maxgpr = CCALL_NARG_GPR;
#endif
/* Perform required setup for some result types. */
ctr = ctype_rawchild(cts, ct);
if (ctype_isvector(ctr->info)) {
if (!(CCALL_VECTOR_REG && (ctr->size == 8 || ctr->size == 16)))
goto err_nyi;
} else if (ctype_iscomplex(ctr->info) || ctype_isstruct(ctr->info)) {
/* Preallocate cdata object and anchor it after arguments. */
CTSize sz = ctr->size;
GCcdata *cd = lj_cdata_new(cts, ctype_cid(ct->info), sz);
void *dp = cdataptr(cd);
setcdataV(L, L->top++, cd);
if (ctype_isstruct(ctr->info)) {
CCALL_HANDLE_STRUCTRET
} else {
CCALL_HANDLE_COMPLEXRET
}
#if LJ_TARGET_X86
} else if (ctype_isfp(ctr->info)) {
cc->resx87 = ctr->size == sizeof(float) ? 1 : 2;
#endif
}
/* Skip initial attributes. */
fid = ct->sib;
while (fid) {
CType *ctf = ctype_get(cts, fid);
if (!ctype_isattrib(ctf->info)) break;
fid = ctf->sib;
}
/* Walk through all passed arguments. */
for (o = L->base+1, narg = 1; o < top; o++, narg++) {
CTypeID did;
CType *d;
CTSize sz;
MSize n, isfp = 0, isva = 0;
void *dp, *rp = NULL;
if (fid) { /* Get argument type from field. */
CType *ctf = ctype_get(cts, fid);
fid = ctf->sib;
lua_assert(ctype_isfield(ctf->info));
did = ctype_cid(ctf->info);
} else {
if (!(ct->info & CTF_VARARG))
lj_err_caller(L, LJ_ERR_FFI_NUMARG); /* Too many arguments. */
did = lj_ccall_ctid_vararg(cts, o); /* Infer vararg type. */
isva = 1;
}
d = ctype_raw(cts, did);
sz = d->size;
/* Find out how (by value/ref) and where (GPR/FPR) to pass an argument. */
if (ctype_isnum(d->info)) {
if (sz > 8) goto err_nyi;
if ((d->info & CTF_FP))
isfp = 1;
} else if (ctype_isvector(d->info)) {
if (CCALL_VECTOR_REG && (sz == 8 || sz == 16))
isfp = 1;
else
goto err_nyi;
} else if (ctype_isstruct(d->info)) {
CCALL_HANDLE_STRUCTARG
} else if (ctype_iscomplex(d->info)) {
CCALL_HANDLE_COMPLEXARG
} else {
sz = CTSIZE_PTR;
}
sz = (sz + CTSIZE_PTR-1) & ~(CTSIZE_PTR-1);
n = sz / CTSIZE_PTR; /* Number of GPRs or stack slots needed. */
CCALL_HANDLE_REGARG /* Handle register arguments. */
/* Otherwise pass argument on stack. */
if (CCALL_ALIGN_STACKARG && !rp && (d->info & CTF_ALIGN) > CTALIGN_PTR) {
MSize align = (1u << ctype_align(d->info-CTALIGN_PTR)) -1;
nsp = (nsp + align) & ~align; /* Align argument on stack. */
}
if (nsp + n > CCALL_MAXSTACK) { /* Too many arguments. */
err_nyi:
lj_err_caller(L, LJ_ERR_FFI_NYICALL);
}
dp = &cc->stack[nsp];
nsp += n;
isva = 0;
done:
if (rp) { /* Pass by reference. */
gcsteps++;
*(void **)dp = rp;
dp = rp;
}
lj_cconv_ct_tv(cts, d, (uint8_t *)dp, o, CCF_ARG(narg));
/* Extend passed integers to 32 bits at least. */
if (ctype_isinteger_or_bool(d->info) && d->size < 4) {
if (d->info & CTF_UNSIGNED)
*(uint32_t *)dp = d->size == 1 ? (uint32_t)*(uint8_t *)dp :
(uint32_t)*(uint16_t *)dp;
else
*(int32_t *)dp = d->size == 1 ? (int32_t)*(int8_t *)dp :
(int32_t)*(int16_t *)dp;
}
#if LJ_TARGET_X64 && LJ_ABI_WIN
if (isva) { /* Windows/x64 mirrors varargs in both register sets. */
if (nfpr == ngpr)
cc->gpr[ngpr-1] = cc->fpr[ngpr-1].l[0];
else
cc->fpr[ngpr-1].l[0] = cc->gpr[ngpr-1];
}
#else
UNUSED(isva);
#endif
#if LJ_TARGET_X64 && !LJ_ABI_WIN
if (isfp == 2 && n == 2 && (uint8_t *)dp == (uint8_t *)&cc->fpr[nfpr-2]) {
cc->fpr[nfpr-1].d[0] = cc->fpr[nfpr-2].d[1]; /* Split complex double. */
cc->fpr[nfpr-2].d[1] = 0;
}
#elif LJ_TARGET_ARM64
if (isfp == 2 && (uint8_t *)dp < (uint8_t *)cc->stack) {
/* Split float HFA or complex float into separate registers. */
CTSize i = (sz >> 2) - 1;
do { ((uint64_t *)dp)[i] = ((uint32_t *)dp)[i]; } while (i--);
}
#else
UNUSED(isfp);
#endif
}
if (fid) lj_err_caller(L, LJ_ERR_FFI_NUMARG); /* Too few arguments. */
#if LJ_TARGET_X64 || LJ_TARGET_PPC
cc->nfpr = nfpr; /* Required for vararg functions. */
#endif
cc->nsp = nsp;
cc->spadj = (CCALL_SPS_FREE + CCALL_SPS_EXTRA)*CTSIZE_PTR;
if (nsp > CCALL_SPS_FREE)
cc->spadj += (((nsp-CCALL_SPS_FREE)*CTSIZE_PTR + 15u) & ~15u);
return gcsteps;
}
/* Get results from C call. */
static int ccall_get_results(lua_State *L, CTState *cts, CType *ct,
CCallState *cc, int *ret)
{
CType *ctr = ctype_rawchild(cts, ct);
uint8_t *sp = (uint8_t *)&cc->gpr[0];
if (ctype_isvoid(ctr->info)) {
*ret = 0; /* Zero results. */
return 0; /* No additional GC step. */
}
*ret = 1; /* One result. */
if (ctype_isstruct(ctr->info)) {
/* Return cdata object which is already on top of stack. */
if (!cc->retref) {
void *dp = cdataptr(cdataV(L->top-1)); /* Use preallocated object. */
CCALL_HANDLE_STRUCTRET2
}
return 1; /* One GC step. */
}
if (ctype_iscomplex(ctr->info)) {
/* Return cdata object which is already on top of stack. */
void *dp = cdataptr(cdataV(L->top-1)); /* Use preallocated object. */
CCALL_HANDLE_COMPLEXRET2
return 1; /* One GC step. */
}
if (LJ_BE && ctype_isinteger_or_bool(ctr->info) && ctr->size < CTSIZE_PTR)
sp += (CTSIZE_PTR - ctr->size);
#if CCALL_NUM_FPR
if (ctype_isfp(ctr->info) || ctype_isvector(ctr->info))
sp = (uint8_t *)&cc->fpr[0];
#endif
#ifdef CCALL_HANDLE_RET
CCALL_HANDLE_RET
#endif
/* No reference types end up here, so there's no need for the CTypeID. */
lua_assert(!(ctype_isrefarray(ctr->info) || ctype_isstruct(ctr->info)));
return lj_cconv_tv_ct(cts, ctr, 0, L->top-1, sp);
}
/* Call C function. */
int lj_ccall_func(lua_State *L, GCcdata *cd)
{
CTState *cts = ctype_cts(L);
CType *ct = ctype_raw(cts, cd->ctypeid);
CTSize sz = CTSIZE_PTR;
if (ctype_isptr(ct->info)) {
sz = ct->size;
ct = ctype_rawchild(cts, ct);
}
if (ctype_isfunc(ct->info)) {
CCallState cc;
int gcsteps, ret;
cc.func = (void (*)(void))cdata_getptr(cdataptr(cd), sz);
gcsteps = ccall_set_args(L, cts, ct, &cc);
ct = (CType *)((intptr_t)ct-(intptr_t)cts->tab);
cts->cb.slot = ~0u;
lj_vm_ffi_call(&cc);
if (cts->cb.slot != ~0u) { /* Blacklist function that called a callback. */
TValue tv;
setlightudV(&tv, (void *)cc.func);
setboolV(lj_tab_set(L, cts->miscmap, &tv), 1);
}
ct = (CType *)((intptr_t)ct+(intptr_t)cts->tab); /* May be reallocated. */
gcsteps += ccall_get_results(L, cts, ct, &cc, &ret);
#if LJ_TARGET_X86 && LJ_ABI_WIN
/* Automatically detect __stdcall and fix up C function declaration. */
if (cc.spadj && ctype_cconv(ct->info) == CTCC_CDECL) {
CTF_INSERT(ct->info, CCONV, CTCC_STDCALL);
lj_trace_abort(G(L));
}
#endif
while (gcsteps-- > 0)
lj_gc_check(L);
return ret;
}
return -1; /* Not a function. */
}
#endif
| xLua/build/luajit-2.1.0b2/src/lj_ccall.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_ccall.c",
"repo_id": "xLua",
"token_count": 14418
} | 2,109 |
/*
** C type management.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#include "lj_obj.h"
#if LJ_HASFFI
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_strfmt.h"
#include "lj_ctype.h"
#include "lj_ccallback.h"
#include "lj_buf.h"
/* -- C type definitions -------------------------------------------------- */
/* Predefined typedefs. */
#define CTTDDEF(_) \
/* Vararg handling. */ \
_("va_list", P_VOID) \
_("__builtin_va_list", P_VOID) \
_("__gnuc_va_list", P_VOID) \
/* From stddef.h. */ \
_("ptrdiff_t", INT_PSZ) \
_("size_t", UINT_PSZ) \
_("wchar_t", WCHAR) \
/* Subset of stdint.h. */ \
_("int8_t", INT8) \
_("int16_t", INT16) \
_("int32_t", INT32) \
_("int64_t", INT64) \
_("uint8_t", UINT8) \
_("uint16_t", UINT16) \
_("uint32_t", UINT32) \
_("uint64_t", UINT64) \
_("intptr_t", INT_PSZ) \
_("uintptr_t", UINT_PSZ) \
/* From POSIX. */ \
_("ssize_t", INT_PSZ) \
/* End of typedef list. */
/* Keywords (only the ones we actually care for). */
#define CTKWDEF(_) \
/* Type specifiers. */ \
_("void", -1, CTOK_VOID) \
_("_Bool", 0, CTOK_BOOL) \
_("bool", 1, CTOK_BOOL) \
_("char", 1, CTOK_CHAR) \
_("int", 4, CTOK_INT) \
_("__int8", 1, CTOK_INT) \
_("__int16", 2, CTOK_INT) \
_("__int32", 4, CTOK_INT) \
_("__int64", 8, CTOK_INT) \
_("float", 4, CTOK_FP) \
_("double", 8, CTOK_FP) \
_("long", 0, CTOK_LONG) \
_("short", 0, CTOK_SHORT) \
_("_Complex", 0, CTOK_COMPLEX) \
_("complex", 0, CTOK_COMPLEX) \
_("__complex", 0, CTOK_COMPLEX) \
_("__complex__", 0, CTOK_COMPLEX) \
_("signed", 0, CTOK_SIGNED) \
_("__signed", 0, CTOK_SIGNED) \
_("__signed__", 0, CTOK_SIGNED) \
_("unsigned", 0, CTOK_UNSIGNED) \
/* Type qualifiers. */ \
_("const", 0, CTOK_CONST) \
_("__const", 0, CTOK_CONST) \
_("__const__", 0, CTOK_CONST) \
_("volatile", 0, CTOK_VOLATILE) \
_("__volatile", 0, CTOK_VOLATILE) \
_("__volatile__", 0, CTOK_VOLATILE) \
_("restrict", 0, CTOK_RESTRICT) \
_("__restrict", 0, CTOK_RESTRICT) \
_("__restrict__", 0, CTOK_RESTRICT) \
_("inline", 0, CTOK_INLINE) \
_("__inline", 0, CTOK_INLINE) \
_("__inline__", 0, CTOK_INLINE) \
/* Storage class specifiers. */ \
_("typedef", 0, CTOK_TYPEDEF) \
_("extern", 0, CTOK_EXTERN) \
_("static", 0, CTOK_STATIC) \
_("auto", 0, CTOK_AUTO) \
_("register", 0, CTOK_REGISTER) \
/* GCC Attributes. */ \
_("__extension__", 0, CTOK_EXTENSION) \
_("__attribute", 0, CTOK_ATTRIBUTE) \
_("__attribute__", 0, CTOK_ATTRIBUTE) \
_("asm", 0, CTOK_ASM) \
_("__asm", 0, CTOK_ASM) \
_("__asm__", 0, CTOK_ASM) \
/* MSVC Attributes. */ \
_("__declspec", 0, CTOK_DECLSPEC) \
_("__cdecl", CTCC_CDECL, CTOK_CCDECL) \
_("__thiscall", CTCC_THISCALL, CTOK_CCDECL) \
_("__fastcall", CTCC_FASTCALL, CTOK_CCDECL) \
_("__stdcall", CTCC_STDCALL, CTOK_CCDECL) \
_("__ptr32", 4, CTOK_PTRSZ) \
_("__ptr64", 8, CTOK_PTRSZ) \
/* Other type specifiers. */ \
_("struct", 0, CTOK_STRUCT) \
_("union", 0, CTOK_UNION) \
_("enum", 0, CTOK_ENUM) \
/* Operators. */ \
_("sizeof", 0, CTOK_SIZEOF) \
_("__alignof", 0, CTOK_ALIGNOF) \
_("__alignof__", 0, CTOK_ALIGNOF) \
/* End of keyword list. */
/* Type info for predefined types. Size merged in. */
static CTInfo lj_ctype_typeinfo[] = {
#define CTTYINFODEF(id, sz, ct, info) CTINFO((ct),(((sz)&0x3fu)<<10)+(info)),
#define CTTDINFODEF(name, id) CTINFO(CT_TYPEDEF, CTID_##id),
#define CTKWINFODEF(name, sz, kw) CTINFO(CT_KW,(((sz)&0x3fu)<<10)+(kw)),
CTTYDEF(CTTYINFODEF)
CTTDDEF(CTTDINFODEF)
CTKWDEF(CTKWINFODEF)
#undef CTTYINFODEF
#undef CTTDINFODEF
#undef CTKWINFODEF
0
};
/* Predefined type names collected in a single string. */
static const char * const lj_ctype_typenames =
#define CTTDNAMEDEF(name, id) name "\0"
#define CTKWNAMEDEF(name, sz, cds) name "\0"
CTTDDEF(CTTDNAMEDEF)
CTKWDEF(CTKWNAMEDEF)
#undef CTTDNAMEDEF
#undef CTKWNAMEDEF
;
#define CTTYPEINFO_NUM (sizeof(lj_ctype_typeinfo)/sizeof(CTInfo)-1)
#ifdef LUAJIT_CTYPE_CHECK_ANCHOR
#define CTTYPETAB_MIN CTTYPEINFO_NUM
#else
#define CTTYPETAB_MIN 128
#endif
/* -- C type interning ---------------------------------------------------- */
#define ct_hashtype(info, size) (hashrot(info, size) & CTHASH_MASK)
#define ct_hashname(name) \
(hashrot(u32ptr(name), u32ptr(name) + HASH_BIAS) & CTHASH_MASK)
/* Create new type element. */
CTypeID lj_ctype_new(CTState *cts, CType **ctp)
{
CTypeID id = cts->top;
CType *ct;
lua_assert(cts->L);
if (LJ_UNLIKELY(id >= cts->sizetab)) {
if (id >= CTID_MAX) lj_err_msg(cts->L, LJ_ERR_TABOV);
#ifdef LUAJIT_CTYPE_CHECK_ANCHOR
ct = lj_mem_newvec(cts->L, id+1, CType);
memcpy(ct, cts->tab, id*sizeof(CType));
memset(cts->tab, 0, id*sizeof(CType));
lj_mem_freevec(cts->g, cts->tab, cts->sizetab, CType);
cts->tab = ct;
cts->sizetab = id+1;
#else
lj_mem_growvec(cts->L, cts->tab, cts->sizetab, CTID_MAX, CType);
#endif
}
cts->top = id+1;
*ctp = ct = &cts->tab[id];
ct->info = 0;
ct->size = 0;
ct->sib = 0;
ct->next = 0;
setgcrefnull(ct->name);
return id;
}
/* Intern a type element. */
CTypeID lj_ctype_intern(CTState *cts, CTInfo info, CTSize size)
{
uint32_t h = ct_hashtype(info, size);
CTypeID id = cts->hash[h];
lua_assert(cts->L);
while (id) {
CType *ct = ctype_get(cts, id);
if (ct->info == info && ct->size == size)
return id;
id = ct->next;
}
id = cts->top;
if (LJ_UNLIKELY(id >= cts->sizetab)) {
if (id >= CTID_MAX) lj_err_msg(cts->L, LJ_ERR_TABOV);
lj_mem_growvec(cts->L, cts->tab, cts->sizetab, CTID_MAX, CType);
}
cts->top = id+1;
cts->tab[id].info = info;
cts->tab[id].size = size;
cts->tab[id].sib = 0;
cts->tab[id].next = cts->hash[h];
setgcrefnull(cts->tab[id].name);
cts->hash[h] = (CTypeID1)id;
return id;
}
/* Add type element to hash table. */
static void ctype_addtype(CTState *cts, CType *ct, CTypeID id)
{
uint32_t h = ct_hashtype(ct->info, ct->size);
ct->next = cts->hash[h];
cts->hash[h] = (CTypeID1)id;
}
/* Add named element to hash table. */
void lj_ctype_addname(CTState *cts, CType *ct, CTypeID id)
{
uint32_t h = ct_hashname(gcref(ct->name));
ct->next = cts->hash[h];
cts->hash[h] = (CTypeID1)id;
}
/* Get a C type by name, matching the type mask. */
CTypeID lj_ctype_getname(CTState *cts, CType **ctp, GCstr *name, uint32_t tmask)
{
CTypeID id = cts->hash[ct_hashname(name)];
while (id) {
CType *ct = ctype_get(cts, id);
if (gcref(ct->name) == obj2gco(name) &&
((tmask >> ctype_type(ct->info)) & 1)) {
*ctp = ct;
return id;
}
id = ct->next;
}
*ctp = &cts->tab[0]; /* Simplify caller logic. ctype_get() would assert. */
return 0;
}
/* Get a struct/union/enum/function field by name. */
CType *lj_ctype_getfieldq(CTState *cts, CType *ct, GCstr *name, CTSize *ofs,
CTInfo *qual)
{
while (ct->sib) {
ct = ctype_get(cts, ct->sib);
if (gcref(ct->name) == obj2gco(name)) {
*ofs = ct->size;
return ct;
}
if (ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
CType *fct, *cct = ctype_child(cts, ct);
CTInfo q = 0;
while (ctype_isattrib(cct->info)) {
if (ctype_attrib(cct->info) == CTA_QUAL) q |= cct->size;
cct = ctype_child(cts, cct);
}
fct = lj_ctype_getfieldq(cts, cct, name, ofs, qual);
if (fct) {
if (qual) *qual |= q;
*ofs += ct->size;
return fct;
}
}
}
return NULL; /* Not found. */
}
/* -- C type information -------------------------------------------------- */
/* Follow references and get raw type for a C type ID. */
CType *lj_ctype_rawref(CTState *cts, CTypeID id)
{
CType *ct = ctype_get(cts, id);
while (ctype_isattrib(ct->info) || ctype_isref(ct->info))
ct = ctype_child(cts, ct);
return ct;
}
/* Get size for a C type ID. Does NOT support VLA/VLS. */
CTSize lj_ctype_size(CTState *cts, CTypeID id)
{
CType *ct = ctype_raw(cts, id);
return ctype_hassize(ct->info) ? ct->size : CTSIZE_INVALID;
}
/* Get size for a variable-length C type. Does NOT support other C types. */
CTSize lj_ctype_vlsize(CTState *cts, CType *ct, CTSize nelem)
{
uint64_t xsz = 0;
if (ctype_isstruct(ct->info)) {
CTypeID arrid = 0, fid = ct->sib;
xsz = ct->size; /* Add the struct size. */
while (fid) {
CType *ctf = ctype_get(cts, fid);
if (ctype_type(ctf->info) == CT_FIELD)
arrid = ctype_cid(ctf->info); /* Remember last field of VLS. */
fid = ctf->sib;
}
ct = ctype_raw(cts, arrid);
}
lua_assert(ctype_isvlarray(ct->info)); /* Must be a VLA. */
ct = ctype_rawchild(cts, ct); /* Get array element. */
lua_assert(ctype_hassize(ct->info));
/* Calculate actual size of VLA and check for overflow. */
xsz += (uint64_t)ct->size * nelem;
return xsz < 0x80000000u ? (CTSize)xsz : CTSIZE_INVALID;
}
/* Get type, qualifiers, size and alignment for a C type ID. */
CTInfo lj_ctype_info(CTState *cts, CTypeID id, CTSize *szp)
{
CTInfo qual = 0;
CType *ct = ctype_get(cts, id);
for (;;) {
CTInfo info = ct->info;
if (ctype_isenum(info)) {
/* Follow child. Need to look at its attributes, too. */
} else if (ctype_isattrib(info)) {
if (ctype_isxattrib(info, CTA_QUAL))
qual |= ct->size;
else if (ctype_isxattrib(info, CTA_ALIGN) && !(qual & CTFP_ALIGNED))
qual |= CTFP_ALIGNED + CTALIGN(ct->size);
} else {
if (!(qual & CTFP_ALIGNED)) qual |= (info & CTF_ALIGN);
qual |= (info & ~(CTF_ALIGN|CTMASK_CID));
lua_assert(ctype_hassize(info) || ctype_isfunc(info));
*szp = ctype_isfunc(info) ? CTSIZE_INVALID : ct->size;
break;
}
ct = ctype_get(cts, ctype_cid(info));
}
return qual;
}
/* Get ctype metamethod. */
cTValue *lj_ctype_meta(CTState *cts, CTypeID id, MMS mm)
{
CType *ct = ctype_get(cts, id);
cTValue *tv;
while (ctype_isattrib(ct->info) || ctype_isref(ct->info)) {
id = ctype_cid(ct->info);
ct = ctype_get(cts, id);
}
if (ctype_isptr(ct->info) &&
ctype_isfunc(ctype_get(cts, ctype_cid(ct->info))->info))
tv = lj_tab_getstr(cts->miscmap, &cts->g->strempty);
else
tv = lj_tab_getinth(cts->miscmap, -(int32_t)id);
if (tv && tvistab(tv) &&
(tv = lj_tab_getstr(tabV(tv), mmname_str(cts->g, mm))) && !tvisnil(tv))
return tv;
return NULL;
}
/* -- C type representation ----------------------------------------------- */
/* Fixed max. length of a C type representation. */
#define CTREPR_MAX 512
typedef struct CTRepr {
char *pb, *pe;
CTState *cts;
lua_State *L;
int needsp;
int ok;
char buf[CTREPR_MAX];
} CTRepr;
/* Prepend string. */
static void ctype_prepstr(CTRepr *ctr, const char *str, MSize len)
{
char *p = ctr->pb;
if (ctr->buf + len+1 > p) { ctr->ok = 0; return; }
if (ctr->needsp) *--p = ' ';
ctr->needsp = 1;
p -= len;
while (len-- > 0) p[len] = str[len];
ctr->pb = p;
}
#define ctype_preplit(ctr, str) ctype_prepstr((ctr), "" str, sizeof(str)-1)
/* Prepend char. */
static void ctype_prepc(CTRepr *ctr, int c)
{
if (ctr->buf >= ctr->pb) { ctr->ok = 0; return; }
*--ctr->pb = c;
}
/* Prepend number. */
static void ctype_prepnum(CTRepr *ctr, uint32_t n)
{
char *p = ctr->pb;
if (ctr->buf + 10+1 > p) { ctr->ok = 0; return; }
do { *--p = (char)('0' + n % 10); } while (n /= 10);
ctr->pb = p;
ctr->needsp = 0;
}
/* Append char. */
static void ctype_appc(CTRepr *ctr, int c)
{
if (ctr->pe >= ctr->buf + CTREPR_MAX) { ctr->ok = 0; return; }
*ctr->pe++ = c;
}
/* Append number. */
static void ctype_appnum(CTRepr *ctr, uint32_t n)
{
char buf[10];
char *p = buf+sizeof(buf);
char *q = ctr->pe;
if (q > ctr->buf + CTREPR_MAX - 10) { ctr->ok = 0; return; }
do { *--p = (char)('0' + n % 10); } while (n /= 10);
do { *q++ = *p++; } while (p < buf+sizeof(buf));
ctr->pe = q;
}
/* Prepend qualifiers. */
static void ctype_prepqual(CTRepr *ctr, CTInfo info)
{
if ((info & CTF_VOLATILE)) ctype_preplit(ctr, "volatile");
if ((info & CTF_CONST)) ctype_preplit(ctr, "const");
}
/* Prepend named type. */
static void ctype_preptype(CTRepr *ctr, CType *ct, CTInfo qual, const char *t)
{
if (gcref(ct->name)) {
GCstr *str = gco2str(gcref(ct->name));
ctype_prepstr(ctr, strdata(str), str->len);
} else {
if (ctr->needsp) ctype_prepc(ctr, ' ');
ctype_prepnum(ctr, ctype_typeid(ctr->cts, ct));
ctr->needsp = 1;
}
ctype_prepstr(ctr, t, (MSize)strlen(t));
ctype_prepqual(ctr, qual);
}
static void ctype_repr(CTRepr *ctr, CTypeID id)
{
CType *ct = ctype_get(ctr->cts, id);
CTInfo qual = 0;
int ptrto = 0;
for (;;) {
CTInfo info = ct->info;
CTSize size = ct->size;
switch (ctype_type(info)) {
case CT_NUM:
if ((info & CTF_BOOL)) {
ctype_preplit(ctr, "bool");
} else if ((info & CTF_FP)) {
if (size == sizeof(double)) ctype_preplit(ctr, "double");
else if (size == sizeof(float)) ctype_preplit(ctr, "float");
else ctype_preplit(ctr, "long double");
} else if (size == 1) {
if (!((info ^ CTF_UCHAR) & CTF_UNSIGNED)) ctype_preplit(ctr, "char");
else if (CTF_UCHAR) ctype_preplit(ctr, "signed char");
else ctype_preplit(ctr, "unsigned char");
} else if (size < 8) {
if (size == 4) ctype_preplit(ctr, "int");
else ctype_preplit(ctr, "short");
if ((info & CTF_UNSIGNED)) ctype_preplit(ctr, "unsigned");
} else {
ctype_preplit(ctr, "_t");
ctype_prepnum(ctr, size*8);
ctype_preplit(ctr, "int");
if ((info & CTF_UNSIGNED)) ctype_prepc(ctr, 'u');
}
ctype_prepqual(ctr, (qual|info));
return;
case CT_VOID:
ctype_preplit(ctr, "void");
ctype_prepqual(ctr, (qual|info));
return;
case CT_STRUCT:
ctype_preptype(ctr, ct, qual, (info & CTF_UNION) ? "union" : "struct");
return;
case CT_ENUM:
if (id == CTID_CTYPEID) {
ctype_preplit(ctr, "ctype");
return;
}
ctype_preptype(ctr, ct, qual, "enum");
return;
case CT_ATTRIB:
if (ctype_attrib(info) == CTA_QUAL) qual |= size;
break;
case CT_PTR:
if ((info & CTF_REF)) {
ctype_prepc(ctr, '&');
} else {
ctype_prepqual(ctr, (qual|info));
if (LJ_64 && size == 4) ctype_preplit(ctr, "__ptr32");
ctype_prepc(ctr, '*');
}
qual = 0;
ptrto = 1;
ctr->needsp = 1;
break;
case CT_ARRAY:
if (ctype_isrefarray(info)) {
ctr->needsp = 1;
if (ptrto) { ptrto = 0; ctype_prepc(ctr, '('); ctype_appc(ctr, ')'); }
ctype_appc(ctr, '[');
if (size != CTSIZE_INVALID) {
CTSize csize = ctype_child(ctr->cts, ct)->size;
ctype_appnum(ctr, csize ? size/csize : 0);
} else if ((info & CTF_VLA)) {
ctype_appc(ctr, '?');
}
ctype_appc(ctr, ']');
} else if ((info & CTF_COMPLEX)) {
if (size == 2*sizeof(float)) ctype_preplit(ctr, "float");
ctype_preplit(ctr, "complex");
return;
} else {
ctype_preplit(ctr, ")))");
ctype_prepnum(ctr, size);
ctype_preplit(ctr, "__attribute__((vector_size(");
}
break;
case CT_FUNC:
ctr->needsp = 1;
if (ptrto) { ptrto = 0; ctype_prepc(ctr, '('); ctype_appc(ctr, ')'); }
ctype_appc(ctr, '(');
ctype_appc(ctr, ')');
break;
default:
lua_assert(0);
break;
}
ct = ctype_get(ctr->cts, ctype_cid(info));
}
}
/* Return a printable representation of a C type. */
GCstr *lj_ctype_repr(lua_State *L, CTypeID id, GCstr *name)
{
global_State *g = G(L);
CTRepr ctr;
ctr.pb = ctr.pe = &ctr.buf[CTREPR_MAX/2];
ctr.cts = ctype_ctsG(g);
ctr.L = L;
ctr.ok = 1;
ctr.needsp = 0;
if (name) ctype_prepstr(&ctr, strdata(name), name->len);
ctype_repr(&ctr, id);
if (LJ_UNLIKELY(!ctr.ok)) return lj_str_newlit(L, "?");
return lj_str_new(L, ctr.pb, ctr.pe - ctr.pb);
}
/* Convert int64_t/uint64_t to string with 'LL' or 'ULL' suffix. */
GCstr *lj_ctype_repr_int64(lua_State *L, uint64_t n, int isunsigned)
{
char buf[1+20+3];
char *p = buf+sizeof(buf);
int sign = 0;
*--p = 'L'; *--p = 'L';
if (isunsigned) {
*--p = 'U';
} else if ((int64_t)n < 0) {
n = (uint64_t)-(int64_t)n;
sign = 1;
}
do { *--p = (char)('0' + n % 10); } while (n /= 10);
if (sign) *--p = '-';
return lj_str_new(L, p, (size_t)(buf+sizeof(buf)-p));
}
/* Convert complex to string with 'i' or 'I' suffix. */
GCstr *lj_ctype_repr_complex(lua_State *L, void *sp, CTSize size)
{
SBuf *sb = lj_buf_tmp_(L);
TValue re, im;
if (size == 2*sizeof(double)) {
re.n = *(double *)sp; im.n = ((double *)sp)[1];
} else {
re.n = (double)*(float *)sp; im.n = (double)((float *)sp)[1];
}
lj_strfmt_putfnum(sb, STRFMT_G14, re.n);
if (!(im.u32.hi & 0x80000000u) || im.n != im.n) lj_buf_putchar(sb, '+');
lj_strfmt_putfnum(sb, STRFMT_G14, im.n);
lj_buf_putchar(sb, sbufP(sb)[-1] >= 'a' ? 'I' : 'i');
return lj_buf_str(L, sb);
}
/* -- C type state -------------------------------------------------------- */
/* Initialize C type table and state. */
CTState *lj_ctype_init(lua_State *L)
{
CTState *cts = lj_mem_newt(L, sizeof(CTState), CTState);
CType *ct = lj_mem_newvec(L, CTTYPETAB_MIN, CType);
const char *name = lj_ctype_typenames;
CTypeID id;
memset(cts, 0, sizeof(CTState));
cts->tab = ct;
cts->sizetab = CTTYPETAB_MIN;
cts->top = CTTYPEINFO_NUM;
cts->L = NULL;
cts->g = G(L);
for (id = 0; id < CTTYPEINFO_NUM; id++, ct++) {
CTInfo info = lj_ctype_typeinfo[id];
ct->size = (CTSize)((int32_t)(info << 16) >> 26);
ct->info = info & 0xffff03ffu;
ct->sib = 0;
if (ctype_type(info) == CT_KW || ctype_istypedef(info)) {
size_t len = strlen(name);
GCstr *str = lj_str_new(L, name, len);
ctype_setname(ct, str);
name += len+1;
lj_ctype_addname(cts, ct, id);
} else {
setgcrefnull(ct->name);
ct->next = 0;
if (!ctype_isenum(info)) ctype_addtype(cts, ct, id);
}
}
setmref(G(L)->ctype_state, cts);
return cts;
}
/* Free C type table and state. */
void lj_ctype_freestate(global_State *g)
{
CTState *cts = ctype_ctsG(g);
if (cts) {
lj_ccallback_mcode_free(cts);
lj_mem_freevec(g, cts->tab, cts->sizetab, CType);
lj_mem_freevec(g, cts->cb.cbid, cts->cb.sizeid, CTypeID1);
lj_mem_freet(g, cts);
}
}
#endif
| xLua/build/luajit-2.1.0b2/src/lj_ctype.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_ctype.c",
"repo_id": "xLua",
"token_count": 8918
} | 2,110 |
/*
** Fast function call recorder.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_FFRECORD_H
#define _LJ_FFRECORD_H
#include "lj_obj.h"
#include "lj_jit.h"
#if LJ_HASJIT
/* Data used by handlers to record a fast function. */
typedef struct RecordFFData {
TValue *argv; /* Runtime argument values. */
ptrdiff_t nres; /* Number of returned results (defaults to 1). */
uint32_t data; /* Per-ffid auxiliary data (opcode, literal etc.). */
} RecordFFData;
LJ_FUNC int32_t lj_ffrecord_select_mode(jit_State *J, TRef tr, TValue *tv);
LJ_FUNC void lj_ffrecord_func(jit_State *J);
#endif
#endif
| xLua/build/luajit-2.1.0b2/src/lj_ffrecord.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_ffrecord.h",
"repo_id": "xLua",
"token_count": 250
} | 2,111 |
/*
** Library function support.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_LIB_H
#define _LJ_LIB_H
#include "lj_obj.h"
/*
** A fallback handler is called by the assembler VM if the fast path fails:
**
** - too few arguments: unrecoverable.
** - wrong argument type: recoverable, if coercion succeeds.
** - bad argument value: unrecoverable.
** - stack overflow: recoverable, if stack reallocation succeeds.
** - extra handling: recoverable.
**
** The unrecoverable cases throw an error with lj_err_arg(), lj_err_argtype(),
** lj_err_caller() or lj_err_callermsg().
** The recoverable cases return 0 or the number of results + 1.
** The assembler VM retries the fast path only if 0 is returned.
** This time the fallback must not be called again or it gets stuck in a loop.
*/
/* Return values from fallback handler. */
#define FFH_RETRY 0
#define FFH_UNREACHABLE FFH_RETRY
#define FFH_RES(n) ((n)+1)
#define FFH_TAILCALL (-1)
LJ_FUNC TValue *lj_lib_checkany(lua_State *L, int narg);
LJ_FUNC GCstr *lj_lib_checkstr(lua_State *L, int narg);
LJ_FUNC GCstr *lj_lib_optstr(lua_State *L, int narg);
#if LJ_DUALNUM
LJ_FUNC void lj_lib_checknumber(lua_State *L, int narg);
#else
#define lj_lib_checknumber(L, narg) lj_lib_checknum((L), (narg))
#endif
LJ_FUNC lua_Number lj_lib_checknum(lua_State *L, int narg);
LJ_FUNC int32_t lj_lib_checkint(lua_State *L, int narg);
LJ_FUNC int32_t lj_lib_optint(lua_State *L, int narg, int32_t def);
LJ_FUNC GCfunc *lj_lib_checkfunc(lua_State *L, int narg);
LJ_FUNC GCtab *lj_lib_checktab(lua_State *L, int narg);
LJ_FUNC GCtab *lj_lib_checktabornil(lua_State *L, int narg);
LJ_FUNC int lj_lib_checkopt(lua_State *L, int narg, int def, const char *lst);
/* Avoid including lj_frame.h. */
#if LJ_GC64
#define lj_lib_upvalue(L, n) \
(&gcval(L->base-2)->fn.c.upvalue[(n)-1])
#elif LJ_FR2
#define lj_lib_upvalue(L, n) \
(&gcref((L->base-2)->gcr)->fn.c.upvalue[(n)-1])
#else
#define lj_lib_upvalue(L, n) \
(&gcref((L->base-1)->fr.func)->fn.c.upvalue[(n)-1])
#endif
#if LJ_TARGET_WINDOWS
#define lj_lib_checkfpu(L) \
do { setnumV(L->top++, (lua_Number)1437217655); \
if (lua_tointeger(L, -1) != 1437217655) lj_err_caller(L, LJ_ERR_BADFPU); \
L->top--; } while (0)
#else
#define lj_lib_checkfpu(L) UNUSED(L)
#endif
LJ_FUNC GCfunc *lj_lib_pushcc(lua_State *L, lua_CFunction f, int id, int n);
#define lj_lib_pushcf(L, fn, id) (lj_lib_pushcc(L, (fn), (id), 0))
/* Library function declarations. Scanned by buildvm. */
#define LJLIB_CF(name) static int lj_cf_##name(lua_State *L)
#define LJLIB_ASM(name) static int lj_ffh_##name(lua_State *L)
#define LJLIB_ASM_(name)
#define LJLIB_LUA(name)
#define LJLIB_SET(name)
#define LJLIB_PUSH(arg)
#define LJLIB_REC(handler)
#define LJLIB_NOREGUV
#define LJLIB_NOREG
#define LJ_LIB_REG(L, regname, name) \
lj_lib_register(L, regname, lj_lib_init_##name, lj_lib_cf_##name)
LJ_FUNC void lj_lib_register(lua_State *L, const char *libname,
const uint8_t *init, const lua_CFunction *cf);
LJ_FUNC void lj_lib_prereg(lua_State *L, const char *name, lua_CFunction f,
GCtab *env);
LJ_FUNC int lj_lib_postreg(lua_State *L, lua_CFunction cf, int id,
const char *name);
/* Library init data tags. */
#define LIBINIT_LENMASK 0x3f
#define LIBINIT_TAGMASK 0xc0
#define LIBINIT_CF 0x00
#define LIBINIT_ASM 0x40
#define LIBINIT_ASM_ 0x80
#define LIBINIT_STRING 0xc0
#define LIBINIT_MAXSTR 0x38
#define LIBINIT_LUA 0xf9
#define LIBINIT_SET 0xfa
#define LIBINIT_NUMBER 0xfb
#define LIBINIT_COPY 0xfc
#define LIBINIT_LASTCL 0xfd
#define LIBINIT_FFID 0xfe
#define LIBINIT_END 0xff
/* Exported library functions. */
typedef struct RandomState RandomState;
LJ_FUNC uint64_t LJ_FASTCALL lj_math_random_step(RandomState *rs);
#endif
| xLua/build/luajit-2.1.0b2/src/lj_lib.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_lib.h",
"repo_id": "xLua",
"token_count": 1673
} | 2,112 |
/*
** Lua parser (source code -> bytecode).
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_PARSE_H
#define _LJ_PARSE_H
#include "lj_obj.h"
#include "lj_lex.h"
LJ_FUNC GCproto *lj_parse(LexState *ls);
LJ_FUNC GCstr *lj_parse_keepstr(LexState *ls, const char *str, size_t l);
#if LJ_HASFFI
LJ_FUNC void lj_parse_keepcdata(LexState *ls, TValue *tv, GCcdata *cd);
#endif
#endif
| xLua/build/luajit-2.1.0b2/src/lj_parse.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_parse.h",
"repo_id": "xLua",
"token_count": 188
} | 2,113 |
/*
** Table handling.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
**
** Major portions taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#define lj_tab_c
#define LUA_CORE
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_tab.h"
/* -- Object hashing ------------------------------------------------------ */
/* Hash values are masked with the table hash mask and used as an index. */
static LJ_AINLINE Node *hashmask(const GCtab *t, uint32_t hash)
{
Node *n = noderef(t->node);
return &n[hash & t->hmask];
}
/* String hashes are precomputed when they are interned. */
#define hashstr(t, s) hashmask(t, (s)->hash)
#define hashlohi(t, lo, hi) hashmask((t), hashrot((lo), (hi)))
#define hashnum(t, o) hashlohi((t), (o)->u32.lo, ((o)->u32.hi << 1))
#define hashptr(t, p) hashlohi((t), u32ptr(p), u32ptr(p) + HASH_BIAS)
#if LJ_GC64
#define hashgcref(t, r) \
hashlohi((t), (uint32_t)gcrefu(r), (uint32_t)(gcrefu(r) >> 32))
#else
#define hashgcref(t, r) hashlohi((t), gcrefu(r), gcrefu(r) + HASH_BIAS)
#endif
/* Hash an arbitrary key and return its anchor position in the hash table. */
static Node *hashkey(const GCtab *t, cTValue *key)
{
lua_assert(!tvisint(key));
if (tvisstr(key))
return hashstr(t, strV(key));
else if (tvisnum(key))
return hashnum(t, key);
else if (tvisbool(key))
return hashmask(t, boolV(key));
else
return hashgcref(t, key->gcr);
/* Only hash 32 bits of lightuserdata on a 64 bit CPU. Good enough? */
}
/* -- Table creation and destruction -------------------------------------- */
/* Create new hash part for table. */
static LJ_AINLINE void newhpart(lua_State *L, GCtab *t, uint32_t hbits)
{
uint32_t hsize;
Node *node;
lua_assert(hbits != 0);
if (hbits > LJ_MAX_HBITS)
lj_err_msg(L, LJ_ERR_TABOV);
hsize = 1u << hbits;
node = lj_mem_newvec(L, hsize, Node);
setmref(t->node, node);
setfreetop(t, node, &node[hsize]);
t->hmask = hsize-1;
}
/*
** Q: Why all of these copies of t->hmask, t->node etc. to local variables?
** A: Because alias analysis for C is _really_ tough.
** Even state-of-the-art C compilers won't produce good code without this.
*/
/* Clear hash part of table. */
static LJ_AINLINE void clearhpart(GCtab *t)
{
uint32_t i, hmask = t->hmask;
Node *node = noderef(t->node);
lua_assert(t->hmask != 0);
for (i = 0; i <= hmask; i++) {
Node *n = &node[i];
setmref(n->next, NULL);
setnilV(&n->key);
setnilV(&n->val);
}
}
/* Clear array part of table. */
static LJ_AINLINE void clearapart(GCtab *t)
{
uint32_t i, asize = t->asize;
TValue *array = tvref(t->array);
for (i = 0; i < asize; i++)
setnilV(&array[i]);
}
/* Create a new table. Note: the slots are not initialized (yet). */
static GCtab *newtab(lua_State *L, uint32_t asize, uint32_t hbits)
{
GCtab *t;
/* First try to colocate the array part. */
if (LJ_MAX_COLOSIZE != 0 && asize > 0 && asize <= LJ_MAX_COLOSIZE) {
Node *nilnode;
lua_assert((sizeof(GCtab) & 7) == 0);
t = (GCtab *)lj_mem_newgco(L, sizetabcolo(asize));
t->gct = ~LJ_TTAB;
t->nomm = (uint8_t)~0;
t->colo = (int8_t)asize;
setmref(t->array, (TValue *)((char *)t + sizeof(GCtab)));
setgcrefnull(t->metatable);
t->asize = asize;
t->hmask = 0;
nilnode = &G(L)->nilnode;
setmref(t->node, nilnode);
#if LJ_GC64
setmref(t->freetop, nilnode);
#endif
} else { /* Otherwise separately allocate the array part. */
Node *nilnode;
t = lj_mem_newobj(L, GCtab);
t->gct = ~LJ_TTAB;
t->nomm = (uint8_t)~0;
t->colo = 0;
setmref(t->array, NULL);
setgcrefnull(t->metatable);
t->asize = 0; /* In case the array allocation fails. */
t->hmask = 0;
nilnode = &G(L)->nilnode;
setmref(t->node, nilnode);
#if LJ_GC64
setmref(t->freetop, nilnode);
#endif
if (asize > 0) {
if (asize > LJ_MAX_ASIZE)
lj_err_msg(L, LJ_ERR_TABOV);
setmref(t->array, lj_mem_newvec(L, asize, TValue));
t->asize = asize;
}
}
if (hbits)
newhpart(L, t, hbits);
return t;
}
/* Create a new table.
**
** IMPORTANT NOTE: The API differs from lua_createtable()!
**
** The array size is non-inclusive. E.g. asize=128 creates array slots
** for 0..127, but not for 128. If you need slots 1..128, pass asize=129
** (slot 0 is wasted in this case).
**
** The hash size is given in hash bits. hbits=0 means no hash part.
** hbits=1 creates 2 hash slots, hbits=2 creates 4 hash slots and so on.
*/
GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits)
{
GCtab *t = newtab(L, asize, hbits);
clearapart(t);
if (t->hmask > 0) clearhpart(t);
return t;
}
/* The API of this function conforms to lua_createtable(). */
GCtab *lj_tab_new_ah(lua_State *L, int32_t a, int32_t h)
{
return lj_tab_new(L, (uint32_t)(a > 0 ? a+1 : 0), hsize2hbits(h));
}
#if LJ_HASJIT
GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize)
{
GCtab *t = newtab(L, ahsize & 0xffffff, ahsize >> 24);
clearapart(t);
if (t->hmask > 0) clearhpart(t);
return t;
}
#endif
/* Duplicate a table. */
GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt)
{
GCtab *t;
uint32_t asize, hmask;
t = newtab(L, kt->asize, kt->hmask > 0 ? lj_fls(kt->hmask)+1 : 0);
lua_assert(kt->asize == t->asize && kt->hmask == t->hmask);
t->nomm = 0; /* Keys with metamethod names may be present. */
asize = kt->asize;
if (asize > 0) {
TValue *array = tvref(t->array);
TValue *karray = tvref(kt->array);
if (asize < 64) { /* An inlined loop beats memcpy for < 512 bytes. */
uint32_t i;
for (i = 0; i < asize; i++)
copyTV(L, &array[i], &karray[i]);
} else {
memcpy(array, karray, asize*sizeof(TValue));
}
}
hmask = kt->hmask;
if (hmask > 0) {
uint32_t i;
Node *node = noderef(t->node);
Node *knode = noderef(kt->node);
ptrdiff_t d = (char *)node - (char *)knode;
setfreetop(t, node, (Node *)((char *)getfreetop(kt, knode) + d));
for (i = 0; i <= hmask; i++) {
Node *kn = &knode[i];
Node *n = &node[i];
Node *next = nextnode(kn);
/* Don't use copyTV here, since it asserts on a copy of a dead key. */
n->val = kn->val; n->key = kn->key;
setmref(n->next, next == NULL? next : (Node *)((char *)next + d));
}
}
return t;
}
/* Clear a table. */
void LJ_FASTCALL lj_tab_clear(GCtab *t)
{
clearapart(t);
if (t->hmask > 0) {
Node *node = noderef(t->node);
setfreetop(t, node, &node[t->hmask+1]);
clearhpart(t);
}
}
/* Free a table. */
void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t)
{
if (t->hmask > 0)
lj_mem_freevec(g, noderef(t->node), t->hmask+1, Node);
if (t->asize > 0 && LJ_MAX_COLOSIZE != 0 && t->colo <= 0)
lj_mem_freevec(g, tvref(t->array), t->asize, TValue);
if (LJ_MAX_COLOSIZE != 0 && t->colo)
lj_mem_free(g, t, sizetabcolo((uint32_t)t->colo & 0x7f));
else
lj_mem_freet(g, t);
}
/* -- Table resizing ------------------------------------------------------ */
/* Resize a table to fit the new array/hash part sizes. */
void lj_tab_resize(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits)
{
Node *oldnode = noderef(t->node);
uint32_t oldasize = t->asize;
uint32_t oldhmask = t->hmask;
if (asize > oldasize) { /* Array part grows? */
TValue *array;
uint32_t i;
if (asize > LJ_MAX_ASIZE)
lj_err_msg(L, LJ_ERR_TABOV);
if (LJ_MAX_COLOSIZE != 0 && t->colo > 0) {
/* A colocated array must be separated and copied. */
TValue *oarray = tvref(t->array);
array = lj_mem_newvec(L, asize, TValue);
t->colo = (int8_t)(t->colo | 0x80); /* Mark as separated (colo < 0). */
for (i = 0; i < oldasize; i++)
copyTV(L, &array[i], &oarray[i]);
} else {
array = (TValue *)lj_mem_realloc(L, tvref(t->array),
oldasize*sizeof(TValue), asize*sizeof(TValue));
}
setmref(t->array, array);
t->asize = asize;
for (i = oldasize; i < asize; i++) /* Clear newly allocated slots. */
setnilV(&array[i]);
}
/* Create new (empty) hash part. */
if (hbits) {
newhpart(L, t, hbits);
clearhpart(t);
} else {
global_State *g = G(L);
setmref(t->node, &g->nilnode);
#if LJ_GC64
setmref(t->freetop, &g->nilnode);
#endif
t->hmask = 0;
}
if (asize < oldasize) { /* Array part shrinks? */
TValue *array = tvref(t->array);
uint32_t i;
t->asize = asize; /* Note: This 'shrinks' even colocated arrays. */
for (i = asize; i < oldasize; i++) /* Reinsert old array values. */
if (!tvisnil(&array[i]))
copyTV(L, lj_tab_setinth(L, t, (int32_t)i), &array[i]);
/* Physically shrink only separated arrays. */
if (LJ_MAX_COLOSIZE != 0 && t->colo <= 0)
setmref(t->array, lj_mem_realloc(L, array,
oldasize*sizeof(TValue), asize*sizeof(TValue)));
}
if (oldhmask > 0) { /* Reinsert pairs from old hash part. */
global_State *g;
uint32_t i;
for (i = 0; i <= oldhmask; i++) {
Node *n = &oldnode[i];
if (!tvisnil(&n->val))
copyTV(L, lj_tab_set(L, t, &n->key), &n->val);
}
g = G(L);
lj_mem_freevec(g, oldnode, oldhmask+1, Node);
}
}
static uint32_t countint(cTValue *key, uint32_t *bins)
{
lua_assert(!tvisint(key));
if (tvisnum(key)) {
lua_Number nk = numV(key);
int32_t k = lj_num2int(nk);
if ((uint32_t)k < LJ_MAX_ASIZE && nk == (lua_Number)k) {
bins[(k > 2 ? lj_fls((uint32_t)(k-1)) : 0)]++;
return 1;
}
}
return 0;
}
static uint32_t countarray(const GCtab *t, uint32_t *bins)
{
uint32_t na, b, i;
if (t->asize == 0) return 0;
for (na = i = b = 0; b < LJ_MAX_ABITS; b++) {
uint32_t n, top = 2u << b;
TValue *array;
if (top >= t->asize) {
top = t->asize-1;
if (i > top)
break;
}
array = tvref(t->array);
for (n = 0; i <= top; i++)
if (!tvisnil(&array[i]))
n++;
bins[b] += n;
na += n;
}
return na;
}
static uint32_t counthash(const GCtab *t, uint32_t *bins, uint32_t *narray)
{
uint32_t total, na, i, hmask = t->hmask;
Node *node = noderef(t->node);
for (total = na = 0, i = 0; i <= hmask; i++) {
Node *n = &node[i];
if (!tvisnil(&n->val)) {
na += countint(&n->key, bins);
total++;
}
}
*narray += na;
return total;
}
static uint32_t bestasize(uint32_t bins[], uint32_t *narray)
{
uint32_t b, sum, na = 0, sz = 0, nn = *narray;
for (b = 0, sum = 0; 2*nn > (1u<<b) && sum != nn; b++)
if (bins[b] > 0 && 2*(sum += bins[b]) > (1u<<b)) {
sz = (2u<<b)+1;
na = sum;
}
*narray = sz;
return na;
}
static void rehashtab(lua_State *L, GCtab *t, cTValue *ek)
{
uint32_t bins[LJ_MAX_ABITS];
uint32_t total, asize, na, i;
for (i = 0; i < LJ_MAX_ABITS; i++) bins[i] = 0;
asize = countarray(t, bins);
total = 1 + asize;
total += counthash(t, bins, &asize);
asize += countint(ek, bins);
na = bestasize(bins, &asize);
total -= na;
lj_tab_resize(L, t, asize, hsize2hbits(total));
}
#if LJ_HASFFI
void lj_tab_rehash(lua_State *L, GCtab *t)
{
rehashtab(L, t, niltv(L));
}
#endif
void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize)
{
lj_tab_resize(L, t, nasize+1, t->hmask > 0 ? lj_fls(t->hmask)+1 : 0);
}
/* -- Table getters ------------------------------------------------------- */
cTValue * LJ_FASTCALL lj_tab_getinth(GCtab *t, int32_t key)
{
TValue k;
Node *n;
k.n = (lua_Number)key;
n = hashnum(t, &k);
do {
if (tvisnum(&n->key) && n->key.n == k.n)
return &n->val;
} while ((n = nextnode(n)));
return NULL;
}
cTValue *lj_tab_getstr(GCtab *t, GCstr *key)
{
Node *n = hashstr(t, key);
do {
if (tvisstr(&n->key) && strV(&n->key) == key)
return &n->val;
} while ((n = nextnode(n)));
return NULL;
}
cTValue *lj_tab_get(lua_State *L, GCtab *t, cTValue *key)
{
if (tvisstr(key)) {
cTValue *tv = lj_tab_getstr(t, strV(key));
if (tv)
return tv;
} else if (tvisint(key)) {
cTValue *tv = lj_tab_getint(t, intV(key));
if (tv)
return tv;
} else if (tvisnum(key)) {
lua_Number nk = numV(key);
int32_t k = lj_num2int(nk);
if (nk == (lua_Number)k) {
cTValue *tv = lj_tab_getint(t, k);
if (tv)
return tv;
} else {
goto genlookup; /* Else use the generic lookup. */
}
} else if (!tvisnil(key)) {
Node *n;
genlookup:
n = hashkey(t, key);
do {
if (lj_obj_equal(&n->key, key))
return &n->val;
} while ((n = nextnode(n)));
}
return niltv(L);
}
/* -- Table setters ------------------------------------------------------- */
/* Insert new key. Use Brent's variation to optimize the chain length. */
TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key)
{
Node *n = hashkey(t, key);
if (!tvisnil(&n->val) || t->hmask == 0) {
Node *nodebase = noderef(t->node);
Node *collide, *freenode = getfreetop(t, nodebase);
lua_assert(freenode >= nodebase && freenode <= nodebase+t->hmask+1);
do {
if (freenode == nodebase) { /* No free node found? */
rehashtab(L, t, key); /* Rehash table. */
return lj_tab_set(L, t, key); /* Retry key insertion. */
}
} while (!tvisnil(&(--freenode)->key));
setfreetop(t, nodebase, freenode);
lua_assert(freenode != &G(L)->nilnode);
collide = hashkey(t, &n->key);
if (collide != n) { /* Colliding node not the main node? */
while (noderef(collide->next) != n) /* Find predecessor. */
collide = nextnode(collide);
setmref(collide->next, freenode); /* Relink chain. */
/* Copy colliding node into free node and free main node. */
freenode->val = n->val;
freenode->key = n->key;
freenode->next = n->next;
setmref(n->next, NULL);
setnilV(&n->val);
/* Rechain pseudo-resurrected string keys with colliding hashes. */
while (nextnode(freenode)) {
Node *nn = nextnode(freenode);
if (tvisstr(&nn->key) && !tvisnil(&nn->val) &&
hashstr(t, strV(&nn->key)) == n) {
freenode->next = nn->next;
nn->next = n->next;
setmref(n->next, nn);
} else {
freenode = nn;
}
}
} else { /* Otherwise use free node. */
setmrefr(freenode->next, n->next); /* Insert into chain. */
setmref(n->next, freenode);
n = freenode;
}
}
n->key.u64 = key->u64;
if (LJ_UNLIKELY(tvismzero(&n->key)))
n->key.u64 = 0;
lj_gc_anybarriert(L, t);
lua_assert(tvisnil(&n->val));
return &n->val;
}
TValue *lj_tab_setinth(lua_State *L, GCtab *t, int32_t key)
{
TValue k;
Node *n;
k.n = (lua_Number)key;
n = hashnum(t, &k);
do {
if (tvisnum(&n->key) && n->key.n == k.n)
return &n->val;
} while ((n = nextnode(n)));
return lj_tab_newkey(L, t, &k);
}
TValue *lj_tab_setstr(lua_State *L, GCtab *t, GCstr *key)
{
TValue k;
Node *n = hashstr(t, key);
do {
if (tvisstr(&n->key) && strV(&n->key) == key)
return &n->val;
} while ((n = nextnode(n)));
setstrV(L, &k, key);
return lj_tab_newkey(L, t, &k);
}
TValue *lj_tab_set(lua_State *L, GCtab *t, cTValue *key)
{
Node *n;
t->nomm = 0; /* Invalidate negative metamethod cache. */
if (tvisstr(key)) {
return lj_tab_setstr(L, t, strV(key));
} else if (tvisint(key)) {
return lj_tab_setint(L, t, intV(key));
} else if (tvisnum(key)) {
lua_Number nk = numV(key);
int32_t k = lj_num2int(nk);
if (nk == (lua_Number)k)
return lj_tab_setint(L, t, k);
if (tvisnan(key))
lj_err_msg(L, LJ_ERR_NANIDX);
/* Else use the generic lookup. */
} else if (tvisnil(key)) {
lj_err_msg(L, LJ_ERR_NILIDX);
}
n = hashkey(t, key);
do {
if (lj_obj_equal(&n->key, key))
return &n->val;
} while ((n = nextnode(n)));
return lj_tab_newkey(L, t, key);
}
/* -- Table traversal ----------------------------------------------------- */
/* Get the traversal index of a key. */
static uint32_t keyindex(lua_State *L, GCtab *t, cTValue *key)
{
TValue tmp;
if (tvisint(key)) {
int32_t k = intV(key);
if ((uint32_t)k < t->asize)
return (uint32_t)k; /* Array key indexes: [0..t->asize-1] */
setnumV(&tmp, (lua_Number)k);
key = &tmp;
} else if (tvisnum(key)) {
lua_Number nk = numV(key);
int32_t k = lj_num2int(nk);
if ((uint32_t)k < t->asize && nk == (lua_Number)k)
return (uint32_t)k; /* Array key indexes: [0..t->asize-1] */
}
if (!tvisnil(key)) {
Node *n = hashkey(t, key);
do {
if (lj_obj_equal(&n->key, key))
return t->asize + (uint32_t)(n - noderef(t->node));
/* Hash key indexes: [t->asize..t->asize+t->nmask] */
} while ((n = nextnode(n)));
if (key->u32.hi == 0xfffe7fff) /* ITERN was despecialized while running. */
return key->u32.lo - 1;
lj_err_msg(L, LJ_ERR_NEXTIDX);
return 0; /* unreachable */
}
return ~0u; /* A nil key starts the traversal. */
}
/* Advance to the next step in a table traversal. */
int lj_tab_next(lua_State *L, GCtab *t, TValue *key)
{
uint32_t i = keyindex(L, t, key); /* Find predecessor key index. */
for (i++; i < t->asize; i++) /* First traverse the array keys. */
if (!tvisnil(arrayslot(t, i))) {
setintV(key, i);
copyTV(L, key+1, arrayslot(t, i));
return 1;
}
for (i -= t->asize; i <= t->hmask; i++) { /* Then traverse the hash keys. */
Node *n = &noderef(t->node)[i];
if (!tvisnil(&n->val)) {
copyTV(L, key, &n->key);
copyTV(L, key+1, &n->val);
return 1;
}
}
return 0; /* End of traversal. */
}
/* -- Table length calculation -------------------------------------------- */
static MSize unbound_search(GCtab *t, MSize j)
{
cTValue *tv;
MSize i = j; /* i is zero or a present index */
j++;
/* find `i' and `j' such that i is present and j is not */
while ((tv = lj_tab_getint(t, (int32_t)j)) && !tvisnil(tv)) {
i = j;
j *= 2;
if (j > (MSize)(INT_MAX-2)) { /* overflow? */
/* table was built with bad purposes: resort to linear search */
i = 1;
while ((tv = lj_tab_getint(t, (int32_t)i)) && !tvisnil(tv)) i++;
return i - 1;
}
}
/* now do a binary search between them */
while (j - i > 1) {
MSize m = (i+j)/2;
cTValue *tvb = lj_tab_getint(t, (int32_t)m);
if (tvb && !tvisnil(tvb)) i = m; else j = m;
}
return i;
}
/*
** 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).
*/
MSize LJ_FASTCALL lj_tab_len(GCtab *t)
{
MSize j = (MSize)t->asize;
if (j > 1 && tvisnil(arrayslot(t, j-1))) {
MSize i = 1;
while (j - i > 1) {
MSize m = (i+j)/2;
if (tvisnil(arrayslot(t, m-1))) j = m; else i = m;
}
return i-1;
}
if (j) j--;
if (t->hmask <= 0)
return j;
return unbound_search(t, j);
}
| xLua/build/luajit-2.1.0b2/src/lj_tab.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_tab.c",
"repo_id": "xLua",
"token_count": 8749
} | 2,114 |
/*
** Math helper functions for assembler VM.
** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_vmmath_c
#define LUA_CORE
#include <errno.h>
#include <math.h>
#include "lj_obj.h"
#include "lj_ir.h"
#include "lj_vm.h"
/* -- Wrapper functions --------------------------------------------------- */
#if LJ_TARGET_X86 && __ELF__ && __PIC__
/* Wrapper functions to deal with the ELF/x86 PIC disaster. */
LJ_FUNCA double lj_wrap_log(double x) { return log(x); }
LJ_FUNCA double lj_wrap_log10(double x) { return log10(x); }
LJ_FUNCA double lj_wrap_exp(double x) { return exp(x); }
LJ_FUNCA double lj_wrap_sin(double x) { return sin(x); }
LJ_FUNCA double lj_wrap_cos(double x) { return cos(x); }
LJ_FUNCA double lj_wrap_tan(double x) { return tan(x); }
LJ_FUNCA double lj_wrap_asin(double x) { return asin(x); }
LJ_FUNCA double lj_wrap_acos(double x) { return acos(x); }
LJ_FUNCA double lj_wrap_atan(double x) { return atan(x); }
LJ_FUNCA double lj_wrap_sinh(double x) { return sinh(x); }
LJ_FUNCA double lj_wrap_cosh(double x) { return cosh(x); }
LJ_FUNCA double lj_wrap_tanh(double x) { return tanh(x); }
LJ_FUNCA double lj_wrap_atan2(double x, double y) { return atan2(x, y); }
LJ_FUNCA double lj_wrap_pow(double x, double y) { return pow(x, y); }
LJ_FUNCA double lj_wrap_fmod(double x, double y) { return fmod(x, y); }
#endif
/* -- Helper functions for generated machine code ------------------------- */
double lj_vm_foldarith(double x, double y, int op)
{
switch (op) {
case IR_ADD - IR_ADD: return x+y; break;
case IR_SUB - IR_ADD: return x-y; break;
case IR_MUL - IR_ADD: return x*y; break;
case IR_DIV - IR_ADD: return x/y; break;
case IR_MOD - IR_ADD: return x-lj_vm_floor(x/y)*y; break;
case IR_POW - IR_ADD: return pow(x, y); break;
case IR_NEG - IR_ADD: return -x; break;
case IR_ABS - IR_ADD: return fabs(x); break;
#if LJ_HASJIT
case IR_ATAN2 - IR_ADD: return atan2(x, y); break;
case IR_LDEXP - IR_ADD: return ldexp(x, (int)y); break;
case IR_MIN - IR_ADD: return x > y ? y : x; break;
case IR_MAX - IR_ADD: return x < y ? y : x; break;
#endif
default: return x;
}
}
#if (LJ_HASJIT && !(LJ_TARGET_ARM || LJ_TARGET_ARM64 || LJ_TARGET_PPC)) || LJ_TARGET_MIPS
int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b)
{
uint32_t y, ua, ub;
lua_assert(b != 0); /* This must be checked before using this function. */
ua = a < 0 ? (uint32_t)-a : (uint32_t)a;
ub = b < 0 ? (uint32_t)-b : (uint32_t)b;
y = ua % ub;
if (y != 0 && (a^b) < 0) y = y - ub;
if (((int32_t)y^b) < 0) y = (uint32_t)-(int32_t)y;
return (int32_t)y;
}
#endif
#if LJ_HASJIT
#ifdef LUAJIT_NO_LOG2
double lj_vm_log2(double a)
{
return log(a) * 1.4426950408889634074;
}
#endif
#ifdef LUAJIT_NO_EXP2
double lj_vm_exp2(double a)
{
return exp(a * 0.6931471805599453);
}
#endif
#if !LJ_TARGET_X86ORX64
/* Unsigned x^k. */
static double lj_vm_powui(double x, uint32_t k)
{
double y;
lua_assert(k != 0);
for (; (k & 1) == 0; k >>= 1) x *= x;
y = x;
if ((k >>= 1) != 0) {
for (;;) {
x *= x;
if (k == 1) break;
if (k & 1) y *= x;
k >>= 1;
}
y *= x;
}
return y;
}
/* Signed x^k. */
double lj_vm_powi(double x, int32_t k)
{
if (k > 1)
return lj_vm_powui(x, (uint32_t)k);
else if (k == 1)
return x;
else if (k == 0)
return 1.0;
else
return 1.0 / lj_vm_powui(x, (uint32_t)-k);
}
#endif
/* Computes fpm(x) for extended math functions. */
double lj_vm_foldfpm(double x, int fpm)
{
switch (fpm) {
case IRFPM_FLOOR: return lj_vm_floor(x);
case IRFPM_CEIL: return lj_vm_ceil(x);
case IRFPM_TRUNC: return lj_vm_trunc(x);
case IRFPM_SQRT: return sqrt(x);
case IRFPM_EXP: return exp(x);
case IRFPM_EXP2: return lj_vm_exp2(x);
case IRFPM_LOG: return log(x);
case IRFPM_LOG2: return lj_vm_log2(x);
case IRFPM_LOG10: return log10(x);
case IRFPM_SIN: return sin(x);
case IRFPM_COS: return cos(x);
case IRFPM_TAN: return tan(x);
default: lua_assert(0);
}
return 0;
}
#if LJ_HASFFI
int lj_vm_errno(void)
{
return errno;
}
#endif
#endif
| xLua/build/luajit-2.1.0b2/src/lj_vmmath.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/lj_vmmath.c",
"repo_id": "xLua",
"token_count": 1887
} | 2,115 |
|// Low-level VM code for PowerPC 32 bit or 32on64 bit mode.
|// Bytecode interpreter, fast functions and helper functions.
|// Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
|
|.arch ppc
|.section code_op, code_sub
|
|.actionlist build_actionlist
|.globals GLOB_
|.globalnames globnames
|.externnames extnames
|
|// Note: The ragged indentation of the instructions is intentional.
|// The starting columns indicate data dependencies.
|
|//-----------------------------------------------------------------------
|
|// DynASM defines used by the PPC port:
|//
|// P64 64 bit pointers (only for GPR64 testing).
|// Note: see vm_ppc64.dasc for a full PPC64 _LP64 port.
|// GPR64 64 bit registers (but possibly 32 bit pointers, e.g. PS3).
|// Affects reg saves, stack layout, carry/overflow/dot flags etc.
|// FRAME32 Use 32 bit frame layout, even with GPR64 (Xbox 360).
|// TOC Need table of contents (64 bit or 32 bit variant, e.g. PS3).
|// Function pointers are really a struct: code, TOC, env (optional).
|// TOCENV Function pointers have an environment pointer, too (not on PS3).
|// PPE Power Processor Element of Cell (PS3) or Xenon (Xbox 360).
|// Must avoid (slow) micro-coded instructions.
|
|.if P64
|.define TOC, 1
|.define TOCENV, 1
|.macro lpx, a, b, c; ldx a, b, c; .endmacro
|.macro lp, a, b; ld a, b; .endmacro
|.macro stp, a, b; std a, b; .endmacro
|.define decode_OPP, decode_OP8
|.if FFI
|// Missing: Calling conventions, 64 bit regs, TOC.
|.error lib_ffi not yet implemented for PPC64
|.endif
|.else
|.macro lpx, a, b, c; lwzx a, b, c; .endmacro
|.macro lp, a, b; lwz a, b; .endmacro
|.macro stp, a, b; stw a, b; .endmacro
|.define decode_OPP, decode_OP4
|.endif
|
|// Convenience macros for TOC handling.
|.if TOC
|// Linker needs a TOC patch area for every external call relocation.
|.macro blex, target; bl extern target@plt; nop; .endmacro
|.macro .toc, a, b; a, b; .endmacro
|.if P64
|.define TOC_OFS, 8
|.define ENV_OFS, 16
|.else
|.define TOC_OFS, 4
|.define ENV_OFS, 8
|.endif
|.else // No TOC.
|.macro blex, target; bl extern target@plt; .endmacro
|.macro .toc, a, b; .endmacro
|.endif
|.macro .tocenv, a, b; .if TOCENV; a, b; .endif; .endmacro
|
|.macro .gpr64, a, b; .if GPR64; a, b; .endif; .endmacro
|
|.macro andix., y, a, i
|.if PPE
| rlwinm y, a, 0, 31-lj_fls(i), 31-lj_ffs(i)
| cmpwi y, 0
|.else
| andi. y, a, i
|.endif
|.endmacro
|
|.macro clrso, reg
|.if PPE
| li reg, 0
| mtxer reg
|.else
| mcrxr cr0
|.endif
|.endmacro
|
|.macro checkov, reg, noov
|.if PPE
| mfxer reg
| add reg, reg, reg
| cmpwi reg, 0
| li reg, 0
| mtxer reg
| bgey noov
|.else
| mcrxr cr0
| bley noov
|.endif
|.endmacro
|
|//-----------------------------------------------------------------------
|
|// Fixed register assignments for the interpreter.
|// Don't use: r1 = sp, r2 and r13 = reserved (TOC, TLS or SDATA)
|
|// The following must be C callee-save (but BASE is often refetched).
|.define BASE, r14 // Base of current Lua stack frame.
|.define KBASE, r15 // Constants of current Lua function.
|.define PC, r16 // Next PC.
|.define DISPATCH, r17 // Opcode dispatch table.
|.define LREG, r18 // Register holding lua_State (also in SAVE_L).
|.define MULTRES, r19 // Size of multi-result: (nresults+1)*8.
|.define JGL, r31 // On-trace: global_State + 32768.
|
|// Constants for type-comparisons, stores and conversions. C callee-save.
|.define TISNUM, r22
|.define TISNIL, r23
|.define ZERO, r24
|.define TOBIT, f30 // 2^52 + 2^51.
|.define TONUM, f31 // 2^52 + 2^51 + 2^31.
|
|// The following temporaries are not saved across C calls, except for RA.
|.define RA, r20 // Callee-save.
|.define RB, r10
|.define RC, r11
|.define RD, r12
|.define INS, r7 // Overlaps CARG5.
|
|.define TMP0, r0
|.define TMP1, r8
|.define TMP2, r9
|.define TMP3, r6 // Overlaps CARG4.
|
|// Saved temporaries.
|.define SAVE0, r21
|
|// Calling conventions.
|.define CARG1, r3
|.define CARG2, r4
|.define CARG3, r5
|.define CARG4, r6 // Overlaps TMP3.
|.define CARG5, r7 // Overlaps INS.
|
|.define FARG1, f1
|.define FARG2, f2
|
|.define CRET1, r3
|.define CRET2, r4
|
|.define TOCREG, r2 // TOC register (only used by C code).
|.define ENVREG, r11 // Environment pointer (nested C functions).
|
|// Stack layout while in interpreter. Must match with lj_frame.h.
|.if GPR64
|.if FRAME32
|
|// 456(sp) // \ 32/64 bit C frame info
|.define TONUM_LO, 452(sp) // |
|.define TONUM_HI, 448(sp) // |
|.define TMPD_LO, 444(sp) // |
|.define TMPD_HI, 440(sp) // |
|.define SAVE_CR, 432(sp) // | 64 bit CR save.
|.define SAVE_ERRF, 424(sp) // > Parameter save area.
|.define SAVE_NRES, 420(sp) // |
|.define SAVE_L, 416(sp) // |
|.define SAVE_PC, 412(sp) // |
|.define SAVE_MULTRES, 408(sp) // |
|.define SAVE_CFRAME, 400(sp) // / 64 bit C frame chain.
|// 392(sp) // Reserved.
|.define CFRAME_SPACE, 384 // Delta for sp.
|// Back chain for sp: 384(sp) <-- sp entering interpreter
|.define SAVE_LR, 376(sp) // 32 bit LR stored in hi-part.
|.define SAVE_GPR_, 232 // .. 232+18*8: 64 bit GPR saves.
|.define SAVE_FPR_, 88 // .. 88+18*8: 64 bit FPR saves.
|// 80(sp) // Needed for 16 byte stack frame alignment.
|// 16(sp) // Callee parameter save area (ABI mandated).
|// 8(sp) // Reserved
|// Back chain for sp: 0(sp) <-- sp while in interpreter
|// 32 bit sp stored in hi-part of 0(sp).
|
|.define TMPD_BLO, 447(sp)
|.define TMPD, TMPD_HI
|.define TONUM_D, TONUM_HI
|
|.else
|
|// 508(sp) // \ 32 bit C frame info.
|.define SAVE_ERRF, 472(sp) // |
|.define SAVE_NRES, 468(sp) // |
|.define SAVE_L, 464(sp) // > Parameter save area.
|.define SAVE_PC, 460(sp) // |
|.define SAVE_MULTRES, 456(sp) // |
|.define SAVE_CFRAME, 448(sp) // / 64 bit C frame chain.
|.define SAVE_LR, 416(sp)
|.define CFRAME_SPACE, 400 // Delta for sp.
|// Back chain for sp: 400(sp) <-- sp entering interpreter
|.define SAVE_FPR_, 256 // .. 256+18*8: 64 bit FPR saves.
|.define SAVE_GPR_, 112 // .. 112+18*8: 64 bit GPR saves.
|// 48(sp) // Callee parameter save area (ABI mandated).
|.define SAVE_TOC, 40(sp) // TOC save area.
|.define TMPD_LO, 36(sp) // \ Link editor temp (ABI mandated).
|.define TMPD_HI, 32(sp) // /
|.define TONUM_LO, 28(sp) // \ Compiler temp (ABI mandated).
|.define TONUM_HI, 24(sp) // /
|// Next frame lr: 16(sp)
|.define SAVE_CR, 8(sp) // 64 bit CR save.
|// Back chain for sp: 0(sp) <-- sp while in interpreter
|
|.define TMPD_BLO, 39(sp)
|.define TMPD, TMPD_HI
|.define TONUM_D, TONUM_HI
|
|.endif
|.else
|
|.define SAVE_LR, 276(sp)
|.define CFRAME_SPACE, 272 // Delta for sp.
|// Back chain for sp: 272(sp) <-- sp entering interpreter
|.define SAVE_FPR_, 128 // .. 128+18*8: 64 bit FPR saves.
|.define SAVE_GPR_, 56 // .. 56+18*4: 32 bit GPR saves.
|.define SAVE_CR, 52(sp) // 32 bit CR save.
|.define SAVE_ERRF, 48(sp) // 32 bit C frame info.
|.define SAVE_NRES, 44(sp)
|.define SAVE_CFRAME, 40(sp)
|.define SAVE_L, 36(sp)
|.define SAVE_PC, 32(sp)
|.define SAVE_MULTRES, 28(sp)
|.define UNUSED1, 24(sp)
|.define TMPD_LO, 20(sp)
|.define TMPD_HI, 16(sp)
|.define TONUM_LO, 12(sp)
|.define TONUM_HI, 8(sp)
|// Next frame lr: 4(sp)
|// Back chain for sp: 0(sp) <-- sp while in interpreter
|
|.define TMPD_BLO, 23(sp)
|.define TMPD, TMPD_HI
|.define TONUM_D, TONUM_HI
|
|.endif
|
|.macro save_, reg
|.if GPR64
| std r..reg, SAVE_GPR_+(reg-14)*8(sp)
|.else
| stw r..reg, SAVE_GPR_+(reg-14)*4(sp)
|.endif
| stfd f..reg, SAVE_FPR_+(reg-14)*8(sp)
|.endmacro
|.macro rest_, reg
|.if GPR64
| ld r..reg, SAVE_GPR_+(reg-14)*8(sp)
|.else
| lwz r..reg, SAVE_GPR_+(reg-14)*4(sp)
|.endif
| lfd f..reg, SAVE_FPR_+(reg-14)*8(sp)
|.endmacro
|
|.macro saveregs
|.if GPR64 and not FRAME32
| stdu sp, -CFRAME_SPACE(sp)
|.else
| stwu sp, -CFRAME_SPACE(sp)
|.endif
| save_ 14; save_ 15; save_ 16
| mflr r0
| save_ 17; save_ 18; save_ 19; save_ 20; save_ 21; save_ 22
|.if GPR64 and not FRAME32
| std r0, SAVE_LR
|.else
| stw r0, SAVE_LR
|.endif
| save_ 23; save_ 24; save_ 25
| mfcr r0
| save_ 26; save_ 27; save_ 28; save_ 29; save_ 30; save_ 31
|.if GPR64
| std r0, SAVE_CR
|.else
| stw r0, SAVE_CR
|.endif
| .toc std TOCREG, SAVE_TOC
|.endmacro
|
|.macro restoreregs
|.if GPR64 and not FRAME32
| ld r0, SAVE_LR
|.else
| lwz r0, SAVE_LR
|.endif
|.if GPR64
| ld r12, SAVE_CR
|.else
| lwz r12, SAVE_CR
|.endif
| rest_ 14; rest_ 15; rest_ 16; rest_ 17; rest_ 18; rest_ 19
| mtlr r0;
|.if PPE; mtocrf 0x20, r12; .else; mtcrf 0x38, r12; .endif
| rest_ 20; rest_ 21; rest_ 22; rest_ 23; rest_ 24; rest_ 25
|.if PPE; mtocrf 0x10, r12; .endif
| rest_ 26; rest_ 27; rest_ 28; rest_ 29; rest_ 30; rest_ 31
|.if PPE; mtocrf 0x08, r12; .endif
| addi sp, sp, CFRAME_SPACE
|.endmacro
|
|// Type definitions. Some of these are only used for documentation.
|.type L, lua_State, LREG
|.type GL, global_State
|.type TVALUE, TValue
|.type GCOBJ, GCobj
|.type STR, GCstr
|.type TAB, GCtab
|.type LFUNC, GCfuncL
|.type CFUNC, GCfuncC
|.type PROTO, GCproto
|.type UPVAL, GCupval
|.type NODE, Node
|.type NARGS8, int
|.type TRACE, GCtrace
|.type SBUF, SBuf
|
|//-----------------------------------------------------------------------
|
|// Trap for not-yet-implemented parts.
|.macro NYI; tw 4, sp, sp; .endmacro
|
|// int/FP conversions.
|.macro tonum_i, freg, reg
| xoris reg, reg, 0x8000
| stw reg, TONUM_LO
| lfd freg, TONUM_D
| fsub freg, freg, TONUM
|.endmacro
|
|.macro tonum_u, freg, reg
| stw reg, TONUM_LO
| lfd freg, TONUM_D
| fsub freg, freg, TOBIT
|.endmacro
|
|.macro toint, reg, freg, tmpfreg
| fctiwz tmpfreg, freg
| stfd tmpfreg, TMPD
| lwz reg, TMPD_LO
|.endmacro
|
|.macro toint, reg, freg
| toint reg, freg, freg
|.endmacro
|
|//-----------------------------------------------------------------------
|
|// Access to frame relative to BASE.
|.define FRAME_PC, -8
|.define FRAME_FUNC, -4
|
|// Instruction decode.
|.macro decode_OP4, dst, ins; rlwinm dst, ins, 2, 22, 29; .endmacro
|.macro decode_OP8, dst, ins; rlwinm dst, ins, 3, 21, 28; .endmacro
|.macro decode_RA8, dst, ins; rlwinm dst, ins, 27, 21, 28; .endmacro
|.macro decode_RB8, dst, ins; rlwinm dst, ins, 11, 21, 28; .endmacro
|.macro decode_RC8, dst, ins; rlwinm dst, ins, 19, 21, 28; .endmacro
|.macro decode_RD8, dst, ins; rlwinm dst, ins, 19, 13, 28; .endmacro
|
|.macro decode_OP1, dst, ins; rlwinm dst, ins, 0, 24, 31; .endmacro
|.macro decode_RD4, dst, ins; rlwinm dst, ins, 18, 14, 29; .endmacro
|
|// Instruction fetch.
|.macro ins_NEXT1
| lwz INS, 0(PC)
| addi PC, PC, 4
|.endmacro
|// Instruction decode+dispatch. Note: optimized for e300!
|.macro ins_NEXT2
| decode_OPP TMP1, INS
| lpx TMP0, DISPATCH, TMP1
| mtctr TMP0
| decode_RB8 RB, INS
| decode_RD8 RD, INS
| decode_RA8 RA, INS
| decode_RC8 RC, INS
| bctr
|.endmacro
|.macro ins_NEXT
| ins_NEXT1
| ins_NEXT2
|.endmacro
|
|// Instruction footer.
|.if 1
| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
| .define ins_next, ins_NEXT
| .define ins_next_, ins_NEXT
| .define ins_next1, ins_NEXT1
| .define ins_next2, ins_NEXT2
|.else
| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
| // Affects only certain kinds of benchmarks (and only with -j off).
| .macro ins_next
| b ->ins_next
| .endmacro
| .macro ins_next1
| .endmacro
| .macro ins_next2
| b ->ins_next
| .endmacro
| .macro ins_next_
| ->ins_next:
| ins_NEXT
| .endmacro
|.endif
|
|// Call decode and dispatch.
|.macro ins_callt
| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
| lwz PC, LFUNC:RB->pc
| lwz INS, 0(PC)
| addi PC, PC, 4
| decode_OPP TMP1, INS
| decode_RA8 RA, INS
| lpx TMP0, DISPATCH, TMP1
| add RA, RA, BASE
| mtctr TMP0
| bctr
|.endmacro
|
|.macro ins_call
| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, PC = caller PC
| stw PC, FRAME_PC(BASE)
| ins_callt
|.endmacro
|
|//-----------------------------------------------------------------------
|
|// Macros to test operand types.
|.macro checknum, reg; cmplw reg, TISNUM; .endmacro
|.macro checknum, cr, reg; cmplw cr, reg, TISNUM; .endmacro
|.macro checkstr, reg; cmpwi reg, LJ_TSTR; .endmacro
|.macro checktab, reg; cmpwi reg, LJ_TTAB; .endmacro
|.macro checkfunc, reg; cmpwi reg, LJ_TFUNC; .endmacro
|.macro checknil, reg; cmpwi reg, LJ_TNIL; .endmacro
|
|.macro branch_RD
| srwi TMP0, RD, 1
| addis PC, PC, -(BCBIAS_J*4 >> 16)
| add PC, PC, TMP0
|.endmacro
|
|// Assumes DISPATCH is relative to GL.
#define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field))
#define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field))
|
#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
|
|.macro hotcheck, delta, target
| rlwinm TMP1, PC, 31, 25, 30
| addi TMP1, TMP1, GG_DISP2HOT
| lhzx TMP2, DISPATCH, TMP1
| addic. TMP2, TMP2, -delta
| sthx TMP2, DISPATCH, TMP1
| blt target
|.endmacro
|
|.macro hotloop
| hotcheck HOTCOUNT_LOOP, ->vm_hotloop
|.endmacro
|
|.macro hotcall
| hotcheck HOTCOUNT_CALL, ->vm_hotcall
|.endmacro
|
|// Set current VM state. Uses TMP0.
|.macro li_vmstate, st; li TMP0, ~LJ_VMST_..st; .endmacro
|.macro st_vmstate; stw TMP0, DISPATCH_GL(vmstate)(DISPATCH); .endmacro
|
|// Move table write barrier back. Overwrites mark and tmp.
|.macro barrierback, tab, mark, tmp
| lwz tmp, DISPATCH_GL(gc.grayagain)(DISPATCH)
| // Assumes LJ_GC_BLACK is 0x04.
| rlwinm mark, mark, 0, 30, 28 // black2gray(tab)
| stw tab, DISPATCH_GL(gc.grayagain)(DISPATCH)
| stb mark, tab->marked
| stw tmp, tab->gclist
|.endmacro
|
|//-----------------------------------------------------------------------
/* Generate subroutines used by opcodes and other parts of the VM. */
/* The .code_sub section should be last to help static branch prediction. */
static void build_subroutines(BuildCtx *ctx)
{
|.code_sub
|
|//-----------------------------------------------------------------------
|//-- Return handling ----------------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_returnp:
| // See vm_return. Also: TMP2 = previous base.
| andix. TMP0, PC, FRAME_P
| li TMP1, LJ_TTRUE
| beq ->cont_dispatch
|
| // Return from pcall or xpcall fast func.
| lwz PC, FRAME_PC(TMP2) // Fetch PC of previous frame.
| mr BASE, TMP2 // Restore caller base.
| // Prepending may overwrite the pcall frame, so do it at the end.
| stwu TMP1, FRAME_PC(RA) // Prepend true to results.
|
|->vm_returnc:
| addi RD, RD, 8 // RD = (nresults+1)*8.
| andix. TMP0, PC, FRAME_TYPE
| cmpwi cr1, RD, 0
| li CRET1, LUA_YIELD
| beq cr1, ->vm_unwind_c_eh
| mr MULTRES, RD
| beq ->BC_RET_Z // Handle regular return to Lua.
|
|->vm_return:
| // BASE = base, RA = resultptr, RD/MULTRES = (nresults+1)*8, PC = return
| // TMP0 = PC & FRAME_TYPE
| cmpwi TMP0, FRAME_C
| rlwinm TMP2, PC, 0, 0, 28
| li_vmstate C
| sub TMP2, BASE, TMP2 // TMP2 = previous base.
| bney ->vm_returnp
|
| addic. TMP1, RD, -8
| stp TMP2, L->base
| lwz TMP2, SAVE_NRES
| subi BASE, BASE, 8
| st_vmstate
| slwi TMP2, TMP2, 3
| beq >2
|1:
| addic. TMP1, TMP1, -8
| lfd f0, 0(RA)
| addi RA, RA, 8
| stfd f0, 0(BASE)
| addi BASE, BASE, 8
| bney <1
|
|2:
| cmpw TMP2, RD // More/less results wanted?
| bne >6
|3:
| stp BASE, L->top // Store new top.
|
|->vm_leave_cp:
| lp TMP0, SAVE_CFRAME // Restore previous C frame.
| li CRET1, 0 // Ok return status for vm_pcall.
| stp TMP0, L->cframe
|
|->vm_leave_unw:
| restoreregs
| blr
|
|6:
| ble >7 // Less results wanted?
| // More results wanted. Check stack size and fill up results with nil.
| lwz TMP1, L->maxstack
| cmplw BASE, TMP1
| bge >8
| stw TISNIL, 0(BASE)
| addi RD, RD, 8
| addi BASE, BASE, 8
| b <2
|
|7: // Less results wanted.
| subfic TMP3, TMP2, 0 // LUA_MULTRET+1 case?
| sub TMP0, RD, TMP2
| subfe TMP1, TMP1, TMP1 // TMP1 = TMP2 == 0 ? 0 : -1
| and TMP0, TMP0, TMP1
| sub BASE, BASE, TMP0 // Either keep top or shrink it.
| b <3
|
|8: // Corner case: need to grow stack for filling up results.
| // This can happen if:
| // - A C function grows the stack (a lot).
| // - The GC shrinks the stack in between.
| // - A return back from a lua_call() with (high) nresults adjustment.
| stp BASE, L->top // Save current top held in BASE (yes).
| mr SAVE0, RD
| srwi CARG2, TMP2, 3
| mr CARG1, L
| bl extern lj_state_growstack // (lua_State *L, int n)
| lwz TMP2, SAVE_NRES
| mr RD, SAVE0
| slwi TMP2, TMP2, 3
| lp BASE, L->top // Need the (realloced) L->top in BASE.
| b <2
|
|->vm_unwind_c: // Unwind C stack, return from vm_pcall.
| // (void *cframe, int errcode)
| mr sp, CARG1
| mr CRET1, CARG2
|->vm_unwind_c_eh: // Landing pad for external unwinder.
| lwz L, SAVE_L
| .toc ld TOCREG, SAVE_TOC
| li TMP0, ~LJ_VMST_C
| lwz GL:TMP1, L->glref
| stw TMP0, GL:TMP1->vmstate
| b ->vm_leave_unw
|
|->vm_unwind_ff: // Unwind C stack, return from ff pcall.
| // (void *cframe)
|.if GPR64
| rldicr sp, CARG1, 0, 61
|.else
| rlwinm sp, CARG1, 0, 0, 29
|.endif
|->vm_unwind_ff_eh: // Landing pad for external unwinder.
| lwz L, SAVE_L
| .toc ld TOCREG, SAVE_TOC
| li TISNUM, LJ_TISNUM // Setup type comparison constants.
| lp BASE, L->base
| lus TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
| lwz DISPATCH, L->glref // Setup pointer to dispatch table.
| li ZERO, 0
| stw TMP3, TMPD
| li TMP1, LJ_TFALSE
| ori TMP3, TMP3, 0x0004 // TONUM = 2^52 + 2^51 + 2^31 (float).
| li TISNIL, LJ_TNIL
| li_vmstate INTERP
| lfs TOBIT, TMPD
| lwz PC, FRAME_PC(BASE) // Fetch PC of previous frame.
| la RA, -8(BASE) // Results start at BASE-8.
| stw TMP3, TMPD
| addi DISPATCH, DISPATCH, GG_G2DISP
| stw TMP1, 0(RA) // Prepend false to error message.
| li RD, 16 // 2 results: false + error message.
| st_vmstate
| lfs TONUM, TMPD
| b ->vm_returnc
|
|//-----------------------------------------------------------------------
|//-- Grow stack for calls -----------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_growstack_c: // Grow stack for C function.
| li CARG2, LUA_MINSTACK
| b >2
|
|->vm_growstack_l: // Grow stack for Lua function.
| // BASE = new base, RA = BASE+framesize*8, RC = nargs*8, PC = first PC
| add RC, BASE, RC
| sub RA, RA, BASE
| stp BASE, L->base
| addi PC, PC, 4 // Must point after first instruction.
| stp RC, L->top
| srwi CARG2, RA, 3
|2:
| // L->base = new base, L->top = top
| stw PC, SAVE_PC
| mr CARG1, L
| bl extern lj_state_growstack // (lua_State *L, int n)
| lp BASE, L->base
| lp RC, L->top
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| sub RC, RC, BASE
| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
| ins_callt // Just retry the call.
|
|//-----------------------------------------------------------------------
|//-- Entry points into the assembler VM ---------------------------------
|//-----------------------------------------------------------------------
|
|->vm_resume: // Setup C frame and resume thread.
| // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
| saveregs
| mr L, CARG1
| lwz DISPATCH, L->glref // Setup pointer to dispatch table.
| mr BASE, CARG2
| lbz TMP1, L->status
| stw L, SAVE_L
| li PC, FRAME_CP
| addi TMP0, sp, CFRAME_RESUME
| addi DISPATCH, DISPATCH, GG_G2DISP
| stw CARG3, SAVE_NRES
| cmplwi TMP1, 0
| stw CARG3, SAVE_ERRF
| stp CARG3, SAVE_CFRAME
| stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
| stp TMP0, L->cframe
| beq >3
|
| // Resume after yield (like a return).
| stw L, DISPATCH_GL(cur_L)(DISPATCH)
| mr RA, BASE
| lp BASE, L->base
| li TISNUM, LJ_TISNUM // Setup type comparison constants.
| lp TMP1, L->top
| lwz PC, FRAME_PC(BASE)
| lus TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
| stb CARG3, L->status
| stw TMP3, TMPD
| ori TMP3, TMP3, 0x0004 // TONUM = 2^52 + 2^51 + 2^31 (float).
| lfs TOBIT, TMPD
| sub RD, TMP1, BASE
| stw TMP3, TMPD
| lus TMP0, 0x4338 // Hiword of 2^52 + 2^51 (double)
| addi RD, RD, 8
| stw TMP0, TONUM_HI
| li_vmstate INTERP
| li ZERO, 0
| st_vmstate
| andix. TMP0, PC, FRAME_TYPE
| mr MULTRES, RD
| lfs TONUM, TMPD
| li TISNIL, LJ_TNIL
| beq ->BC_RET_Z
| b ->vm_return
|
|->vm_pcall: // Setup protected C frame and enter VM.
| // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
| saveregs
| li PC, FRAME_CP
| stw CARG4, SAVE_ERRF
| b >1
|
|->vm_call: // Setup C frame and enter VM.
| // (lua_State *L, TValue *base, int nres1)
| saveregs
| li PC, FRAME_C
|
|1: // Entry point for vm_pcall above (PC = ftype).
| lp TMP1, L:CARG1->cframe
| mr L, CARG1
| stw CARG3, SAVE_NRES
| lwz DISPATCH, L->glref // Setup pointer to dispatch table.
| stw CARG1, SAVE_L
| mr BASE, CARG2
| addi DISPATCH, DISPATCH, GG_G2DISP
| stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
| stp TMP1, SAVE_CFRAME
| stp sp, L->cframe // Add our C frame to cframe chain.
|
|3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
| stw L, DISPATCH_GL(cur_L)(DISPATCH)
| lp TMP2, L->base // TMP2 = old base (used in vmeta_call).
| li TISNUM, LJ_TISNUM // Setup type comparison constants.
| lp TMP1, L->top
| lus TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
| add PC, PC, BASE
| stw TMP3, TMPD
| li ZERO, 0
| ori TMP3, TMP3, 0x0004 // TONUM = 2^52 + 2^51 + 2^31 (float).
| lfs TOBIT, TMPD
| sub PC, PC, TMP2 // PC = frame delta + frame type
| stw TMP3, TMPD
| lus TMP0, 0x4338 // Hiword of 2^52 + 2^51 (double)
| sub NARGS8:RC, TMP1, BASE
| stw TMP0, TONUM_HI
| li_vmstate INTERP
| lfs TONUM, TMPD
| li TISNIL, LJ_TNIL
| st_vmstate
|
|->vm_call_dispatch:
| // TMP2 = old base, BASE = new base, RC = nargs*8, PC = caller PC
| lwz TMP0, FRAME_PC(BASE)
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| checkfunc TMP0; bne ->vmeta_call
|
|->vm_call_dispatch_f:
| ins_call
| // BASE = new base, RB = func, RC = nargs*8, PC = caller PC
|
|->vm_cpcall: // Setup protected C frame, call C.
| // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
| saveregs
| mr L, CARG1
| lwz TMP0, L:CARG1->stack
| stw CARG1, SAVE_L
| lp TMP1, L->top
| lwz DISPATCH, L->glref // Setup pointer to dispatch table.
| stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
| sub TMP0, TMP0, TMP1 // Compute -savestack(L, L->top).
| lp TMP1, L->cframe
| addi DISPATCH, DISPATCH, GG_G2DISP
| .toc lp CARG4, 0(CARG4)
| li TMP2, 0
| stw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame.
| stw TMP2, SAVE_ERRF // No error function.
| stp TMP1, SAVE_CFRAME
| stp sp, L->cframe // Add our C frame to cframe chain.
| stw L, DISPATCH_GL(cur_L)(DISPATCH)
| mtctr CARG4
| bctrl // (lua_State *L, lua_CFunction func, void *ud)
|.if PPE
| mr BASE, CRET1
| cmpwi CRET1, 0
|.else
| mr. BASE, CRET1
|.endif
| li PC, FRAME_CP
| bne <3 // Else continue with the call.
| b ->vm_leave_cp // No base? Just remove C frame.
|
|//-----------------------------------------------------------------------
|//-- Metamethod handling ------------------------------------------------
|//-----------------------------------------------------------------------
|
|// The lj_meta_* functions (except for lj_meta_cat) don't reallocate the
|// stack, so BASE doesn't need to be reloaded across these calls.
|
|//-- Continuation dispatch ----------------------------------------------
|
|->cont_dispatch:
| // BASE = meta base, RA = resultptr, RD = (nresults+1)*8
| lwz TMP0, -12(BASE) // Continuation.
| mr RB, BASE
| mr BASE, TMP2 // Restore caller BASE.
| lwz LFUNC:TMP1, FRAME_FUNC(TMP2)
|.if FFI
| cmplwi TMP0, 1
|.endif
| lwz PC, -16(RB) // Restore PC from [cont|PC].
| subi TMP2, RD, 8
| lwz TMP1, LFUNC:TMP1->pc
| stwx TISNIL, RA, TMP2 // Ensure one valid arg.
|.if FFI
| ble >1
|.endif
| lwz KBASE, PC2PROTO(k)(TMP1)
| // BASE = base, RA = resultptr, RB = meta base
| mtctr TMP0
| bctr // Jump to continuation.
|
|.if FFI
|1:
| beq ->cont_ffi_callback // cont = 1: return from FFI callback.
| // cont = 0: tailcall from C function.
| subi TMP1, RB, 16
| sub RC, TMP1, BASE
| b ->vm_call_tail
|.endif
|
|->cont_cat: // RA = resultptr, RB = meta base
| lwz INS, -4(PC)
| subi CARG2, RB, 16
| decode_RB8 SAVE0, INS
| lfd f0, 0(RA)
| add TMP1, BASE, SAVE0
| stp BASE, L->base
| cmplw TMP1, CARG2
| sub CARG3, CARG2, TMP1
| decode_RA8 RA, INS
| stfd f0, 0(CARG2)
| bney ->BC_CAT_Z
| stfdx f0, BASE, RA
| b ->cont_nop
|
|//-- Table indexing metamethods -----------------------------------------
|
|->vmeta_tgets1:
| la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
| li TMP0, LJ_TSTR
| decode_RB8 RB, INS
| stw STR:RC, 4(CARG3)
| add CARG2, BASE, RB
| stw TMP0, 0(CARG3)
| b >1
|
|->vmeta_tgets:
| la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
| li TMP0, LJ_TTAB
| stw TAB:RB, 4(CARG2)
| la CARG3, DISPATCH_GL(tmptv2)(DISPATCH)
| stw TMP0, 0(CARG2)
| li TMP1, LJ_TSTR
| stw STR:RC, 4(CARG3)
| stw TMP1, 0(CARG3)
| b >1
|
|->vmeta_tgetb: // TMP0 = index
|.if not DUALNUM
| tonum_u f0, TMP0
|.endif
| decode_RB8 RB, INS
| la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
| add CARG2, BASE, RB
|.if DUALNUM
| stw TISNUM, 0(CARG3)
| stw TMP0, 4(CARG3)
|.else
| stfd f0, 0(CARG3)
|.endif
| b >1
|
|->vmeta_tgetv:
| decode_RB8 RB, INS
| decode_RC8 RC, INS
| add CARG2, BASE, RB
| add CARG3, BASE, RC
|1:
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| bl extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
| // Returns TValue * (finished) or NULL (metamethod).
| cmplwi CRET1, 0
| beq >3
| lfd f0, 0(CRET1)
| ins_next1
| stfdx f0, BASE, RA
| ins_next2
|
|3: // Call __index metamethod.
| // BASE = base, L->top = new base, stack = cont/func/t/k
| subfic TMP1, BASE, FRAME_CONT
| lp BASE, L->top
| stw PC, -16(BASE) // [cont|PC]
| add PC, TMP1, BASE
| lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
| li NARGS8:RC, 16 // 2 args for func(t, k).
| b ->vm_call_dispatch_f
|
|->vmeta_tgetr:
| bl extern lj_tab_getinth // (GCtab *t, int32_t key)
| // Returns cTValue * or NULL.
| cmplwi CRET1, 0
| beq >1
| lfd f14, 0(CRET1)
| b ->BC_TGETR_Z
|1:
| stwx TISNIL, BASE, RA
| b ->cont_nop
|
|//-----------------------------------------------------------------------
|
|->vmeta_tsets1:
| la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
| li TMP0, LJ_TSTR
| decode_RB8 RB, INS
| stw STR:RC, 4(CARG3)
| add CARG2, BASE, RB
| stw TMP0, 0(CARG3)
| b >1
|
|->vmeta_tsets:
| la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
| li TMP0, LJ_TTAB
| stw TAB:RB, 4(CARG2)
| la CARG3, DISPATCH_GL(tmptv2)(DISPATCH)
| stw TMP0, 0(CARG2)
| li TMP1, LJ_TSTR
| stw STR:RC, 4(CARG3)
| stw TMP1, 0(CARG3)
| b >1
|
|->vmeta_tsetb: // TMP0 = index
|.if not DUALNUM
| tonum_u f0, TMP0
|.endif
| decode_RB8 RB, INS
| la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
| add CARG2, BASE, RB
|.if DUALNUM
| stw TISNUM, 0(CARG3)
| stw TMP0, 4(CARG3)
|.else
| stfd f0, 0(CARG3)
|.endif
| b >1
|
|->vmeta_tsetv:
| decode_RB8 RB, INS
| decode_RC8 RC, INS
| add CARG2, BASE, RB
| add CARG3, BASE, RC
|1:
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| bl extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
| // Returns TValue * (finished) or NULL (metamethod).
| cmplwi CRET1, 0
| lfdx f0, BASE, RA
| beq >3
| // NOBARRIER: lj_meta_tset ensures the table is not black.
| ins_next1
| stfd f0, 0(CRET1)
| ins_next2
|
|3: // Call __newindex metamethod.
| // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
| subfic TMP1, BASE, FRAME_CONT
| lp BASE, L->top
| stw PC, -16(BASE) // [cont|PC]
| add PC, TMP1, BASE
| lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
| li NARGS8:RC, 24 // 3 args for func(t, k, v)
| stfd f0, 16(BASE) // Copy value to third argument.
| b ->vm_call_dispatch_f
|
|->vmeta_tsetr:
| stp BASE, L->base
| stw PC, SAVE_PC
| bl extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
| // Returns TValue *.
| stfd f14, 0(CRET1)
| b ->cont_nop
|
|//-- Comparison metamethods ---------------------------------------------
|
|->vmeta_comp:
| mr CARG1, L
| subi PC, PC, 4
|.if DUALNUM
| mr CARG2, RA
|.else
| add CARG2, BASE, RA
|.endif
| stw PC, SAVE_PC
|.if DUALNUM
| mr CARG3, RD
|.else
| add CARG3, BASE, RD
|.endif
| stp BASE, L->base
| decode_OP1 CARG4, INS
| bl extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
| // Returns 0/1 or TValue * (metamethod).
|3:
| cmplwi CRET1, 1
| bgt ->vmeta_binop
| subfic CRET1, CRET1, 0
|4:
| lwz INS, 0(PC)
| addi PC, PC, 4
| decode_RD4 TMP2, INS
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| and TMP2, TMP2, CRET1
| add PC, PC, TMP2
|->cont_nop:
| ins_next
|
|->cont_ra: // RA = resultptr
| lwz INS, -4(PC)
| lfd f0, 0(RA)
| decode_RA8 TMP1, INS
| stfdx f0, BASE, TMP1
| b ->cont_nop
|
|->cont_condt: // RA = resultptr
| lwz TMP0, 0(RA)
| .gpr64 extsw TMP0, TMP0
| subfic TMP0, TMP0, LJ_TTRUE // Branch if result is true.
| subfe CRET1, CRET1, CRET1
| not CRET1, CRET1
| b <4
|
|->cont_condf: // RA = resultptr
| lwz TMP0, 0(RA)
| .gpr64 extsw TMP0, TMP0
| subfic TMP0, TMP0, LJ_TTRUE // Branch if result is false.
| subfe CRET1, CRET1, CRET1
| b <4
|
|->vmeta_equal:
| // CARG2, CARG3, CARG4 are already set by BC_ISEQV/BC_ISNEV.
| subi PC, PC, 4
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| bl extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
| // Returns 0/1 or TValue * (metamethod).
| b <3
|
|->vmeta_equal_cd:
|.if FFI
| mr CARG2, INS
| subi PC, PC, 4
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| bl extern lj_meta_equal_cd // (lua_State *L, BCIns op)
| // Returns 0/1 or TValue * (metamethod).
| b <3
|.endif
|
|->vmeta_istype:
| subi PC, PC, 4
| stp BASE, L->base
| srwi CARG2, RA, 3
| mr CARG1, L
| srwi CARG3, RD, 3
| stw PC, SAVE_PC
| bl extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
| b ->cont_nop
|
|//-- Arithmetic metamethods ---------------------------------------------
|
|->vmeta_arith_nv:
| add CARG3, KBASE, RC
| add CARG4, BASE, RB
| b >1
|->vmeta_arith_nv2:
|.if DUALNUM
| mr CARG3, RC
| mr CARG4, RB
| b >1
|.endif
|
|->vmeta_unm:
| mr CARG3, RD
| mr CARG4, RD
| b >1
|
|->vmeta_arith_vn:
| add CARG3, BASE, RB
| add CARG4, KBASE, RC
| b >1
|
|->vmeta_arith_vv:
| add CARG3, BASE, RB
| add CARG4, BASE, RC
|.if DUALNUM
| b >1
|.endif
|->vmeta_arith_vn2:
|->vmeta_arith_vv2:
|.if DUALNUM
| mr CARG3, RB
| mr CARG4, RC
|.endif
|1:
| add CARG2, BASE, RA
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| decode_OP1 CARG5, INS // Caveat: CARG5 overlaps INS.
| bl extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
| // Returns NULL (finished) or TValue * (metamethod).
| cmplwi CRET1, 0
| beq ->cont_nop
|
| // Call metamethod for binary op.
|->vmeta_binop:
| // BASE = old base, CRET1 = new base, stack = cont/func/o1/o2
| sub TMP1, CRET1, BASE
| stw PC, -16(CRET1) // [cont|PC]
| mr TMP2, BASE
| addi PC, TMP1, FRAME_CONT
| mr BASE, CRET1
| li NARGS8:RC, 16 // 2 args for func(o1, o2).
| b ->vm_call_dispatch
|
|->vmeta_len:
#if LJ_52
| mr SAVE0, CARG1
#endif
| mr CARG2, RD
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| bl extern lj_meta_len // (lua_State *L, TValue *o)
| // Returns NULL (retry) or TValue * (metamethod base).
#if LJ_52
| cmplwi CRET1, 0
| bne ->vmeta_binop // Binop call for compatibility.
| mr CARG1, SAVE0
| b ->BC_LEN_Z
#else
| b ->vmeta_binop // Binop call for compatibility.
#endif
|
|//-- Call metamethod ----------------------------------------------------
|
|->vmeta_call: // Resolve and call __call metamethod.
| // TMP2 = old base, BASE = new base, RC = nargs*8
| mr CARG1, L
| stp TMP2, L->base // This is the callers base!
| subi CARG2, BASE, 8
| stw PC, SAVE_PC
| add CARG3, BASE, RC
| mr SAVE0, NARGS8:RC
| bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
| lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
| addi NARGS8:RC, SAVE0, 8 // Got one more argument now.
| ins_call
|
|->vmeta_callt: // Resolve __call for BC_CALLT.
| // BASE = old base, RA = new base, RC = nargs*8
| mr CARG1, L
| stp BASE, L->base
| subi CARG2, RA, 8
| stw PC, SAVE_PC
| add CARG3, RA, RC
| mr SAVE0, NARGS8:RC
| bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
| lwz TMP1, FRAME_PC(BASE)
| addi NARGS8:RC, SAVE0, 8 // Got one more argument now.
| lwz LFUNC:RB, FRAME_FUNC(RA) // Guaranteed to be a function here.
| b ->BC_CALLT_Z
|
|//-- Argument coercion for 'for' statement ------------------------------
|
|->vmeta_for:
| mr CARG1, L
| stp BASE, L->base
| mr CARG2, RA
| stw PC, SAVE_PC
| mr SAVE0, INS
| bl extern lj_meta_for // (lua_State *L, TValue *base)
|.if JIT
| decode_OP1 TMP0, SAVE0
|.endif
| decode_RA8 RA, SAVE0
|.if JIT
| cmpwi TMP0, BC_JFORI
|.endif
| decode_RD8 RD, SAVE0
|.if JIT
| beqy =>BC_JFORI
|.endif
| b =>BC_FORI
|
|//-----------------------------------------------------------------------
|//-- Fast functions -----------------------------------------------------
|//-----------------------------------------------------------------------
|
|.macro .ffunc, name
|->ff_ .. name:
|.endmacro
|
|.macro .ffunc_1, name
|->ff_ .. name:
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
| lwz CARG1, 4(BASE)
| blt ->fff_fallback
|.endmacro
|
|.macro .ffunc_2, name
|->ff_ .. name:
| cmplwi NARGS8:RC, 16
| lwz CARG3, 0(BASE)
| lwz CARG4, 8(BASE)
| lwz CARG1, 4(BASE)
| lwz CARG2, 12(BASE)
| blt ->fff_fallback
|.endmacro
|
|.macro .ffunc_n, name
|->ff_ .. name:
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
| lfd FARG1, 0(BASE)
| blt ->fff_fallback
| checknum CARG3; bge ->fff_fallback
|.endmacro
|
|.macro .ffunc_nn, name
|->ff_ .. name:
| cmplwi NARGS8:RC, 16
| lwz CARG3, 0(BASE)
| lfd FARG1, 0(BASE)
| lwz CARG4, 8(BASE)
| lfd FARG2, 8(BASE)
| blt ->fff_fallback
| checknum CARG3; bge ->fff_fallback
| checknum CARG4; bge ->fff_fallback
|.endmacro
|
|// Inlined GC threshold check. Caveat: uses TMP0 and TMP1.
|.macro ffgccheck
| lwz TMP0, DISPATCH_GL(gc.total)(DISPATCH)
| lwz TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
| cmplw TMP0, TMP1
| bgel ->fff_gcstep
|.endmacro
|
|//-- Base library: checks -----------------------------------------------
|
|.ffunc_1 assert
| li TMP1, LJ_TFALSE
| la RA, -8(BASE)
| cmplw cr1, CARG3, TMP1
| lwz PC, FRAME_PC(BASE)
| bge cr1, ->fff_fallback
| stw CARG3, 0(RA)
| addi RD, NARGS8:RC, 8 // Compute (nresults+1)*8.
| stw CARG1, 4(RA)
| beq ->fff_res // Done if exactly 1 argument.
| li TMP1, 8
| subi RC, RC, 8
|1:
| cmplw TMP1, RC
| lfdx f0, BASE, TMP1
| stfdx f0, RA, TMP1
| addi TMP1, TMP1, 8
| bney <1
| b ->fff_res
|
|.ffunc type
| cmplwi NARGS8:RC, 8
| lwz CARG1, 0(BASE)
| blt ->fff_fallback
| .gpr64 extsw CARG1, CARG1
| subfc TMP0, TISNUM, CARG1
| subfe TMP2, CARG1, CARG1
| orc TMP1, TMP2, TMP0
| addi TMP1, TMP1, ~LJ_TISNUM+1
| slwi TMP1, TMP1, 3
| la TMP2, CFUNC:RB->upvalue
| lfdx FARG1, TMP2, TMP1
| b ->fff_resn
|
|//-- Base library: getters and setters ---------------------------------
|
|.ffunc_1 getmetatable
| checktab CARG3; bne >6
|1: // Field metatable must be at same offset for GCtab and GCudata!
| lwz TAB:CARG1, TAB:CARG1->metatable
|2:
| li CARG3, LJ_TNIL
| cmplwi TAB:CARG1, 0
| lwz STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH)
| beq ->fff_restv
| lwz TMP0, TAB:CARG1->hmask
| li CARG3, LJ_TTAB // Use metatable as default result.
| lwz TMP1, STR:RC->hash
| lwz NODE:TMP2, TAB:CARG1->node
| and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
| slwi TMP0, TMP1, 5
| slwi TMP1, TMP1, 3
| sub TMP1, TMP0, TMP1
| add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
|3: // Rearranged logic, because we expect _not_ to find the key.
| lwz CARG4, NODE:TMP2->key
| lwz TMP0, 4+offsetof(Node, key)(NODE:TMP2)
| lwz CARG2, NODE:TMP2->val
| lwz TMP1, 4+offsetof(Node, val)(NODE:TMP2)
| checkstr CARG4; bne >4
| cmpw TMP0, STR:RC; beq >5
|4:
| lwz NODE:TMP2, NODE:TMP2->next
| cmplwi NODE:TMP2, 0
| beq ->fff_restv // Not found, keep default result.
| b <3
|5:
| checknil CARG2
| beq ->fff_restv // Ditto for nil value.
| mr CARG3, CARG2 // Return value of mt.__metatable.
| mr CARG1, TMP1
| b ->fff_restv
|
|6:
| cmpwi CARG3, LJ_TUDATA; beq <1
| .gpr64 extsw CARG3, CARG3
| subfc TMP0, TISNUM, CARG3
| subfe TMP2, CARG3, CARG3
| orc TMP1, TMP2, TMP0
| addi TMP1, TMP1, ~LJ_TISNUM+1
| slwi TMP1, TMP1, 2
| la TMP2, DISPATCH_GL(gcroot[GCROOT_BASEMT])(DISPATCH)
| lwzx TAB:CARG1, TMP2, TMP1
| b <2
|
|.ffunc_2 setmetatable
| // Fast path: no mt for table yet and not clearing the mt.
| checktab CARG3; bne ->fff_fallback
| lwz TAB:TMP1, TAB:CARG1->metatable
| checktab CARG4; bne ->fff_fallback
| cmplwi TAB:TMP1, 0
| lbz TMP3, TAB:CARG1->marked
| bne ->fff_fallback
| andix. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
| stw TAB:CARG2, TAB:CARG1->metatable
| beq ->fff_restv
| barrierback TAB:CARG1, TMP3, TMP0
| b ->fff_restv
|
|.ffunc rawget
| cmplwi NARGS8:RC, 16
| lwz CARG4, 0(BASE)
| lwz TAB:CARG2, 4(BASE)
| blt ->fff_fallback
| checktab CARG4; bne ->fff_fallback
| la CARG3, 8(BASE)
| mr CARG1, L
| bl extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
| // Returns cTValue *.
| lfd FARG1, 0(CRET1)
| b ->fff_resn
|
|//-- Base library: conversions ------------------------------------------
|
|.ffunc tonumber
| // Only handles the number case inline (without a base argument).
| cmplwi NARGS8:RC, 8
| lwz CARG1, 0(BASE)
| lfd FARG1, 0(BASE)
| bne ->fff_fallback // Exactly one argument.
| checknum CARG1; bgt ->fff_fallback
| b ->fff_resn
|
|.ffunc_1 tostring
| // Only handles the string or number case inline.
| checkstr CARG3
| // A __tostring method in the string base metatable is ignored.
| beq ->fff_restv // String key?
| // Handle numbers inline, unless a number base metatable is present.
| lwz TMP0, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH)
| checknum CARG3
| cmplwi cr1, TMP0, 0
| stp BASE, L->base // Add frame since C call can throw.
| crorc 4*cr0+eq, 4*cr0+gt, 4*cr1+eq
| stw PC, SAVE_PC // Redundant (but a defined value).
| beq ->fff_fallback
| ffgccheck
| mr CARG1, L
| mr CARG2, BASE
|.if DUALNUM
| bl extern lj_strfmt_number // (lua_State *L, cTValue *o)
|.else
| bl extern lj_strfmt_num // (lua_State *L, lua_Number *np)
|.endif
| // Returns GCstr *.
| li CARG3, LJ_TSTR
| b ->fff_restv
|
|//-- Base library: iterators -------------------------------------------
|
|.ffunc next
| cmplwi NARGS8:RC, 8
| lwz CARG1, 0(BASE)
| lwz TAB:CARG2, 4(BASE)
| blt ->fff_fallback
| stwx TISNIL, BASE, NARGS8:RC // Set missing 2nd arg to nil.
| checktab CARG1
| lwz PC, FRAME_PC(BASE)
| bne ->fff_fallback
| stp BASE, L->base // Add frame since C call can throw.
| mr CARG1, L
| stp BASE, L->top // Dummy frame length is ok.
| la CARG3, 8(BASE)
| stw PC, SAVE_PC
| bl extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key)
| // Returns 0 at end of traversal.
| cmplwi CRET1, 0
| li CARG3, LJ_TNIL
| beq ->fff_restv // End of traversal: return nil.
| lfd f0, 8(BASE) // Copy key and value to results.
| la RA, -8(BASE)
| lfd f1, 16(BASE)
| stfd f0, 0(RA)
| li RD, (2+1)*8
| stfd f1, 8(RA)
| b ->fff_res
|
|.ffunc_1 pairs
| checktab CARG3
| lwz PC, FRAME_PC(BASE)
| bne ->fff_fallback
#if LJ_52
| lwz TAB:TMP2, TAB:CARG1->metatable
| lfd f0, CFUNC:RB->upvalue[0]
| cmplwi TAB:TMP2, 0
| la RA, -8(BASE)
| bne ->fff_fallback
#else
| lfd f0, CFUNC:RB->upvalue[0]
| la RA, -8(BASE)
#endif
| stw TISNIL, 8(BASE)
| li RD, (3+1)*8
| stfd f0, 0(RA)
| b ->fff_res
|
|.ffunc ipairs_aux
| cmplwi NARGS8:RC, 16
| lwz CARG3, 0(BASE)
| lwz TAB:CARG1, 4(BASE)
| lwz CARG4, 8(BASE)
|.if DUALNUM
| lwz TMP2, 12(BASE)
|.else
| lfd FARG2, 8(BASE)
|.endif
| blt ->fff_fallback
| checktab CARG3
| checknum cr1, CARG4
| lwz PC, FRAME_PC(BASE)
|.if DUALNUM
| bne ->fff_fallback
| bne cr1, ->fff_fallback
|.else
| lus TMP0, 0x3ff0
| stw ZERO, TMPD_LO
| bne ->fff_fallback
| stw TMP0, TMPD_HI
| bge cr1, ->fff_fallback
| lfd FARG1, TMPD
| toint TMP2, FARG2, f0
|.endif
| lwz TMP0, TAB:CARG1->asize
| lwz TMP1, TAB:CARG1->array
|.if not DUALNUM
| fadd FARG2, FARG2, FARG1
|.endif
| addi TMP2, TMP2, 1
| la RA, -8(BASE)
| cmplw TMP0, TMP2
|.if DUALNUM
| stw TISNUM, 0(RA)
| slwi TMP3, TMP2, 3
| stw TMP2, 4(RA)
|.else
| slwi TMP3, TMP2, 3
| stfd FARG2, 0(RA)
|.endif
| ble >2 // Not in array part?
| lwzx TMP2, TMP1, TMP3
| lfdx f0, TMP1, TMP3
|1:
| checknil TMP2
| li RD, (0+1)*8
| beq ->fff_res // End of iteration, return 0 results.
| li RD, (2+1)*8
| stfd f0, 8(RA)
| b ->fff_res
|2: // Check for empty hash part first. Otherwise call C function.
| lwz TMP0, TAB:CARG1->hmask
| cmplwi TMP0, 0
| li RD, (0+1)*8
| beq ->fff_res
| mr CARG2, TMP2
| bl extern lj_tab_getinth // (GCtab *t, int32_t key)
| // Returns cTValue * or NULL.
| cmplwi CRET1, 0
| li RD, (0+1)*8
| beq ->fff_res
| lwz TMP2, 0(CRET1)
| lfd f0, 0(CRET1)
| b <1
|
|.ffunc_1 ipairs
| checktab CARG3
| lwz PC, FRAME_PC(BASE)
| bne ->fff_fallback
#if LJ_52
| lwz TAB:TMP2, TAB:CARG1->metatable
| lfd f0, CFUNC:RB->upvalue[0]
| cmplwi TAB:TMP2, 0
| la RA, -8(BASE)
| bne ->fff_fallback
#else
| lfd f0, CFUNC:RB->upvalue[0]
| la RA, -8(BASE)
#endif
|.if DUALNUM
| stw TISNUM, 8(BASE)
|.else
| stw ZERO, 8(BASE)
|.endif
| stw ZERO, 12(BASE)
| li RD, (3+1)*8
| stfd f0, 0(RA)
| b ->fff_res
|
|//-- Base library: catch errors ----------------------------------------
|
|.ffunc pcall
| cmplwi NARGS8:RC, 8
| lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
| blt ->fff_fallback
| mr TMP2, BASE
| la BASE, 8(BASE)
| // Remember active hook before pcall.
| rlwinm TMP3, TMP3, 32-HOOK_ACTIVE_SHIFT, 31, 31
| subi NARGS8:RC, NARGS8:RC, 8
| addi PC, TMP3, 8+FRAME_PCALL
| b ->vm_call_dispatch
|
|.ffunc xpcall
| cmplwi NARGS8:RC, 16
| lwz CARG4, 8(BASE)
| lfd FARG2, 8(BASE)
| lfd FARG1, 0(BASE)
| blt ->fff_fallback
| lbz TMP1, DISPATCH_GL(hookmask)(DISPATCH)
| mr TMP2, BASE
| checkfunc CARG4; bne ->fff_fallback // Traceback must be a function.
| la BASE, 16(BASE)
| // Remember active hook before pcall.
| rlwinm TMP1, TMP1, 32-HOOK_ACTIVE_SHIFT, 31, 31
| stfd FARG2, 0(TMP2) // Swap function and traceback.
| subi NARGS8:RC, NARGS8:RC, 16
| stfd FARG1, 8(TMP2)
| addi PC, TMP1, 16+FRAME_PCALL
| b ->vm_call_dispatch
|
|//-- Coroutine library --------------------------------------------------
|
|.macro coroutine_resume_wrap, resume
|.if resume
|.ffunc_1 coroutine_resume
| cmpwi CARG3, LJ_TTHREAD; bne ->fff_fallback
|.else
|.ffunc coroutine_wrap_aux
| lwz L:CARG1, CFUNC:RB->upvalue[0].gcr
|.endif
| lbz TMP0, L:CARG1->status
| lp TMP1, L:CARG1->cframe
| lp CARG2, L:CARG1->top
| cmplwi cr0, TMP0, LUA_YIELD
| lp TMP2, L:CARG1->base
| cmplwi cr1, TMP1, 0
| lwz TMP0, L:CARG1->maxstack
| cmplw cr7, CARG2, TMP2
| lwz PC, FRAME_PC(BASE)
| crorc 4*cr6+lt, 4*cr0+gt, 4*cr1+eq // st>LUA_YIELD || cframe!=0
| add TMP2, CARG2, NARGS8:RC
| crandc 4*cr6+gt, 4*cr7+eq, 4*cr0+eq // base==top && st!=LUA_YIELD
| cmplw cr1, TMP2, TMP0
| cror 4*cr6+lt, 4*cr6+lt, 4*cr6+gt
| stw PC, SAVE_PC
| cror 4*cr6+lt, 4*cr6+lt, 4*cr1+gt // cond1 || cond2 || stackov
| stp BASE, L->base
| blt cr6, ->fff_fallback
|1:
|.if resume
| addi BASE, BASE, 8 // Keep resumed thread in stack for GC.
| subi NARGS8:RC, NARGS8:RC, 8
| subi TMP2, TMP2, 8
|.endif
| stp TMP2, L:CARG1->top
| li TMP1, 0
| stp BASE, L->top
|2: // Move args to coroutine.
| cmpw TMP1, NARGS8:RC
| lfdx f0, BASE, TMP1
| beq >3
| stfdx f0, CARG2, TMP1
| addi TMP1, TMP1, 8
| b <2
|3:
| li CARG3, 0
| mr L:SAVE0, L:CARG1
| li CARG4, 0
| bl ->vm_resume // (lua_State *L, TValue *base, 0, 0)
| // Returns thread status.
|4:
| lp TMP2, L:SAVE0->base
| cmplwi CRET1, LUA_YIELD
| lp TMP3, L:SAVE0->top
| li_vmstate INTERP
| lp BASE, L->base
| stw L, DISPATCH_GL(cur_L)(DISPATCH)
| st_vmstate
| bgt >8
| sub RD, TMP3, TMP2
| lwz TMP0, L->maxstack
| cmplwi RD, 0
| add TMP1, BASE, RD
| beq >6 // No results?
| cmplw TMP1, TMP0
| li TMP1, 0
| bgt >9 // Need to grow stack?
|
| subi TMP3, RD, 8
| stp TMP2, L:SAVE0->top // Clear coroutine stack.
|5: // Move results from coroutine.
| cmplw TMP1, TMP3
| lfdx f0, TMP2, TMP1
| stfdx f0, BASE, TMP1
| addi TMP1, TMP1, 8
| bne <5
|6:
| andix. TMP0, PC, FRAME_TYPE
|.if resume
| li TMP1, LJ_TTRUE
| la RA, -8(BASE)
| stw TMP1, -8(BASE) // Prepend true to results.
| addi RD, RD, 16
|.else
| mr RA, BASE
| addi RD, RD, 8
|.endif
|7:
| stw PC, SAVE_PC
| mr MULTRES, RD
| beq ->BC_RET_Z
| b ->vm_return
|
|8: // Coroutine returned with error (at co->top-1).
|.if resume
| andix. TMP0, PC, FRAME_TYPE
| la TMP3, -8(TMP3)
| li TMP1, LJ_TFALSE
| lfd f0, 0(TMP3)
| stp TMP3, L:SAVE0->top // Remove error from coroutine stack.
| li RD, (2+1)*8
| stw TMP1, -8(BASE) // Prepend false to results.
| la RA, -8(BASE)
| stfd f0, 0(BASE) // Copy error message.
| b <7
|.else
| mr CARG1, L
| mr CARG2, L:SAVE0
| bl extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co)
|.endif
|
|9: // Handle stack expansion on return from yield.
| mr CARG1, L
| srwi CARG2, RD, 3
| bl extern lj_state_growstack // (lua_State *L, int n)
| li CRET1, 0
| b <4
|.endmacro
|
| coroutine_resume_wrap 1 // coroutine.resume
| coroutine_resume_wrap 0 // coroutine.wrap
|
|.ffunc coroutine_yield
| lp TMP0, L->cframe
| add TMP1, BASE, NARGS8:RC
| stp BASE, L->base
| andix. TMP0, TMP0, CFRAME_RESUME
| stp TMP1, L->top
| li CRET1, LUA_YIELD
| beq ->fff_fallback
| stp ZERO, L->cframe
| stb CRET1, L->status
| b ->vm_leave_unw
|
|//-- Math library -------------------------------------------------------
|
|.ffunc_1 math_abs
| checknum CARG3
|.if DUALNUM
| bne >2
| srawi TMP1, CARG1, 31
| xor TMP2, TMP1, CARG1
|.if GPR64
| lus TMP0, 0x8000
| sub CARG1, TMP2, TMP1
| cmplw CARG1, TMP0
| beq >1
|.else
| sub. CARG1, TMP2, TMP1
| blt >1
|.endif
|->fff_resi:
| lwz PC, FRAME_PC(BASE)
| la RA, -8(BASE)
| stw TISNUM, -8(BASE)
| stw CRET1, -4(BASE)
| b ->fff_res1
|1:
| lus CARG3, 0x41e0 // 2^31.
| li CARG1, 0
| b ->fff_restv
|2:
|.endif
| bge ->fff_fallback
| rlwinm CARG3, CARG3, 0, 1, 31
| // Fallthrough.
|
|->fff_restv:
| // CARG3/CARG1 = TValue result.
| lwz PC, FRAME_PC(BASE)
| stw CARG3, -8(BASE)
| la RA, -8(BASE)
| stw CARG1, -4(BASE)
|->fff_res1:
| // RA = results, PC = return.
| li RD, (1+1)*8
|->fff_res:
| // RA = results, RD = (nresults+1)*8, PC = return.
| andix. TMP0, PC, FRAME_TYPE
| mr MULTRES, RD
| bney ->vm_return
| lwz INS, -4(PC)
| decode_RB8 RB, INS
|5:
| cmplw RB, RD // More results expected?
| decode_RA8 TMP0, INS
| bgt >6
| ins_next1
| // Adjust BASE. KBASE is assumed to be set for the calling frame.
| sub BASE, RA, TMP0
| ins_next2
|
|6: // Fill up results with nil.
| subi TMP1, RD, 8
| addi RD, RD, 8
| stwx TISNIL, RA, TMP1
| b <5
|
|.macro math_extern, func
| .ffunc_n math_ .. func
| blex func
| b ->fff_resn
|.endmacro
|
|.macro math_extern2, func
| .ffunc_nn math_ .. func
| blex func
| b ->fff_resn
|.endmacro
|
|.macro math_round, func
| .ffunc_1 math_ .. func
| checknum CARG3; beqy ->fff_restv
| rlwinm TMP2, CARG3, 12, 21, 31
| bge ->fff_fallback
| addic. TMP2, TMP2, -1023 // exp = exponent(x) - 1023
| cmplwi cr1, TMP2, 31 // 0 <= exp < 31?
| subfic TMP0, TMP2, 31
| blt >3
| slwi TMP1, CARG3, 11
| srwi TMP3, CARG1, 21
| oris TMP1, TMP1, 0x8000
| addi TMP2, TMP2, 1
| or TMP1, TMP1, TMP3
| slwi CARG2, CARG1, 11
| bge cr1, >4
| slw TMP3, TMP1, TMP2
| srw RD, TMP1, TMP0
| or TMP3, TMP3, CARG2
| srawi TMP2, CARG3, 31
|.if "func" == "floor"
| and TMP1, TMP3, TMP2
| addic TMP0, TMP1, -1
| subfe TMP1, TMP0, TMP1
| add CARG1, RD, TMP1
| xor CARG1, CARG1, TMP2
| sub CARG1, CARG1, TMP2
| b ->fff_resi
|.else
| andc TMP1, TMP3, TMP2
| addic TMP0, TMP1, -1
| subfe TMP1, TMP0, TMP1
| add CARG1, RD, TMP1
| cmpw CARG1, RD
| xor CARG1, CARG1, TMP2
| sub CARG1, CARG1, TMP2
| bge ->fff_resi
| // Overflow to 2^31.
| lus CARG3, 0x41e0 // 2^31.
| li CARG1, 0
| b ->fff_restv
|.endif
|3: // |x| < 1
| slwi TMP2, CARG3, 1
| srawi TMP1, CARG3, 31
| or TMP2, CARG1, TMP2 // ztest = (hi+hi) | lo
|.if "func" == "floor"
| and TMP1, TMP2, TMP1 // (ztest & sign) == 0 ? 0 : -1
| subfic TMP2, TMP1, 0
| subfe CARG1, CARG1, CARG1
|.else
| andc TMP1, TMP2, TMP1 // (ztest & ~sign) == 0 ? 0 : 1
| addic TMP2, TMP1, -1
| subfe CARG1, TMP2, TMP1
|.endif
| b ->fff_resi
|4: // exp >= 31. Check for -(2^31).
| xoris TMP1, TMP1, 0x8000
| srawi TMP2, CARG3, 31
|.if "func" == "floor"
| or TMP1, TMP1, CARG2
|.endif
|.if PPE
| orc TMP1, TMP1, TMP2
| cmpwi TMP1, 0
|.else
| orc. TMP1, TMP1, TMP2
|.endif
| crand 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
| lus CARG1, 0x8000 // -(2^31).
| beqy ->fff_resi
|5:
| lfd FARG1, 0(BASE)
| blex func
| b ->fff_resn
|.endmacro
|
|.if DUALNUM
| math_round floor
| math_round ceil
|.else
| // NYI: use internal implementation.
| math_extern floor
| math_extern ceil
|.endif
|
|.if SQRT
|.ffunc_n math_sqrt
| fsqrt FARG1, FARG1
| b ->fff_resn
|.else
| math_extern sqrt
|.endif
|
|.ffunc math_log
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
| lfd FARG1, 0(BASE)
| bne ->fff_fallback // Need exactly 1 argument.
| checknum CARG3; bge ->fff_fallback
| blex log
| b ->fff_resn
|
| math_extern log10
| math_extern exp
| math_extern sin
| math_extern cos
| math_extern tan
| math_extern asin
| math_extern acos
| math_extern atan
| math_extern sinh
| math_extern cosh
| math_extern tanh
| math_extern2 pow
| math_extern2 atan2
| math_extern2 fmod
|
|.if DUALNUM
|.ffunc math_ldexp
| cmplwi NARGS8:RC, 16
| lwz CARG3, 0(BASE)
| lfd FARG1, 0(BASE)
| lwz CARG4, 8(BASE)
|.if GPR64
| lwz CARG2, 12(BASE)
|.else
| lwz CARG1, 12(BASE)
|.endif
| blt ->fff_fallback
| checknum CARG3; bge ->fff_fallback
| checknum CARG4; bne ->fff_fallback
|.else
|.ffunc_nn math_ldexp
|.if GPR64
| toint CARG2, FARG2
|.else
| toint CARG1, FARG2
|.endif
|.endif
| blex ldexp
| b ->fff_resn
|
|.ffunc_n math_frexp
|.if GPR64
| la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
|.else
| la CARG1, DISPATCH_GL(tmptv)(DISPATCH)
|.endif
| lwz PC, FRAME_PC(BASE)
| blex frexp
| lwz TMP1, DISPATCH_GL(tmptv)(DISPATCH)
| la RA, -8(BASE)
|.if not DUALNUM
| tonum_i FARG2, TMP1
|.endif
| stfd FARG1, 0(RA)
| li RD, (2+1)*8
|.if DUALNUM
| stw TISNUM, 8(RA)
| stw TMP1, 12(RA)
|.else
| stfd FARG2, 8(RA)
|.endif
| b ->fff_res
|
|.ffunc_n math_modf
|.if GPR64
| la CARG2, -8(BASE)
|.else
| la CARG1, -8(BASE)
|.endif
| lwz PC, FRAME_PC(BASE)
| blex modf
| la RA, -8(BASE)
| stfd FARG1, 0(BASE)
| li RD, (2+1)*8
| b ->fff_res
|
|.macro math_minmax, name, ismax
|.if DUALNUM
| .ffunc_1 name
| checknum CARG3
| addi TMP1, BASE, 8
| add TMP2, BASE, NARGS8:RC
| bne >4
|1: // Handle integers.
| lwz CARG4, 0(TMP1)
| cmplw cr1, TMP1, TMP2
| lwz CARG2, 4(TMP1)
| bge cr1, ->fff_resi
| checknum CARG4
| xoris TMP0, CARG1, 0x8000
| xoris TMP3, CARG2, 0x8000
| bne >3
| subfc TMP3, TMP3, TMP0
| subfe TMP0, TMP0, TMP0
|.if ismax
| andc TMP3, TMP3, TMP0
|.else
| and TMP3, TMP3, TMP0
|.endif
| add CARG1, TMP3, CARG2
|.if GPR64
| rldicl CARG1, CARG1, 0, 32
|.endif
| addi TMP1, TMP1, 8
| b <1
|3:
| bge ->fff_fallback
| // Convert intermediate result to number and continue below.
| tonum_i FARG1, CARG1
| lfd FARG2, 0(TMP1)
| b >6
|4:
| lfd FARG1, 0(BASE)
| bge ->fff_fallback
|5: // Handle numbers.
| lwz CARG4, 0(TMP1)
| cmplw cr1, TMP1, TMP2
| lfd FARG2, 0(TMP1)
| bge cr1, ->fff_resn
| checknum CARG4; bge >7
|6:
| fsub f0, FARG1, FARG2
| addi TMP1, TMP1, 8
|.if ismax
| fsel FARG1, f0, FARG1, FARG2
|.else
| fsel FARG1, f0, FARG2, FARG1
|.endif
| b <5
|7: // Convert integer to number and continue above.
| lwz CARG2, 4(TMP1)
| bne ->fff_fallback
| tonum_i FARG2, CARG2
| b <6
|.else
| .ffunc_n name
| li TMP1, 8
|1:
| lwzx CARG2, BASE, TMP1
| lfdx FARG2, BASE, TMP1
| cmplw cr1, TMP1, NARGS8:RC
| checknum CARG2
| bge cr1, ->fff_resn
| bge ->fff_fallback
| fsub f0, FARG1, FARG2
| addi TMP1, TMP1, 8
|.if ismax
| fsel FARG1, f0, FARG1, FARG2
|.else
| fsel FARG1, f0, FARG2, FARG1
|.endif
| b <1
|.endif
|.endmacro
|
| math_minmax math_min, 0
| math_minmax math_max, 1
|
|//-- String library -----------------------------------------------------
|
|.ffunc string_byte // Only handle the 1-arg case here.
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
| lwz STR:CARG1, 4(BASE)
| bne ->fff_fallback // Need exactly 1 argument.
| checkstr CARG3
| bne ->fff_fallback
| lwz TMP0, STR:CARG1->len
|.if DUALNUM
| lbz CARG1, STR:CARG1[1] // Access is always ok (NUL at end).
| li RD, (0+1)*8
| lwz PC, FRAME_PC(BASE)
| cmplwi TMP0, 0
| la RA, -8(BASE)
| beqy ->fff_res
| b ->fff_resi
|.else
| lbz TMP1, STR:CARG1[1] // Access is always ok (NUL at end).
| addic TMP3, TMP0, -1 // RD = ((str->len != 0)+1)*8
| subfe RD, TMP3, TMP0
| stw TMP1, TONUM_LO // Inlined tonum_u f0, TMP1.
| addi RD, RD, 1
| lfd f0, TONUM_D
| la RA, -8(BASE)
| lwz PC, FRAME_PC(BASE)
| fsub f0, f0, TOBIT
| slwi RD, RD, 3
| stfd f0, 0(RA)
| b ->fff_res
|.endif
|
|.ffunc string_char // Only handle the 1-arg case here.
| ffgccheck
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
|.if DUALNUM
| lwz TMP0, 4(BASE)
| bne ->fff_fallback // Exactly 1 argument.
| checknum CARG3; bne ->fff_fallback
| la CARG2, 7(BASE)
|.else
| lfd FARG1, 0(BASE)
| bne ->fff_fallback // Exactly 1 argument.
| checknum CARG3; bge ->fff_fallback
| toint TMP0, FARG1
| la CARG2, TMPD_BLO
|.endif
| li CARG3, 1
| cmplwi TMP0, 255; bgt ->fff_fallback
|->fff_newstr:
| mr CARG1, L
| stp BASE, L->base
| stw PC, SAVE_PC
| bl extern lj_str_new // (lua_State *L, char *str, size_t l)
|->fff_resstr:
| // Returns GCstr *.
| lp BASE, L->base
| li CARG3, LJ_TSTR
| b ->fff_restv
|
|.ffunc string_sub
| ffgccheck
| cmplwi NARGS8:RC, 16
| lwz CARG3, 16(BASE)
|.if not DUALNUM
| lfd f0, 16(BASE)
|.endif
| lwz TMP0, 0(BASE)
| lwz STR:CARG1, 4(BASE)
| blt ->fff_fallback
| lwz CARG2, 8(BASE)
|.if DUALNUM
| lwz TMP1, 12(BASE)
|.else
| lfd f1, 8(BASE)
|.endif
| li TMP2, -1
| beq >1
|.if DUALNUM
| checknum CARG3
| lwz TMP2, 20(BASE)
| bne ->fff_fallback
|1:
| checknum CARG2; bne ->fff_fallback
|.else
| checknum CARG3; bge ->fff_fallback
| toint TMP2, f0
|1:
| checknum CARG2; bge ->fff_fallback
|.endif
| checkstr TMP0; bne ->fff_fallback
|.if not DUALNUM
| toint TMP1, f1
|.endif
| lwz TMP0, STR:CARG1->len
| cmplw TMP0, TMP2 // len < end? (unsigned compare)
| addi TMP3, TMP2, 1
| blt >5
|2:
| cmpwi TMP1, 0 // start <= 0?
| add TMP3, TMP1, TMP0
| ble >7
|3:
| sub CARG3, TMP2, TMP1
| addi CARG2, STR:CARG1, #STR-1
| srawi TMP0, CARG3, 31
| addi CARG3, CARG3, 1
| add CARG2, CARG2, TMP1
| andc CARG3, CARG3, TMP0
|.if GPR64
| rldicl CARG2, CARG2, 0, 32
| rldicl CARG3, CARG3, 0, 32
|.endif
| b ->fff_newstr
|
|5: // Negative end or overflow.
| cmpw TMP0, TMP2 // len >= end? (signed compare)
| add TMP2, TMP0, TMP3 // Negative end: end = end+len+1.
| bge <2
| mr TMP2, TMP0 // Overflow: end = len.
| b <2
|
|7: // Negative start or underflow.
| .gpr64 extsw TMP1, TMP1
| addic CARG3, TMP1, -1
| subfe CARG3, CARG3, CARG3
| srawi CARG2, TMP3, 31 // Note: modifies carry.
| andc TMP3, TMP3, CARG3
| andc TMP1, TMP3, CARG2
| addi TMP1, TMP1, 1 // start = 1 + (start ? start+len : 0)
| b <3
|
|.macro ffstring_op, name
| .ffunc string_ .. name
| ffgccheck
| cmplwi NARGS8:RC, 8
| lwz CARG3, 0(BASE)
| lwz STR:CARG2, 4(BASE)
| blt ->fff_fallback
| checkstr CARG3
| la SBUF:CARG1, DISPATCH_GL(tmpbuf)(DISPATCH)
| bne ->fff_fallback
| lwz TMP0, SBUF:CARG1->b
| stw L, SBUF:CARG1->L
| stp BASE, L->base
| stw PC, SAVE_PC
| stw TMP0, SBUF:CARG1->p
| bl extern lj_buf_putstr_ .. name
| bl extern lj_buf_tostr
| b ->fff_resstr
|.endmacro
|
|ffstring_op reverse
|ffstring_op lower
|ffstring_op upper
|
|//-- Bit library --------------------------------------------------------
|
|.macro .ffunc_bit, name
|.if DUALNUM
| .ffunc_1 bit_..name
| checknum CARG3; bnel ->fff_tobit_fb
|.else
| .ffunc_n bit_..name
| fadd FARG1, FARG1, TOBIT
| stfd FARG1, TMPD
| lwz CARG1, TMPD_LO
|.endif
|.endmacro
|
|.macro .ffunc_bit_op, name, ins
| .ffunc_bit name
| addi TMP1, BASE, 8
| add TMP2, BASE, NARGS8:RC
|1:
| lwz CARG4, 0(TMP1)
| cmplw cr1, TMP1, TMP2
|.if DUALNUM
| lwz CARG2, 4(TMP1)
|.else
| lfd FARG1, 0(TMP1)
|.endif
| bgey cr1, ->fff_resi
| checknum CARG4
|.if DUALNUM
| bnel ->fff_bitop_fb
|.else
| fadd FARG1, FARG1, TOBIT
| bge ->fff_fallback
| stfd FARG1, TMPD
| lwz CARG2, TMPD_LO
|.endif
| ins CARG1, CARG1, CARG2
| addi TMP1, TMP1, 8
| b <1
|.endmacro
|
|.ffunc_bit_op band, and
|.ffunc_bit_op bor, or
|.ffunc_bit_op bxor, xor
|
|.ffunc_bit bswap
| rotlwi TMP0, CARG1, 8
| rlwimi TMP0, CARG1, 24, 0, 7
| rlwimi TMP0, CARG1, 24, 16, 23
| mr CRET1, TMP0
| b ->fff_resi
|
|.ffunc_bit bnot
| not CRET1, CARG1
| b ->fff_resi
|
|.macro .ffunc_bit_sh, name, ins, shmod
|.if DUALNUM
| .ffunc_2 bit_..name
| checknum CARG3; bnel ->fff_tobit_fb
| // Note: no inline conversion from number for 2nd argument!
| checknum CARG4; bne ->fff_fallback
|.else
| .ffunc_nn bit_..name
| fadd FARG1, FARG1, TOBIT
| fadd FARG2, FARG2, TOBIT
| stfd FARG1, TMPD
| lwz CARG1, TMPD_LO
| stfd FARG2, TMPD
| lwz CARG2, TMPD_LO
|.endif
|.if shmod == 1
| rlwinm CARG2, CARG2, 0, 27, 31
|.elif shmod == 2
| neg CARG2, CARG2
|.endif
| ins CRET1, CARG1, CARG2
| b ->fff_resi
|.endmacro
|
|.ffunc_bit_sh lshift, slw, 1
|.ffunc_bit_sh rshift, srw, 1
|.ffunc_bit_sh arshift, sraw, 1
|.ffunc_bit_sh rol, rotlw, 0
|.ffunc_bit_sh ror, rotlw, 2
|
|.ffunc_bit tobit
|.if DUALNUM
| b ->fff_resi
|.else
|->fff_resi:
| tonum_i FARG1, CRET1
|.endif
|->fff_resn:
| lwz PC, FRAME_PC(BASE)
| la RA, -8(BASE)
| stfd FARG1, -8(BASE)
| b ->fff_res1
|
|// Fallback FP number to bit conversion.
|->fff_tobit_fb:
|.if DUALNUM
| lfd FARG1, 0(BASE)
| bgt ->fff_fallback
| fadd FARG1, FARG1, TOBIT
| stfd FARG1, TMPD
| lwz CARG1, TMPD_LO
| blr
|.endif
|->fff_bitop_fb:
|.if DUALNUM
| lfd FARG1, 0(TMP1)
| bgt ->fff_fallback
| fadd FARG1, FARG1, TOBIT
| stfd FARG1, TMPD
| lwz CARG2, TMPD_LO
| blr
|.endif
|
|//-----------------------------------------------------------------------
|
|->fff_fallback: // Call fast function fallback handler.
| // BASE = new base, RB = CFUNC, RC = nargs*8
| lp TMP3, CFUNC:RB->f
| add TMP1, BASE, NARGS8:RC
| lwz PC, FRAME_PC(BASE) // Fallback may overwrite PC.
| addi TMP0, TMP1, 8*LUA_MINSTACK
| lwz TMP2, L->maxstack
| stw PC, SAVE_PC // Redundant (but a defined value).
| .toc lp TMP3, 0(TMP3)
| cmplw TMP0, TMP2
| stp BASE, L->base
| stp TMP1, L->top
| mr CARG1, L
| bgt >5 // Need to grow stack.
| mtctr TMP3
| bctrl // (lua_State *L)
| // Either throws an error, or recovers and returns -1, 0 or nresults+1.
| lp BASE, L->base
| cmpwi CRET1, 0
| slwi RD, CRET1, 3
| la RA, -8(BASE)
| bgt ->fff_res // Returned nresults+1?
|1: // Returned 0 or -1: retry fast path.
| lp TMP0, L->top
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| sub NARGS8:RC, TMP0, BASE
| bne ->vm_call_tail // Returned -1?
| ins_callt // Returned 0: retry fast path.
|
|// Reconstruct previous base for vmeta_call during tailcall.
|->vm_call_tail:
| andix. TMP0, PC, FRAME_TYPE
| rlwinm TMP1, PC, 0, 0, 28
| bne >3
| lwz INS, -4(PC)
| decode_RA8 TMP1, INS
| addi TMP1, TMP1, 8
|3:
| sub TMP2, BASE, TMP1
| b ->vm_call_dispatch // Resolve again for tailcall.
|
|5: // Grow stack for fallback handler.
| li CARG2, LUA_MINSTACK
| bl extern lj_state_growstack // (lua_State *L, int n)
| lp BASE, L->base
| cmpw TMP0, TMP0 // Set 4*cr0+eq to force retry.
| b <1
|
|->fff_gcstep: // Call GC step function.
| // BASE = new base, RC = nargs*8
| mflr SAVE0
| stp BASE, L->base
| add TMP0, BASE, NARGS8:RC
| stw PC, SAVE_PC // Redundant (but a defined value).
| stp TMP0, L->top
| mr CARG1, L
| bl extern lj_gc_step // (lua_State *L)
| lp BASE, L->base
| mtlr SAVE0
| lp TMP0, L->top
| sub NARGS8:RC, TMP0, BASE
| lwz CFUNC:RB, FRAME_FUNC(BASE)
| blr
|
|//-----------------------------------------------------------------------
|//-- Special dispatch targets -------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_record: // Dispatch target for recording phase.
|.if JIT
| lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
| andix. TMP0, TMP3, HOOK_VMEVENT // No recording while in vmevent.
| bne >5
| // Decrement the hookcount for consistency, but always do the call.
| lwz TMP2, DISPATCH_GL(hookcount)(DISPATCH)
| andix. TMP0, TMP3, HOOK_ACTIVE
| bne >1
| subi TMP2, TMP2, 1
| andi. TMP0, TMP3, LUA_MASKLINE|LUA_MASKCOUNT
| beqy >1
| stw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
| b >1
|.endif
|
|->vm_rethook: // Dispatch target for return hooks.
| lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
| andix. TMP0, TMP3, HOOK_ACTIVE // Hook already active?
| beq >1
|5: // Re-dispatch to static ins.
| addi TMP1, TMP1, GG_DISP2STATIC // Assumes decode_OPP TMP1, INS.
| lpx TMP0, DISPATCH, TMP1
| mtctr TMP0
| bctr
|
|->vm_inshook: // Dispatch target for instr/line hooks.
| lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
| lwz TMP2, DISPATCH_GL(hookcount)(DISPATCH)
| andix. TMP0, TMP3, HOOK_ACTIVE // Hook already active?
| rlwinm TMP0, TMP3, 31-LUA_HOOKLINE, 31, 0
| bne <5
|
| cmpwi cr1, TMP0, 0
| addic. TMP2, TMP2, -1
| beq cr1, <5
| stw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
| beq >1
| bge cr1, <5
|1:
| mr CARG1, L
| stw MULTRES, SAVE_MULTRES
| mr CARG2, PC
| stp BASE, L->base
| // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
| bl extern lj_dispatch_ins // (lua_State *L, const BCIns *pc)
|3:
| lp BASE, L->base
|4: // Re-dispatch to static ins.
| lwz INS, -4(PC)
| decode_OPP TMP1, INS
| decode_RB8 RB, INS
| addi TMP1, TMP1, GG_DISP2STATIC
| decode_RD8 RD, INS
| lpx TMP0, DISPATCH, TMP1
| decode_RA8 RA, INS
| decode_RC8 RC, INS
| mtctr TMP0
| bctr
|
|->cont_hook: // Continue from hook yield.
| addi PC, PC, 4
| lwz MULTRES, -20(RB) // Restore MULTRES for *M ins.
| b <4
|
|->vm_hotloop: // Hot loop counter underflow.
|.if JIT
| lwz LFUNC:TMP1, FRAME_FUNC(BASE)
| addi CARG1, DISPATCH, GG_DISP2J
| stw PC, SAVE_PC
| lwz TMP1, LFUNC:TMP1->pc
| mr CARG2, PC
| stw L, DISPATCH_J(L)(DISPATCH)
| lbz TMP1, PC2PROTO(framesize)(TMP1)
| stp BASE, L->base
| slwi TMP1, TMP1, 3
| add TMP1, BASE, TMP1
| stp TMP1, L->top
| bl extern lj_trace_hot // (jit_State *J, const BCIns *pc)
| b <3
|.endif
|
|->vm_callhook: // Dispatch target for call hooks.
| mr CARG2, PC
|.if JIT
| b >1
|.endif
|
|->vm_hotcall: // Hot call counter underflow.
|.if JIT
| ori CARG2, PC, 1
|1:
|.endif
| add TMP0, BASE, RC
| stw PC, SAVE_PC
| mr CARG1, L
| stp BASE, L->base
| sub RA, RA, BASE
| stp TMP0, L->top
| bl extern lj_dispatch_call // (lua_State *L, const BCIns *pc)
| // Returns ASMFunction.
| lp BASE, L->base
| lp TMP0, L->top
| stw ZERO, SAVE_PC // Invalidate for subsequent line hook.
| sub NARGS8:RC, TMP0, BASE
| add RA, BASE, RA
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| lwz INS, -4(PC)
| mtctr CRET1
| bctr
|
|->cont_stitch: // Trace stitching.
|.if JIT
| // RA = resultptr, RB = meta base
| lwz INS, -4(PC)
| lwz TRACE:TMP2, -20(RB) // Save previous trace.
| addic. TMP1, MULTRES, -8
| decode_RA8 RC, INS // Call base.
| beq >2
|1: // Move results down.
| lfd f0, 0(RA)
| addic. TMP1, TMP1, -8
| addi RA, RA, 8
| stfdx f0, BASE, RC
| addi RC, RC, 8
| bne <1
|2:
| decode_RA8 RA, INS
| decode_RB8 RB, INS
| add RA, RA, RB
|3:
| cmplw RA, RC
| bgt >9 // More results wanted?
|
| lhz TMP3, TRACE:TMP2->traceno
| lhz RD, TRACE:TMP2->link
| cmpw RD, TMP3
| cmpwi cr1, RD, 0
| beq ->cont_nop // Blacklisted.
| slwi RD, RD, 3
| bne cr1, =>BC_JLOOP // Jump to stitched trace.
|
| // Stitch a new trace to the previous trace.
| stw TMP3, DISPATCH_J(exitno)(DISPATCH)
| stp L, DISPATCH_J(L)(DISPATCH)
| stp BASE, L->base
| addi CARG1, DISPATCH, GG_DISP2J
| mr CARG2, PC
| bl extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
| lp BASE, L->base
| b ->cont_nop
|
|9:
| stwx TISNIL, BASE, RC
| addi RC, RC, 8
| b <3
|.endif
|
|->vm_profhook: // Dispatch target for profiler hook.
#if LJ_HASPROFILE
| mr CARG1, L
| stw MULTRES, SAVE_MULTRES
| mr CARG2, PC
| stp BASE, L->base
| bl extern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
| // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
| lp BASE, L->base
| subi PC, PC, 4
| b ->cont_nop
#endif
|
|//-----------------------------------------------------------------------
|//-- Trace exit handler -------------------------------------------------
|//-----------------------------------------------------------------------
|
|.macro savex_, a, b, c, d
| stfd f..a, 16+a*8(sp)
| stfd f..b, 16+b*8(sp)
| stfd f..c, 16+c*8(sp)
| stfd f..d, 16+d*8(sp)
|.endmacro
|
|->vm_exit_handler:
|.if JIT
| addi sp, sp, -(16+32*8+32*4)
| stmw r2, 16+32*8+2*4(sp)
| addi DISPATCH, JGL, -GG_DISP2G-32768
| li CARG2, ~LJ_VMST_EXIT
| lwz CARG1, 16+32*8+32*4(sp) // Get stack chain.
| stw CARG2, DISPATCH_GL(vmstate)(DISPATCH)
| savex_ 0,1,2,3
| stw CARG1, 0(sp) // Store extended stack chain.
| clrso TMP1
| savex_ 4,5,6,7
| addi CARG2, sp, 16+32*8+32*4 // Recompute original value of sp.
| savex_ 8,9,10,11
| stw CARG2, 16+32*8+1*4(sp) // Store sp in RID_SP.
| savex_ 12,13,14,15
| mflr CARG3
| li TMP1, 0
| savex_ 16,17,18,19
| stw TMP1, 16+32*8+0*4(sp) // Clear RID_TMP.
| savex_ 20,21,22,23
| lhz CARG4, 2(CARG3) // Load trace number.
| savex_ 24,25,26,27
| lwz L, DISPATCH_GL(cur_L)(DISPATCH)
| savex_ 28,29,30,31
| sub CARG3, TMP0, CARG3 // Compute exit number.
| lp BASE, DISPATCH_GL(jit_base)(DISPATCH)
| srwi CARG3, CARG3, 2
| stp L, DISPATCH_J(L)(DISPATCH)
| subi CARG3, CARG3, 2
| stp BASE, L->base
| stw CARG4, DISPATCH_J(parent)(DISPATCH)
| stw TMP1, DISPATCH_GL(jit_base)(DISPATCH)
| addi CARG1, DISPATCH, GG_DISP2J
| stw CARG3, DISPATCH_J(exitno)(DISPATCH)
| addi CARG2, sp, 16
| bl extern lj_trace_exit // (jit_State *J, ExitState *ex)
| // Returns MULTRES (unscaled) or negated error code.
| lp TMP1, L->cframe
| lwz TMP2, 0(sp)
| lp BASE, L->base
|.if GPR64
| rldicr sp, TMP1, 0, 61
|.else
| rlwinm sp, TMP1, 0, 0, 29
|.endif
| lwz PC, SAVE_PC // Get SAVE_PC.
| stw TMP2, 0(sp)
| stw L, SAVE_L // Set SAVE_L (on-trace resume/yield).
| b >1
|.endif
|->vm_exit_interp:
|.if JIT
| // CARG1 = MULTRES or negated error code, BASE, PC and JGL set.
| lwz L, SAVE_L
| addi DISPATCH, JGL, -GG_DISP2G-32768
| stp BASE, L->base
|1:
| cmpwi CARG1, 0
| blt >9 // Check for error from exit.
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| slwi MULTRES, CARG1, 3
| li TMP2, 0
| stw MULTRES, SAVE_MULTRES
| lwz TMP1, LFUNC:RB->pc
| stw TMP2, DISPATCH_GL(jit_base)(DISPATCH)
| lwz KBASE, PC2PROTO(k)(TMP1)
| // Setup type comparison constants.
| li TISNUM, LJ_TISNUM
| lus TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
| stw TMP3, TMPD
| li ZERO, 0
| ori TMP3, TMP3, 0x0004 // TONUM = 2^52 + 2^51 + 2^31 (float).
| lfs TOBIT, TMPD
| stw TMP3, TMPD
| lus TMP0, 0x4338 // Hiword of 2^52 + 2^51 (double)
| li TISNIL, LJ_TNIL
| stw TMP0, TONUM_HI
| lfs TONUM, TMPD
| // Modified copy of ins_next which handles function header dispatch, too.
| lwz INS, 0(PC)
| addi PC, PC, 4
| // Assumes TISNIL == ~LJ_VMST_INTERP == -1.
| stw TISNIL, DISPATCH_GL(vmstate)(DISPATCH)
| decode_OPP TMP1, INS
| decode_RA8 RA, INS
| lpx TMP0, DISPATCH, TMP1
| mtctr TMP0
| cmplwi TMP1, BC_FUNCF*4 // Function header?
| bge >2
| decode_RB8 RB, INS
| decode_RD8 RD, INS
| decode_RC8 RC, INS
| bctr
|2:
| cmplwi TMP1, (BC_FUNCC+2)*4 // Fast function?
| blt >3
| // Check frame below fast function.
| lwz TMP1, FRAME_PC(BASE)
| andix. TMP0, TMP1, FRAME_TYPE
| bney >3 // Trace stitching continuation?
| // Otherwise set KBASE for Lua function below fast function.
| lwz TMP2, -4(TMP1)
| decode_RA8 TMP0, TMP2
| sub TMP1, BASE, TMP0
| lwz LFUNC:TMP2, -12(TMP1)
| lwz TMP1, LFUNC:TMP2->pc
| lwz KBASE, PC2PROTO(k)(TMP1)
|3:
| subi RC, MULTRES, 8
| add RA, RA, BASE
| bctr
|
|9: // Rethrow error from the right C frame.
| neg CARG2, CARG1
| mr CARG1, L
| bl extern lj_err_throw // (lua_State *L, int errcode)
|.endif
|
|//-----------------------------------------------------------------------
|//-- Math helper functions ----------------------------------------------
|//-----------------------------------------------------------------------
|
|// NYI: Use internal implementations of floor, ceil, trunc.
|
|->vm_modi:
| divwo. TMP0, CARG1, CARG2
| bso >1
|.if GPR64
| xor CARG3, CARG1, CARG2
| cmpwi CARG3, 0
|.else
| xor. CARG3, CARG1, CARG2
|.endif
| mullw TMP0, TMP0, CARG2
| sub CARG1, CARG1, TMP0
| bgelr
| cmpwi CARG1, 0; beqlr
| add CARG1, CARG1, CARG2
| blr
|1:
| cmpwi CARG2, 0
| li CARG1, 0
| beqlr
| clrso TMP0 // Clear SO for -2147483648 % -1 and return 0.
| blr
|
|//-----------------------------------------------------------------------
|//-- Miscellaneous functions --------------------------------------------
|//-----------------------------------------------------------------------
|
|// void lj_vm_cachesync(void *start, void *end)
|// Flush D-Cache and invalidate I-Cache. Assumes 32 byte cache line size.
|// This is a good lower bound, except for very ancient PPC models.
|->vm_cachesync:
|.if JIT or FFI
| // Compute start of first cache line and number of cache lines.
| rlwinm CARG1, CARG1, 0, 0, 26
| sub CARG2, CARG2, CARG1
| addi CARG2, CARG2, 31
| rlwinm. CARG2, CARG2, 27, 5, 31
| beqlr
| mtctr CARG2
| mr CARG3, CARG1
|1: // Flush D-Cache.
| dcbst r0, CARG1
| addi CARG1, CARG1, 32
| bdnz <1
| sync
| mtctr CARG2
|1: // Invalidate I-Cache.
| icbi r0, CARG3
| addi CARG3, CARG3, 32
| bdnz <1
| isync
| blr
|.endif
|
|//-----------------------------------------------------------------------
|//-- FFI helper functions -----------------------------------------------
|//-----------------------------------------------------------------------
|
|// Handler for callback functions. Callback slot number in r11, g in r12.
|->vm_ffi_callback:
|.if FFI
|.type CTSTATE, CTState, PC
| saveregs
| lwz CTSTATE, GL:r12->ctype_state
| addi DISPATCH, r12, GG_G2DISP
| stw r11, CTSTATE->cb.slot
| stw r3, CTSTATE->cb.gpr[0]
| stfd f1, CTSTATE->cb.fpr[0]
| stw r4, CTSTATE->cb.gpr[1]
| stfd f2, CTSTATE->cb.fpr[1]
| stw r5, CTSTATE->cb.gpr[2]
| stfd f3, CTSTATE->cb.fpr[2]
| stw r6, CTSTATE->cb.gpr[3]
| stfd f4, CTSTATE->cb.fpr[3]
| stw r7, CTSTATE->cb.gpr[4]
| stfd f5, CTSTATE->cb.fpr[4]
| stw r8, CTSTATE->cb.gpr[5]
| stfd f6, CTSTATE->cb.fpr[5]
| stw r9, CTSTATE->cb.gpr[6]
| stfd f7, CTSTATE->cb.fpr[6]
| stw r10, CTSTATE->cb.gpr[7]
| stfd f8, CTSTATE->cb.fpr[7]
| addi TMP0, sp, CFRAME_SPACE+8
| stw TMP0, CTSTATE->cb.stack
| mr CARG1, CTSTATE
| stw CTSTATE, SAVE_PC // Any value outside of bytecode is ok.
| mr CARG2, sp
| bl extern lj_ccallback_enter // (CTState *cts, void *cf)
| // Returns lua_State *.
| lp BASE, L:CRET1->base
| li TISNUM, LJ_TISNUM // Setup type comparison constants.
| lp RC, L:CRET1->top
| lus TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
| li ZERO, 0
| mr L, CRET1
| stw TMP3, TMPD
| lus TMP0, 0x4338 // Hiword of 2^52 + 2^51 (double)
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| ori TMP3, TMP3, 0x0004 // TONUM = 2^52 + 2^51 + 2^31 (float).
| stw TMP0, TONUM_HI
| li TISNIL, LJ_TNIL
| li_vmstate INTERP
| lfs TOBIT, TMPD
| stw TMP3, TMPD
| sub RC, RC, BASE
| st_vmstate
| lfs TONUM, TMPD
| ins_callt
|.endif
|
|->cont_ffi_callback: // Return from FFI callback.
|.if FFI
| lwz CTSTATE, DISPATCH_GL(ctype_state)(DISPATCH)
| stp BASE, L->base
| stp RB, L->top
| stp L, CTSTATE->L
| mr CARG1, CTSTATE
| mr CARG2, RA
| bl extern lj_ccallback_leave // (CTState *cts, TValue *o)
| lwz CRET1, CTSTATE->cb.gpr[0]
| lfd FARG1, CTSTATE->cb.fpr[0]
| lwz CRET2, CTSTATE->cb.gpr[1]
| b ->vm_leave_unw
|.endif
|
|->vm_ffi_call: // Call C function via FFI.
| // Caveat: needs special frame unwinding, see below.
|.if FFI
| .type CCSTATE, CCallState, CARG1
| lwz TMP1, CCSTATE->spadj
| mflr TMP0
| lbz CARG2, CCSTATE->nsp
| lbz CARG3, CCSTATE->nfpr
| neg TMP1, TMP1
| stw TMP0, 4(sp)
| cmpwi cr1, CARG3, 0
| mr TMP2, sp
| addic. CARG2, CARG2, -1
| stwux sp, sp, TMP1
| crnot 4*cr1+eq, 4*cr1+eq // For vararg calls.
| stw r14, -4(TMP2)
| stw CCSTATE, -8(TMP2)
| mr r14, TMP2
| la TMP1, CCSTATE->stack
| slwi CARG2, CARG2, 2
| blty >2
| la TMP2, 8(sp)
|1:
| lwzx TMP0, TMP1, CARG2
| stwx TMP0, TMP2, CARG2
| addic. CARG2, CARG2, -4
| bge <1
|2:
| bney cr1, >3
| lfd f1, CCSTATE->fpr[0]
| lfd f2, CCSTATE->fpr[1]
| lfd f3, CCSTATE->fpr[2]
| lfd f4, CCSTATE->fpr[3]
| lfd f5, CCSTATE->fpr[4]
| lfd f6, CCSTATE->fpr[5]
| lfd f7, CCSTATE->fpr[6]
| lfd f8, CCSTATE->fpr[7]
|3:
| lp TMP0, CCSTATE->func
| lwz CARG2, CCSTATE->gpr[1]
| lwz CARG3, CCSTATE->gpr[2]
| lwz CARG4, CCSTATE->gpr[3]
| lwz CARG5, CCSTATE->gpr[4]
| mtctr TMP0
| lwz r8, CCSTATE->gpr[5]
| lwz r9, CCSTATE->gpr[6]
| lwz r10, CCSTATE->gpr[7]
| lwz CARG1, CCSTATE->gpr[0] // Do this last, since CCSTATE is CARG1.
| bctrl
| lwz CCSTATE:TMP1, -8(r14)
| lwz TMP2, -4(r14)
| lwz TMP0, 4(r14)
| stw CARG1, CCSTATE:TMP1->gpr[0]
| stfd FARG1, CCSTATE:TMP1->fpr[0]
| stw CARG2, CCSTATE:TMP1->gpr[1]
| mtlr TMP0
| stw CARG3, CCSTATE:TMP1->gpr[2]
| mr sp, r14
| stw CARG4, CCSTATE:TMP1->gpr[3]
| mr r14, TMP2
| blr
|.endif
|// Note: vm_ffi_call must be the last function in this object file!
|
|//-----------------------------------------------------------------------
}
/* Generate the code for a single instruction. */
static void build_ins(BuildCtx *ctx, BCOp op, int defop)
{
int vk = 0;
|=>defop:
switch (op) {
/* -- Comparison ops ---------------------------------------------------- */
/* Remember: all ops branch for a true comparison, fall through otherwise. */
case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
| // RA = src1*8, RD = src2*8, JMP with RD = target
|.if DUALNUM
| lwzux TMP0, RA, BASE
| addi PC, PC, 4
| lwz CARG2, 4(RA)
| lwzux TMP1, RD, BASE
| lwz TMP2, -4(PC)
| checknum cr0, TMP0
| lwz CARG3, 4(RD)
| decode_RD4 TMP2, TMP2
| checknum cr1, TMP1
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| bne cr0, >7
| bne cr1, >8
| cmpw CARG2, CARG3
if (op == BC_ISLT) {
| bge >2
} else if (op == BC_ISGE) {
| blt >2
} else if (op == BC_ISLE) {
| bgt >2
} else {
| ble >2
}
|1:
| add PC, PC, TMP2
|2:
| ins_next
|
|7: // RA is not an integer.
| bgt cr0, ->vmeta_comp
| // RA is a number.
| lfd f0, 0(RA)
| bgt cr1, ->vmeta_comp
| blt cr1, >4
| // RA is a number, RD is an integer.
| tonum_i f1, CARG3
| b >5
|
|8: // RA is an integer, RD is not an integer.
| bgt cr1, ->vmeta_comp
| // RA is an integer, RD is a number.
| tonum_i f0, CARG2
|4:
| lfd f1, 0(RD)
|5:
| fcmpu cr0, f0, f1
if (op == BC_ISLT) {
| bge <2
} else if (op == BC_ISGE) {
| blt <2
} else if (op == BC_ISLE) {
| cror 4*cr0+lt, 4*cr0+lt, 4*cr0+eq
| bge <2
} else {
| cror 4*cr0+lt, 4*cr0+lt, 4*cr0+eq
| blt <2
}
| b <1
|.else
| lwzx TMP0, BASE, RA
| addi PC, PC, 4
| lfdx f0, BASE, RA
| lwzx TMP1, BASE, RD
| checknum cr0, TMP0
| lwz TMP2, -4(PC)
| lfdx f1, BASE, RD
| checknum cr1, TMP1
| decode_RD4 TMP2, TMP2
| bge cr0, ->vmeta_comp
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| bge cr1, ->vmeta_comp
| fcmpu cr0, f0, f1
if (op == BC_ISLT) {
| bge >1
} else if (op == BC_ISGE) {
| blt >1
} else if (op == BC_ISLE) {
| cror 4*cr0+lt, 4*cr0+lt, 4*cr0+eq
| bge >1
} else {
| cror 4*cr0+lt, 4*cr0+lt, 4*cr0+eq
| blt >1
}
| add PC, PC, TMP2
|1:
| ins_next
|.endif
break;
case BC_ISEQV: case BC_ISNEV:
vk = op == BC_ISEQV;
| // RA = src1*8, RD = src2*8, JMP with RD = target
|.if DUALNUM
| lwzux TMP0, RA, BASE
| addi PC, PC, 4
| lwz CARG2, 4(RA)
| lwzux TMP1, RD, BASE
| checknum cr0, TMP0
| lwz TMP2, -4(PC)
| checknum cr1, TMP1
| decode_RD4 TMP2, TMP2
| lwz CARG3, 4(RD)
| cror 4*cr7+gt, 4*cr0+gt, 4*cr1+gt
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
if (vk) {
| ble cr7, ->BC_ISEQN_Z
} else {
| ble cr7, ->BC_ISNEN_Z
}
|.else
| lwzux TMP0, RA, BASE
| lwz TMP2, 0(PC)
| lfd f0, 0(RA)
| addi PC, PC, 4
| lwzux TMP1, RD, BASE
| checknum cr0, TMP0
| decode_RD4 TMP2, TMP2
| lfd f1, 0(RD)
| checknum cr1, TMP1
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| bge cr0, >5
| bge cr1, >5
| fcmpu cr0, f0, f1
if (vk) {
| bne >1
| add PC, PC, TMP2
} else {
| beq >1
| add PC, PC, TMP2
}
|1:
| ins_next
|.endif
|5: // Either or both types are not numbers.
|.if not DUALNUM
| lwz CARG2, 4(RA)
| lwz CARG3, 4(RD)
|.endif
|.if FFI
| cmpwi cr7, TMP0, LJ_TCDATA
| cmpwi cr5, TMP1, LJ_TCDATA
|.endif
| not TMP3, TMP0
| cmplw TMP0, TMP1
| cmplwi cr1, TMP3, ~LJ_TISPRI // Primitive?
|.if FFI
| cror 4*cr7+eq, 4*cr7+eq, 4*cr5+eq
|.endif
| cmplwi cr6, TMP3, ~LJ_TISTABUD // Table or userdata?
|.if FFI
| beq cr7, ->vmeta_equal_cd
|.endif
| cmplw cr5, CARG2, CARG3
| crandc 4*cr0+gt, 4*cr0+eq, 4*cr1+gt // 2: Same type and primitive.
| crorc 4*cr0+lt, 4*cr5+eq, 4*cr0+eq // 1: Same tv or different type.
| crand 4*cr0+eq, 4*cr0+eq, 4*cr5+eq // 0: Same type and same tv.
| mr SAVE0, PC
| cror 4*cr0+eq, 4*cr0+eq, 4*cr0+gt // 0 or 2.
| cror 4*cr0+lt, 4*cr0+lt, 4*cr0+gt // 1 or 2.
if (vk) {
| bne cr0, >6
| add PC, PC, TMP2
|6:
} else {
| beq cr0, >6
| add PC, PC, TMP2
|6:
}
|.if DUALNUM
| bge cr0, >2 // Done if 1 or 2.
|1:
| ins_next
|2:
|.else
| blt cr0, <1 // Done if 1 or 2.
|.endif
| blt cr6, <1 // Done if not tab/ud.
|
| // Different tables or userdatas. Need to check __eq metamethod.
| // Field metatable must be at same offset for GCtab and GCudata!
| lwz TAB:TMP2, TAB:CARG2->metatable
| li CARG4, 1-vk // ne = 0 or 1.
| cmplwi TAB:TMP2, 0
| beq <1 // No metatable?
| lbz TMP2, TAB:TMP2->nomm
| andix. TMP2, TMP2, 1<<MM_eq
| bne <1 // Or 'no __eq' flag set?
| mr PC, SAVE0 // Restore old PC.
| b ->vmeta_equal // Handle __eq metamethod.
break;
case BC_ISEQS: case BC_ISNES:
vk = op == BC_ISEQS;
| // RA = src*8, RD = str_const*8 (~), JMP with RD = target
| lwzux TMP0, RA, BASE
| srwi RD, RD, 1
| lwz STR:TMP3, 4(RA)
| lwz TMP2, 0(PC)
| subfic RD, RD, -4
| addi PC, PC, 4
|.if FFI
| cmpwi TMP0, LJ_TCDATA
|.endif
| lwzx STR:TMP1, KBASE, RD // KBASE-4-str_const*4
| .gpr64 extsw TMP0, TMP0
| subfic TMP0, TMP0, LJ_TSTR
|.if FFI
| beq ->vmeta_equal_cd
|.endif
| sub TMP1, STR:TMP1, STR:TMP3
| or TMP0, TMP0, TMP1
| decode_RD4 TMP2, TMP2
| subfic TMP0, TMP0, 0
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| subfe TMP1, TMP1, TMP1
if (vk) {
| andc TMP2, TMP2, TMP1
} else {
| and TMP2, TMP2, TMP1
}
| add PC, PC, TMP2
| ins_next
break;
case BC_ISEQN: case BC_ISNEN:
vk = op == BC_ISEQN;
| // RA = src*8, RD = num_const*8, JMP with RD = target
|.if DUALNUM
| lwzux TMP0, RA, BASE
| addi PC, PC, 4
| lwz CARG2, 4(RA)
| lwzux TMP1, RD, KBASE
| checknum cr0, TMP0
| lwz TMP2, -4(PC)
| checknum cr1, TMP1
| decode_RD4 TMP2, TMP2
| lwz CARG3, 4(RD)
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
if (vk) {
|->BC_ISEQN_Z:
} else {
|->BC_ISNEN_Z:
}
| bne cr0, >7
| bne cr1, >8
| cmpw CARG2, CARG3
|4:
|.else
if (vk) {
|->BC_ISEQN_Z: // Dummy label.
} else {
|->BC_ISNEN_Z: // Dummy label.
}
| lwzx TMP0, BASE, RA
| addi PC, PC, 4
| lfdx f0, BASE, RA
| lwz TMP2, -4(PC)
| lfdx f1, KBASE, RD
| decode_RD4 TMP2, TMP2
| checknum TMP0
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| bge >3
| fcmpu cr0, f0, f1
|.endif
if (vk) {
| bne >1
| add PC, PC, TMP2
|1:
|.if not FFI
|3:
|.endif
} else {
| beq >2
|1:
|.if not FFI
|3:
|.endif
| add PC, PC, TMP2
|2:
}
| ins_next
|.if FFI
|3:
| cmpwi TMP0, LJ_TCDATA
| beq ->vmeta_equal_cd
| b <1
|.endif
|.if DUALNUM
|7: // RA is not an integer.
| bge cr0, <3
| // RA is a number.
| lfd f0, 0(RA)
| blt cr1, >1
| // RA is a number, RD is an integer.
| tonum_i f1, CARG3
| b >2
|
|8: // RA is an integer, RD is a number.
| tonum_i f0, CARG2
|1:
| lfd f1, 0(RD)
|2:
| fcmpu cr0, f0, f1
| b <4
|.endif
break;
case BC_ISEQP: case BC_ISNEP:
vk = op == BC_ISEQP;
| // RA = src*8, RD = primitive_type*8 (~), JMP with RD = target
| lwzx TMP0, BASE, RA
| srwi TMP1, RD, 3
| lwz TMP2, 0(PC)
| not TMP1, TMP1
| addi PC, PC, 4
|.if FFI
| cmpwi TMP0, LJ_TCDATA
|.endif
| sub TMP0, TMP0, TMP1
|.if FFI
| beq ->vmeta_equal_cd
|.endif
| decode_RD4 TMP2, TMP2
| .gpr64 extsw TMP0, TMP0
| addic TMP0, TMP0, -1
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
| subfe TMP1, TMP1, TMP1
if (vk) {
| and TMP2, TMP2, TMP1
} else {
| andc TMP2, TMP2, TMP1
}
| add PC, PC, TMP2
| ins_next
break;
/* -- Unary test and copy ops ------------------------------------------- */
case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
| // RA = dst*8 or unused, RD = src*8, JMP with RD = target
| lwzx TMP0, BASE, RD
| lwz INS, 0(PC)
| addi PC, PC, 4
if (op == BC_IST || op == BC_ISF) {
| .gpr64 extsw TMP0, TMP0
| subfic TMP0, TMP0, LJ_TTRUE
| decode_RD4 TMP2, INS
| subfe TMP1, TMP1, TMP1
| addis TMP2, TMP2, -(BCBIAS_J*4 >> 16)
if (op == BC_IST) {
| andc TMP2, TMP2, TMP1
} else {
| and TMP2, TMP2, TMP1
}
| add PC, PC, TMP2
} else {
| li TMP1, LJ_TFALSE
| lfdx f0, BASE, RD
| cmplw TMP0, TMP1
if (op == BC_ISTC) {
| bge >1
} else {
| blt >1
}
| addis PC, PC, -(BCBIAS_J*4 >> 16)
| decode_RD4 TMP2, INS
| stfdx f0, BASE, RA
| add PC, PC, TMP2
|1:
}
| ins_next
break;
case BC_ISTYPE:
| // RA = src*8, RD = -type*8
| lwzx TMP0, BASE, RA
| srwi TMP1, RD, 3
| ins_next1
|.if not PPE and not GPR64
| add. TMP0, TMP0, TMP1
|.else
| neg TMP1, TMP1
| cmpw TMP0, TMP1
|.endif
| bne ->vmeta_istype
| ins_next2
break;
case BC_ISNUM:
| // RA = src*8, RD = -(TISNUM-1)*8
| lwzx TMP0, BASE, RA
| ins_next1
| checknum TMP0
| bge ->vmeta_istype
| ins_next2
break;
/* -- Unary ops --------------------------------------------------------- */
case BC_MOV:
| // RA = dst*8, RD = src*8
| ins_next1
| lfdx f0, BASE, RD
| stfdx f0, BASE, RA
| ins_next2
break;
case BC_NOT:
| // RA = dst*8, RD = src*8
| ins_next1
| lwzx TMP0, BASE, RD
| .gpr64 extsw TMP0, TMP0
| subfic TMP1, TMP0, LJ_TTRUE
| adde TMP0, TMP0, TMP1
| stwx TMP0, BASE, RA
| ins_next2
break;
case BC_UNM:
| // RA = dst*8, RD = src*8
| lwzux TMP1, RD, BASE
| lwz TMP0, 4(RD)
| checknum TMP1
|.if DUALNUM
| bne >5
|.if GPR64
| lus TMP2, 0x8000
| neg TMP0, TMP0
| cmplw TMP0, TMP2
| beq >4
|.else
| nego. TMP0, TMP0
| bso >4
|1:
|.endif
| ins_next1
| stwux TISNUM, RA, BASE
| stw TMP0, 4(RA)
|3:
| ins_next2
|4:
|.if not GPR64
| // Potential overflow.
| checkov TMP1, <1 // Ignore unrelated overflow.
|.endif
| lus TMP1, 0x41e0 // 2^31.
| li TMP0, 0
| b >7
|.endif
|5:
| bge ->vmeta_unm
| xoris TMP1, TMP1, 0x8000
|7:
| ins_next1
| stwux TMP1, RA, BASE
| stw TMP0, 4(RA)
|.if DUALNUM
| b <3
|.else
| ins_next2
|.endif
break;
case BC_LEN:
| // RA = dst*8, RD = src*8
| lwzux TMP0, RD, BASE
| lwz CARG1, 4(RD)
| checkstr TMP0; bne >2
| lwz CRET1, STR:CARG1->len
|1:
|.if DUALNUM
| ins_next1
| stwux TISNUM, RA, BASE
| stw CRET1, 4(RA)
|.else
| tonum_u f0, CRET1 // Result is a non-negative integer.
| ins_next1
| stfdx f0, BASE, RA
|.endif
| ins_next2
|2:
| checktab TMP0; bne ->vmeta_len
#if LJ_52
| lwz TAB:TMP2, TAB:CARG1->metatable
| cmplwi TAB:TMP2, 0
| bne >9
|3:
#endif
|->BC_LEN_Z:
| bl extern lj_tab_len // (GCtab *t)
| // Returns uint32_t (but less than 2^31).
| b <1
#if LJ_52
|9:
| lbz TMP0, TAB:TMP2->nomm
| andix. TMP0, TMP0, 1<<MM_len
| bne <3 // 'no __len' flag set: done.
| b ->vmeta_len
#endif
break;
/* -- Binary ops -------------------------------------------------------- */
|.macro ins_arithpre
| // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8
||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
||switch (vk) {
||case 0:
| lwzx TMP1, BASE, RB
| .if DUALNUM
| lwzx TMP2, KBASE, RC
| .endif
| lfdx f14, BASE, RB
| lfdx f15, KBASE, RC
| .if DUALNUM
| checknum cr0, TMP1
| checknum cr1, TMP2
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| bge ->vmeta_arith_vn
| .else
| checknum TMP1; bge ->vmeta_arith_vn
| .endif
|| break;
||case 1:
| lwzx TMP1, BASE, RB
| .if DUALNUM
| lwzx TMP2, KBASE, RC
| .endif
| lfdx f15, BASE, RB
| lfdx f14, KBASE, RC
| .if DUALNUM
| checknum cr0, TMP1
| checknum cr1, TMP2
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| bge ->vmeta_arith_nv
| .else
| checknum TMP1; bge ->vmeta_arith_nv
| .endif
|| break;
||default:
| lwzx TMP1, BASE, RB
| lwzx TMP2, BASE, RC
| lfdx f14, BASE, RB
| lfdx f15, BASE, RC
| checknum cr0, TMP1
| checknum cr1, TMP2
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| bge ->vmeta_arith_vv
|| break;
||}
|.endmacro
|
|.macro ins_arithfallback, ins
||switch (vk) {
||case 0:
| ins ->vmeta_arith_vn2
|| break;
||case 1:
| ins ->vmeta_arith_nv2
|| break;
||default:
| ins ->vmeta_arith_vv2
|| break;
||}
|.endmacro
|
|.macro intmod, a, b, c
| bl ->vm_modi
|.endmacro
|
|.macro fpmod, a, b, c
|->BC_MODVN_Z:
| fdiv FARG1, b, c
| // NYI: Use internal implementation of floor.
| blex floor // floor(b/c)
| fmul a, FARG1, c
| fsub a, b, a // b - floor(b/c)*c
|.endmacro
|
|.macro ins_arithfp, fpins
| ins_arithpre
|.if "fpins" == "fpmod_"
| b ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
|.else
| fpins f0, f14, f15
| ins_next1
| stfdx f0, BASE, RA
| ins_next2
|.endif
|.endmacro
|
|.macro ins_arithdn, intins, fpins
| // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8
||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
||switch (vk) {
||case 0:
| lwzux TMP1, RB, BASE
| lwzux TMP2, RC, KBASE
| lwz CARG1, 4(RB)
| checknum cr0, TMP1
| lwz CARG2, 4(RC)
|| break;
||case 1:
| lwzux TMP1, RB, BASE
| lwzux TMP2, RC, KBASE
| lwz CARG2, 4(RB)
| checknum cr0, TMP1
| lwz CARG1, 4(RC)
|| break;
||default:
| lwzux TMP1, RB, BASE
| lwzux TMP2, RC, BASE
| lwz CARG1, 4(RB)
| checknum cr0, TMP1
| lwz CARG2, 4(RC)
|| break;
||}
| checknum cr1, TMP2
| bne >5
| bne cr1, >5
| intins CARG1, CARG1, CARG2
| bso >4
|1:
| ins_next1
| stwux TISNUM, RA, BASE
| stw CARG1, 4(RA)
|2:
| ins_next2
|4: // Overflow.
| checkov TMP0, <1 // Ignore unrelated overflow.
| ins_arithfallback b
|5: // FP variant.
||if (vk == 1) {
| lfd f15, 0(RB)
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| lfd f14, 0(RC)
||} else {
| lfd f14, 0(RB)
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| lfd f15, 0(RC)
||}
| ins_arithfallback bge
|.if "fpins" == "fpmod_"
| b ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
|.else
| fpins f0, f14, f15
| ins_next1
| stfdx f0, BASE, RA
| b <2
|.endif
|.endmacro
|
|.macro ins_arith, intins, fpins
|.if DUALNUM
| ins_arithdn intins, fpins
|.else
| ins_arithfp fpins
|.endif
|.endmacro
case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
|.if GPR64
|.macro addo32., y, a, b
| // Need to check overflow for (a<<32) + (b<<32).
| rldicr TMP0, a, 32, 31
| rldicr TMP3, b, 32, 31
| addo. TMP0, TMP0, TMP3
| add y, a, b
|.endmacro
| ins_arith addo32., fadd
|.else
| ins_arith addo., fadd
|.endif
break;
case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
|.if GPR64
|.macro subo32., y, a, b
| // Need to check overflow for (a<<32) - (b<<32).
| rldicr TMP0, a, 32, 31
| rldicr TMP3, b, 32, 31
| subo. TMP0, TMP0, TMP3
| sub y, a, b
|.endmacro
| ins_arith subo32., fsub
|.else
| ins_arith subo., fsub
|.endif
break;
case BC_MULVN: case BC_MULNV: case BC_MULVV:
| ins_arith mullwo., fmul
break;
case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
| ins_arithfp fdiv
break;
case BC_MODVN:
| ins_arith intmod, fpmod
break;
case BC_MODNV: case BC_MODVV:
| ins_arith intmod, fpmod_
break;
case BC_POW:
| // NYI: (partial) integer arithmetic.
| lwzx TMP1, BASE, RB
| lfdx FARG1, BASE, RB
| lwzx TMP2, BASE, RC
| lfdx FARG2, BASE, RC
| checknum cr0, TMP1
| checknum cr1, TMP2
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| bge ->vmeta_arith_vv
| blex pow
| ins_next1
| stfdx FARG1, BASE, RA
| ins_next2
break;
case BC_CAT:
| // RA = dst*8, RB = src_start*8, RC = src_end*8
| sub CARG3, RC, RB
| stp BASE, L->base
| add CARG2, BASE, RC
| mr SAVE0, RB
|->BC_CAT_Z:
| stw PC, SAVE_PC
| mr CARG1, L
| srwi CARG3, CARG3, 3
| bl extern lj_meta_cat // (lua_State *L, TValue *top, int left)
| // Returns NULL (finished) or TValue * (metamethod).
| cmplwi CRET1, 0
| lp BASE, L->base
| bne ->vmeta_binop
| ins_next1
| lfdx f0, BASE, SAVE0 // Copy result from RB to RA.
| stfdx f0, BASE, RA
| ins_next2
break;
/* -- Constant ops ------------------------------------------------------ */
case BC_KSTR:
| // RA = dst*8, RD = str_const*8 (~)
| srwi TMP1, RD, 1
| subfic TMP1, TMP1, -4
| ins_next1
| lwzx TMP0, KBASE, TMP1 // KBASE-4-str_const*4
| li TMP2, LJ_TSTR
| stwux TMP2, RA, BASE
| stw TMP0, 4(RA)
| ins_next2
break;
case BC_KCDATA:
|.if FFI
| // RA = dst*8, RD = cdata_const*8 (~)
| srwi TMP1, RD, 1
| subfic TMP1, TMP1, -4
| ins_next1
| lwzx TMP0, KBASE, TMP1 // KBASE-4-cdata_const*4
| li TMP2, LJ_TCDATA
| stwux TMP2, RA, BASE
| stw TMP0, 4(RA)
| ins_next2
|.endif
break;
case BC_KSHORT:
| // RA = dst*8, RD = int16_literal*8
|.if DUALNUM
| slwi RD, RD, 13
| srawi RD, RD, 16
| ins_next1
| stwux TISNUM, RA, BASE
| stw RD, 4(RA)
| ins_next2
|.else
| // The soft-float approach is faster.
| slwi RD, RD, 13
| srawi TMP1, RD, 31
| xor TMP2, TMP1, RD
| sub TMP2, TMP2, TMP1 // TMP2 = abs(x)
| cntlzw TMP3, TMP2
| subfic TMP1, TMP3, 0x40d // TMP1 = exponent-1
| slw TMP2, TMP2, TMP3 // TMP2 = left aligned mantissa
| subfic TMP3, RD, 0
| slwi TMP1, TMP1, 20
| rlwimi RD, TMP2, 21, 1, 31 // hi = sign(x) | (mantissa>>11)
| subfe TMP0, TMP0, TMP0
| add RD, RD, TMP1 // hi = hi + exponent-1
| and RD, RD, TMP0 // hi = x == 0 ? 0 : hi
| ins_next1
| stwux RD, RA, BASE
| stw ZERO, 4(RA)
| ins_next2
|.endif
break;
case BC_KNUM:
| // RA = dst*8, RD = num_const*8
| ins_next1
| lfdx f0, KBASE, RD
| stfdx f0, BASE, RA
| ins_next2
break;
case BC_KPRI:
| // RA = dst*8, RD = primitive_type*8 (~)
| srwi TMP1, RD, 3
| not TMP0, TMP1
| ins_next1
| stwx TMP0, BASE, RA
| ins_next2
break;
case BC_KNIL:
| // RA = base*8, RD = end*8
| stwx TISNIL, BASE, RA
| addi RA, RA, 8
|1:
| stwx TISNIL, BASE, RA
| cmpw RA, RD
| addi RA, RA, 8
| blt <1
| ins_next_
break;
/* -- Upvalue and function ops ------------------------------------------ */
case BC_UGET:
| // RA = dst*8, RD = uvnum*8
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| srwi RD, RD, 1
| addi RD, RD, offsetof(GCfuncL, uvptr)
| lwzx UPVAL:RB, LFUNC:RB, RD
| ins_next1
| lwz TMP1, UPVAL:RB->v
| lfd f0, 0(TMP1)
| stfdx f0, BASE, RA
| ins_next2
break;
case BC_USETV:
| // RA = uvnum*8, RD = src*8
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| srwi RA, RA, 1
| addi RA, RA, offsetof(GCfuncL, uvptr)
| lfdux f0, RD, BASE
| lwzx UPVAL:RB, LFUNC:RB, RA
| lbz TMP3, UPVAL:RB->marked
| lwz CARG2, UPVAL:RB->v
| andix. TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
| lbz TMP0, UPVAL:RB->closed
| lwz TMP2, 0(RD)
| stfd f0, 0(CARG2)
| cmplwi cr1, TMP0, 0
| lwz TMP1, 4(RD)
| cror 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
| subi TMP2, TMP2, (LJ_TNUMX+1)
| bne >2 // Upvalue is closed and black?
|1:
| ins_next
|
|2: // Check if new value is collectable.
| cmplwi TMP2, LJ_TISGCV - (LJ_TNUMX+1)
| bge <1 // tvisgcv(v)
| lbz TMP3, GCOBJ:TMP1->gch.marked
| andix. TMP3, TMP3, LJ_GC_WHITES // iswhite(v)
| la CARG1, GG_DISP2G(DISPATCH)
| // Crossed a write barrier. Move the barrier forward.
| beq <1
| bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
| b <1
break;
case BC_USETS:
| // RA = uvnum*8, RD = str_const*8 (~)
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| srwi TMP1, RD, 1
| srwi RA, RA, 1
| subfic TMP1, TMP1, -4
| addi RA, RA, offsetof(GCfuncL, uvptr)
| lwzx STR:TMP1, KBASE, TMP1 // KBASE-4-str_const*4
| lwzx UPVAL:RB, LFUNC:RB, RA
| lbz TMP3, UPVAL:RB->marked
| lwz CARG2, UPVAL:RB->v
| andix. TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
| lbz TMP3, STR:TMP1->marked
| lbz TMP2, UPVAL:RB->closed
| li TMP0, LJ_TSTR
| stw STR:TMP1, 4(CARG2)
| stw TMP0, 0(CARG2)
| bne >2
|1:
| ins_next
|
|2: // Check if string is white and ensure upvalue is closed.
| andix. TMP3, TMP3, LJ_GC_WHITES // iswhite(str)
| cmplwi cr1, TMP2, 0
| cror 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
| la CARG1, GG_DISP2G(DISPATCH)
| // Crossed a write barrier. Move the barrier forward.
| beq <1
| bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
| b <1
break;
case BC_USETN:
| // RA = uvnum*8, RD = num_const*8
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| srwi RA, RA, 1
| addi RA, RA, offsetof(GCfuncL, uvptr)
| lfdx f0, KBASE, RD
| lwzx UPVAL:RB, LFUNC:RB, RA
| ins_next1
| lwz TMP1, UPVAL:RB->v
| stfd f0, 0(TMP1)
| ins_next2
break;
case BC_USETP:
| // RA = uvnum*8, RD = primitive_type*8 (~)
| lwz LFUNC:RB, FRAME_FUNC(BASE)
| srwi RA, RA, 1
| srwi TMP0, RD, 3
| addi RA, RA, offsetof(GCfuncL, uvptr)
| not TMP0, TMP0
| lwzx UPVAL:RB, LFUNC:RB, RA
| ins_next1
| lwz TMP1, UPVAL:RB->v
| stw TMP0, 0(TMP1)
| ins_next2
break;
case BC_UCLO:
| // RA = level*8, RD = target
| lwz TMP1, L->openupval
| branch_RD // Do this first since RD is not saved.
| stp BASE, L->base
| cmplwi TMP1, 0
| mr CARG1, L
| beq >1
| add CARG2, BASE, RA
| bl extern lj_func_closeuv // (lua_State *L, TValue *level)
| lp BASE, L->base
|1:
| ins_next
break;
case BC_FNEW:
| // RA = dst*8, RD = proto_const*8 (~) (holding function prototype)
| srwi TMP1, RD, 1
| stp BASE, L->base
| subfic TMP1, TMP1, -4
| stw PC, SAVE_PC
| lwzx CARG2, KBASE, TMP1 // KBASE-4-tab_const*4
| mr CARG1, L
| lwz CARG3, FRAME_FUNC(BASE)
| // (lua_State *L, GCproto *pt, GCfuncL *parent)
| bl extern lj_func_newL_gc
| // Returns GCfuncL *.
| lp BASE, L->base
| li TMP0, LJ_TFUNC
| stwux TMP0, RA, BASE
| stw LFUNC:CRET1, 4(RA)
| ins_next
break;
/* -- Table ops --------------------------------------------------------- */
case BC_TNEW:
case BC_TDUP:
| // RA = dst*8, RD = (hbits|asize)*8 | tab_const*8 (~)
| lwz TMP0, DISPATCH_GL(gc.total)(DISPATCH)
| mr CARG1, L
| lwz TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
| stp BASE, L->base
| cmplw TMP0, TMP1
| stw PC, SAVE_PC
| bge >5
|1:
if (op == BC_TNEW) {
| rlwinm CARG2, RD, 29, 21, 31
| rlwinm CARG3, RD, 18, 27, 31
| cmpwi CARG2, 0x7ff; beq >3
|2:
| bl extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits)
| // Returns Table *.
} else {
| srwi TMP1, RD, 1
| subfic TMP1, TMP1, -4
| lwzx CARG2, KBASE, TMP1 // KBASE-4-tab_const*4
| bl extern lj_tab_dup // (lua_State *L, Table *kt)
| // Returns Table *.
}
| lp BASE, L->base
| li TMP0, LJ_TTAB
| stwux TMP0, RA, BASE
| stw TAB:CRET1, 4(RA)
| ins_next
if (op == BC_TNEW) {
|3:
| li CARG2, 0x801
| b <2
}
|5:
| mr SAVE0, RD
| bl extern lj_gc_step_fixtop // (lua_State *L)
| mr RD, SAVE0
| mr CARG1, L
| b <1
break;
case BC_GGET:
| // RA = dst*8, RD = str_const*8 (~)
case BC_GSET:
| // RA = src*8, RD = str_const*8 (~)
| lwz LFUNC:TMP2, FRAME_FUNC(BASE)
| srwi TMP1, RD, 1
| lwz TAB:RB, LFUNC:TMP2->env
| subfic TMP1, TMP1, -4
| lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
if (op == BC_GGET) {
| b ->BC_TGETS_Z
} else {
| b ->BC_TSETS_Z
}
break;
case BC_TGETV:
| // RA = dst*8, RB = table*8, RC = key*8
| lwzux CARG1, RB, BASE
| lwzux CARG2, RC, BASE
| lwz TAB:RB, 4(RB)
|.if DUALNUM
| lwz RC, 4(RC)
|.else
| lfd f0, 0(RC)
|.endif
| checktab CARG1
| checknum cr1, CARG2
| bne ->vmeta_tgetv
|.if DUALNUM
| lwz TMP0, TAB:RB->asize
| bne cr1, >5
| lwz TMP1, TAB:RB->array
| cmplw TMP0, RC
| slwi TMP2, RC, 3
|.else
| bge cr1, >5
| // Convert number key to integer, check for integerness and range.
| fctiwz f1, f0
| fadd f2, f0, TOBIT
| stfd f1, TMPD
| lwz TMP0, TAB:RB->asize
| fsub f2, f2, TOBIT
| lwz TMP2, TMPD_LO
| lwz TMP1, TAB:RB->array
| fcmpu cr1, f0, f2
| cmplw cr0, TMP0, TMP2
| crand 4*cr0+gt, 4*cr0+gt, 4*cr1+eq
| slwi TMP2, TMP2, 3
|.endif
| ble ->vmeta_tgetv // Integer key and in array part?
| lwzx TMP0, TMP1, TMP2
| lfdx f14, TMP1, TMP2
| checknil TMP0; beq >2
|1:
| ins_next1
| stfdx f14, BASE, RA
| ins_next2
|
|2: // Check for __index if table value is nil.
| lwz TAB:TMP2, TAB:RB->metatable
| cmplwi TAB:TMP2, 0
| beq <1 // No metatable: done.
| lbz TMP0, TAB:TMP2->nomm
| andix. TMP0, TMP0, 1<<MM_index
| bne <1 // 'no __index' flag set: done.
| b ->vmeta_tgetv
|
|5:
| checkstr CARG2; bne ->vmeta_tgetv
|.if not DUALNUM
| lwz STR:RC, 4(RC)
|.endif
| b ->BC_TGETS_Z // String key?
break;
case BC_TGETS:
| // RA = dst*8, RB = table*8, RC = str_const*8 (~)
| lwzux CARG1, RB, BASE
| srwi TMP1, RC, 1
| lwz TAB:RB, 4(RB)
| subfic TMP1, TMP1, -4
| checktab CARG1
| lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
| bne ->vmeta_tgets1
|->BC_TGETS_Z:
| // TAB:RB = GCtab *, STR:RC = GCstr *, RA = dst*8
| lwz TMP0, TAB:RB->hmask
| lwz TMP1, STR:RC->hash
| lwz NODE:TMP2, TAB:RB->node
| and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
| slwi TMP0, TMP1, 5
| slwi TMP1, TMP1, 3
| sub TMP1, TMP0, TMP1
| add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
|1:
| lwz CARG1, NODE:TMP2->key
| lwz TMP0, 4+offsetof(Node, key)(NODE:TMP2)
| lwz CARG2, NODE:TMP2->val
| lwz TMP1, 4+offsetof(Node, val)(NODE:TMP2)
| checkstr CARG1; bne >4
| cmpw TMP0, STR:RC; bne >4
| checknil CARG2; beq >5 // Key found, but nil value?
|3:
| stwux CARG2, RA, BASE
| stw TMP1, 4(RA)
| ins_next
|
|4: // Follow hash chain.
| lwz NODE:TMP2, NODE:TMP2->next
| cmplwi NODE:TMP2, 0
| bne <1
| // End of hash chain: key not found, nil result.
| li CARG2, LJ_TNIL
|
|5: // Check for __index if table value is nil.
| lwz TAB:TMP2, TAB:RB->metatable
| cmplwi TAB:TMP2, 0
| beq <3 // No metatable: done.
| lbz TMP0, TAB:TMP2->nomm
| andix. TMP0, TMP0, 1<<MM_index
| bne <3 // 'no __index' flag set: done.
| b ->vmeta_tgets
break;
case BC_TGETB:
| // RA = dst*8, RB = table*8, RC = index*8
| lwzux CARG1, RB, BASE
| srwi TMP0, RC, 3
| lwz TAB:RB, 4(RB)
| checktab CARG1; bne ->vmeta_tgetb
| lwz TMP1, TAB:RB->asize
| lwz TMP2, TAB:RB->array
| cmplw TMP0, TMP1; bge ->vmeta_tgetb
| lwzx TMP1, TMP2, RC
| lfdx f0, TMP2, RC
| checknil TMP1; beq >5
|1:
| ins_next1
| stfdx f0, BASE, RA
| ins_next2
|
|5: // Check for __index if table value is nil.
| lwz TAB:TMP2, TAB:RB->metatable
| cmplwi TAB:TMP2, 0
| beq <1 // No metatable: done.
| lbz TMP2, TAB:TMP2->nomm
| andix. TMP2, TMP2, 1<<MM_index
| bne <1 // 'no __index' flag set: done.
| b ->vmeta_tgetb // Caveat: preserve TMP0!
break;
case BC_TGETR:
| // RA = dst*8, RB = table*8, RC = key*8
| add RB, BASE, RB
| lwz TAB:CARG1, 4(RB)
|.if DUALNUM
| add RC, BASE, RC
| lwz TMP0, TAB:CARG1->asize
| lwz CARG2, 4(RC)
| lwz TMP1, TAB:CARG1->array
|.else
| lfdx f0, BASE, RC
| lwz TMP0, TAB:CARG1->asize
| toint CARG2, f0
| lwz TMP1, TAB:CARG1->array
|.endif
| cmplw TMP0, CARG2
| slwi TMP2, CARG2, 3
| ble ->vmeta_tgetr // In array part?
| lfdx f14, TMP1, TMP2
|->BC_TGETR_Z:
| ins_next1
| stfdx f14, BASE, RA
| ins_next2
break;
case BC_TSETV:
| // RA = src*8, RB = table*8, RC = key*8
| lwzux CARG1, RB, BASE
| lwzux CARG2, RC, BASE
| lwz TAB:RB, 4(RB)
|.if DUALNUM
| lwz RC, 4(RC)
|.else
| lfd f0, 0(RC)
|.endif
| checktab CARG1
| checknum cr1, CARG2
| bne ->vmeta_tsetv
|.if DUALNUM
| lwz TMP0, TAB:RB->asize
| bne cr1, >5
| lwz TMP1, TAB:RB->array
| cmplw TMP0, RC
| slwi TMP0, RC, 3
|.else
| bge cr1, >5
| // Convert number key to integer, check for integerness and range.
| fctiwz f1, f0
| fadd f2, f0, TOBIT
| stfd f1, TMPD
| lwz TMP0, TAB:RB->asize
| fsub f2, f2, TOBIT
| lwz TMP2, TMPD_LO
| lwz TMP1, TAB:RB->array
| fcmpu cr1, f0, f2
| cmplw cr0, TMP0, TMP2
| crand 4*cr0+gt, 4*cr0+gt, 4*cr1+eq
| slwi TMP0, TMP2, 3
|.endif
| ble ->vmeta_tsetv // Integer key and in array part?
| lwzx TMP2, TMP1, TMP0
| lbz TMP3, TAB:RB->marked
| lfdx f14, BASE, RA
| checknil TMP2; beq >3
|1:
| andix. TMP2, TMP3, LJ_GC_BLACK // isblack(table)
| stfdx f14, TMP1, TMP0
| bne >7
|2:
| ins_next
|
|3: // Check for __newindex if previous value is nil.
| lwz TAB:TMP2, TAB:RB->metatable
| cmplwi TAB:TMP2, 0
| beq <1 // No metatable: done.
| lbz TMP2, TAB:TMP2->nomm
| andix. TMP2, TMP2, 1<<MM_newindex
| bne <1 // 'no __newindex' flag set: done.
| b ->vmeta_tsetv
|
|5:
| checkstr CARG2; bne ->vmeta_tsetv
|.if not DUALNUM
| lwz STR:RC, 4(RC)
|.endif
| b ->BC_TSETS_Z // String key?
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, TMP3, TMP0
| b <2
break;
case BC_TSETS:
| // RA = src*8, RB = table*8, RC = str_const*8 (~)
| lwzux CARG1, RB, BASE
| srwi TMP1, RC, 1
| lwz TAB:RB, 4(RB)
| subfic TMP1, TMP1, -4
| checktab CARG1
| lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
| bne ->vmeta_tsets1
|->BC_TSETS_Z:
| // TAB:RB = GCtab *, STR:RC = GCstr *, RA = src*8
| lwz TMP0, TAB:RB->hmask
| lwz TMP1, STR:RC->hash
| lwz NODE:TMP2, TAB:RB->node
| stb ZERO, TAB:RB->nomm // Clear metamethod cache.
| and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
| lfdx f14, BASE, RA
| slwi TMP0, TMP1, 5
| slwi TMP1, TMP1, 3
| sub TMP1, TMP0, TMP1
| lbz TMP3, TAB:RB->marked
| add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
|1:
| lwz CARG1, NODE:TMP2->key
| lwz TMP0, 4+offsetof(Node, key)(NODE:TMP2)
| lwz CARG2, NODE:TMP2->val
| lwz NODE:TMP1, NODE:TMP2->next
| checkstr CARG1; bne >5
| cmpw TMP0, STR:RC; bne >5
| checknil CARG2; beq >4 // Key found, but nil value?
|2:
| andix. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
| stfd f14, NODE:TMP2->val
| bne >7
|3:
| ins_next
|
|4: // Check for __newindex if previous value is nil.
| lwz TAB:TMP1, TAB:RB->metatable
| cmplwi TAB:TMP1, 0
| beq <2 // No metatable: done.
| lbz TMP0, TAB:TMP1->nomm
| andix. TMP0, TMP0, 1<<MM_newindex
| bne <2 // 'no __newindex' flag set: done.
| b ->vmeta_tsets
|
|5: // Follow hash chain.
| cmplwi NODE:TMP1, 0
| mr NODE:TMP2, NODE:TMP1
| bne <1
| // End of hash chain: key not found, add a new one.
|
| // But check for __newindex first.
| lwz TAB:TMP1, TAB:RB->metatable
| la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
| stw PC, SAVE_PC
| mr CARG1, L
| cmplwi TAB:TMP1, 0
| stp BASE, L->base
| beq >6 // No metatable: continue.
| lbz TMP0, TAB:TMP1->nomm
| andix. TMP0, TMP0, 1<<MM_newindex
| beq ->vmeta_tsets // 'no __newindex' flag NOT set: check.
|6:
| li TMP0, LJ_TSTR
| stw STR:RC, 4(CARG3)
| mr CARG2, TAB:RB
| stw TMP0, 0(CARG3)
| bl extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k)
| // Returns TValue *.
| lp BASE, L->base
| stfd f14, 0(CRET1)
| b <3 // No 2nd write barrier needed.
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, TMP3, TMP0
| b <3
break;
case BC_TSETB:
| // RA = src*8, RB = table*8, RC = index*8
| lwzux CARG1, RB, BASE
| srwi TMP0, RC, 3
| lwz TAB:RB, 4(RB)
| checktab CARG1; bne ->vmeta_tsetb
| lwz TMP1, TAB:RB->asize
| lwz TMP2, TAB:RB->array
| lbz TMP3, TAB:RB->marked
| cmplw TMP0, TMP1
| lfdx f14, BASE, RA
| bge ->vmeta_tsetb
| lwzx TMP1, TMP2, RC
| checknil TMP1; beq >5
|1:
| andix. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
| stfdx f14, TMP2, RC
| bne >7
|2:
| ins_next
|
|5: // Check for __newindex if previous value is nil.
| lwz TAB:TMP1, TAB:RB->metatable
| cmplwi TAB:TMP1, 0
| beq <1 // No metatable: done.
| lbz TMP1, TAB:TMP1->nomm
| andix. TMP1, TMP1, 1<<MM_newindex
| bne <1 // 'no __newindex' flag set: done.
| b ->vmeta_tsetb // Caveat: preserve TMP0!
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, TMP3, TMP0
| b <2
break;
case BC_TSETR:
| // RA = dst*8, RB = table*8, RC = key*8
| add RB, BASE, RB
| lwz TAB:CARG2, 4(RB)
|.if DUALNUM
| add RC, BASE, RC
| lbz TMP3, TAB:CARG2->marked
| lwz TMP0, TAB:CARG2->asize
| lwz CARG3, 4(RC)
| lwz TMP1, TAB:CARG2->array
|.else
| lfdx f0, BASE, RC
| lbz TMP3, TAB:CARG2->marked
| lwz TMP0, TAB:CARG2->asize
| toint CARG3, f0
| lwz TMP1, TAB:CARG2->array
|.endif
| andix. TMP2, TMP3, LJ_GC_BLACK // isblack(table)
| bne >7
|2:
| cmplw TMP0, CARG3
| slwi TMP2, CARG3, 3
| lfdx f14, BASE, RA
| ble ->vmeta_tsetr // In array part?
| ins_next1
| stfdx f14, TMP1, TMP2
| ins_next2
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:CARG2, TMP3, TMP2
| b <2
break;
case BC_TSETM:
| // RA = base*8 (table at base-1), RD = num_const*8 (start index)
| add RA, BASE, RA
|1:
| add TMP3, KBASE, RD
| lwz TAB:CARG2, -4(RA) // Guaranteed to be a table.
| addic. TMP0, MULTRES, -8
| lwz TMP3, 4(TMP3) // Integer constant is in lo-word.
| srwi CARG3, TMP0, 3
| beq >4 // Nothing to copy?
| add CARG3, CARG3, TMP3
| lwz TMP2, TAB:CARG2->asize
| slwi TMP1, TMP3, 3
| lbz TMP3, TAB:CARG2->marked
| cmplw CARG3, TMP2
| add TMP2, RA, TMP0
| lwz TMP0, TAB:CARG2->array
| bgt >5
| add TMP1, TMP1, TMP0
| andix. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
|3: // Copy result slots to table.
| lfd f0, 0(RA)
| addi RA, RA, 8
| cmpw cr1, RA, TMP2
| stfd f0, 0(TMP1)
| addi TMP1, TMP1, 8
| blt cr1, <3
| bne >7
|4:
| ins_next
|
|5: // Need to resize array part.
| stp BASE, L->base
| mr CARG1, L
| stw PC, SAVE_PC
| mr SAVE0, RD
| bl extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
| // Must not reallocate the stack.
| mr RD, SAVE0
| b <1
|
|7: // Possible table write barrier for any value. Skip valiswhite check.
| barrierback TAB:CARG2, TMP3, TMP0
| b <4
break;
/* -- Calls and vararg handling ----------------------------------------- */
case BC_CALLM:
| // RA = base*8, (RB = (nresults+1)*8,) RC = extra_nargs*8
| add NARGS8:RC, NARGS8:RC, MULTRES
| // Fall through. Assumes BC_CALL follows.
break;
case BC_CALL:
| // RA = base*8, (RB = (nresults+1)*8,) RC = (nargs+1)*8
| mr TMP2, BASE
| lwzux TMP0, BASE, RA
| lwz LFUNC:RB, 4(BASE)
| subi NARGS8:RC, NARGS8:RC, 8
| addi BASE, BASE, 8
| checkfunc TMP0; bne ->vmeta_call
| ins_call
break;
case BC_CALLMT:
| // RA = base*8, (RB = 0,) RC = extra_nargs*8
| add NARGS8:RC, NARGS8:RC, MULTRES
| // Fall through. Assumes BC_CALLT follows.
break;
case BC_CALLT:
| // RA = base*8, (RB = 0,) RC = (nargs+1)*8
| lwzux TMP0, RA, BASE
| lwz LFUNC:RB, 4(RA)
| subi NARGS8:RC, NARGS8:RC, 8
| lwz TMP1, FRAME_PC(BASE)
| checkfunc TMP0
| addi RA, RA, 8
| bne ->vmeta_callt
|->BC_CALLT_Z:
| andix. TMP0, TMP1, FRAME_TYPE // Caveat: preserve cr0 until the crand.
| lbz TMP3, LFUNC:RB->ffid
| xori TMP2, TMP1, FRAME_VARG
| cmplwi cr1, NARGS8:RC, 0
| bne >7
|1:
| stw LFUNC:RB, FRAME_FUNC(BASE) // Copy function down, but keep PC.
| li TMP2, 0
| cmplwi cr7, TMP3, 1 // (> FF_C) Calling a fast function?
| beq cr1, >3
|2:
| addi TMP3, TMP2, 8
| lfdx f0, RA, TMP2
| cmplw cr1, TMP3, NARGS8:RC
| stfdx f0, BASE, TMP2
| mr TMP2, TMP3
| bne cr1, <2
|3:
| crand 4*cr0+eq, 4*cr0+eq, 4*cr7+gt
| beq >5
|4:
| ins_callt
|
|5: // Tailcall to a fast function with a Lua frame below.
| lwz INS, -4(TMP1)
| decode_RA8 RA, INS
| sub TMP1, BASE, RA
| lwz LFUNC:TMP1, FRAME_FUNC-8(TMP1)
| lwz TMP1, LFUNC:TMP1->pc
| lwz KBASE, PC2PROTO(k)(TMP1) // Need to prepare KBASE.
| b <4
|
|7: // Tailcall from a vararg function.
| andix. TMP0, TMP2, FRAME_TYPEP
| bne <1 // Vararg frame below?
| sub BASE, BASE, TMP2 // Relocate BASE down.
| lwz TMP1, FRAME_PC(BASE)
| andix. TMP0, TMP1, FRAME_TYPE
| b <1
break;
case BC_ITERC:
| // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 ((2+1)*8))
| mr TMP2, BASE
| add BASE, BASE, RA
| lwz TMP1, -24(BASE)
| lwz LFUNC:RB, -20(BASE)
| lfd f1, -8(BASE)
| lfd f0, -16(BASE)
| stw TMP1, 0(BASE) // Copy callable.
| stw LFUNC:RB, 4(BASE)
| checkfunc TMP1
| stfd f1, 16(BASE) // Copy control var.
| li NARGS8:RC, 16 // Iterators get 2 arguments.
| stfdu f0, 8(BASE) // Copy state.
| bne ->vmeta_call
| ins_call
break;
case BC_ITERN:
| // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 (2+1)*8)
|.if JIT
| // NYI: add hotloop, record BC_ITERN.
|.endif
| add RA, BASE, RA
| lwz TAB:RB, -12(RA)
| lwz RC, -4(RA) // Get index from control var.
| lwz TMP0, TAB:RB->asize
| lwz TMP1, TAB:RB->array
| addi PC, PC, 4
|1: // Traverse array part.
| cmplw RC, TMP0
| slwi TMP3, RC, 3
| bge >5 // Index points after array part?
| lwzx TMP2, TMP1, TMP3
| lfdx f0, TMP1, TMP3
| checknil TMP2
| lwz INS, -4(PC)
| beq >4
|.if DUALNUM
| stw RC, 4(RA)
| stw TISNUM, 0(RA)
|.else
| tonum_u f1, RC
|.endif
| addi RC, RC, 1
| addis TMP3, PC, -(BCBIAS_J*4 >> 16)
| stfd f0, 8(RA)
| decode_RD4 TMP1, INS
| stw RC, -4(RA) // Update control var.
| add PC, TMP1, TMP3
|.if not DUALNUM
| stfd f1, 0(RA)
|.endif
|3:
| ins_next
|
|4: // Skip holes in array part.
| addi RC, RC, 1
| b <1
|
|5: // Traverse hash part.
| lwz TMP1, TAB:RB->hmask
| sub RC, RC, TMP0
| lwz TMP2, TAB:RB->node
|6:
| cmplw RC, TMP1 // End of iteration? Branch to ITERL+1.
| slwi TMP3, RC, 5
| bgty <3
| slwi RB, RC, 3
| sub TMP3, TMP3, RB
| lwzx RB, TMP2, TMP3
| lfdx f0, TMP2, TMP3
| add NODE:TMP3, TMP2, TMP3
| checknil RB
| lwz INS, -4(PC)
| beq >7
| lfd f1, NODE:TMP3->key
| addis TMP2, PC, -(BCBIAS_J*4 >> 16)
| stfd f0, 8(RA)
| add RC, RC, TMP0
| decode_RD4 TMP1, INS
| stfd f1, 0(RA)
| addi RC, RC, 1
| add PC, TMP1, TMP2
| stw RC, -4(RA) // Update control var.
| b <3
|
|7: // Skip holes in hash part.
| addi RC, RC, 1
| b <6
break;
case BC_ISNEXT:
| // RA = base*8, RD = target (points to ITERN)
| add RA, BASE, RA
| lwz TMP0, -24(RA)
| lwz CFUNC:TMP1, -20(RA)
| lwz TMP2, -16(RA)
| lwz TMP3, -8(RA)
| cmpwi cr0, TMP2, LJ_TTAB
| cmpwi cr1, TMP0, LJ_TFUNC
| cmpwi cr6, TMP3, LJ_TNIL
| bne cr1, >5
| lbz TMP1, CFUNC:TMP1->ffid
| crand 4*cr0+eq, 4*cr0+eq, 4*cr6+eq
| cmpwi cr7, TMP1, FF_next_N
| srwi TMP0, RD, 1
| crand 4*cr0+eq, 4*cr0+eq, 4*cr7+eq
| add TMP3, PC, TMP0
| bne cr0, >5
| lus TMP1, 0xfffe
| ori TMP1, TMP1, 0x7fff
| stw ZERO, -4(RA) // Initialize control var.
| stw TMP1, -8(RA)
| addis PC, TMP3, -(BCBIAS_J*4 >> 16)
|1:
| ins_next
|5: // Despecialize bytecode if any of the checks fail.
| li TMP0, BC_JMP
| li TMP1, BC_ITERC
| stb TMP0, -1(PC)
| addis PC, TMP3, -(BCBIAS_J*4 >> 16)
| stb TMP1, 3(PC)
| b <1
break;
case BC_VARG:
| // RA = base*8, RB = (nresults+1)*8, RC = numparams*8
| lwz TMP0, FRAME_PC(BASE)
| add RC, BASE, RC
| add RA, BASE, RA
| addi RC, RC, FRAME_VARG
| add TMP2, RA, RB
| subi TMP3, BASE, 8 // TMP3 = vtop
| sub RC, RC, TMP0 // RC = vbase
| // Note: RC may now be even _above_ BASE if nargs was < numparams.
| cmplwi cr1, RB, 0
|.if PPE
| sub TMP1, TMP3, RC
| cmpwi TMP1, 0
|.else
| sub. TMP1, TMP3, RC
|.endif
| beq cr1, >5 // Copy all varargs?
| subi TMP2, TMP2, 16
| ble >2 // No vararg slots?
|1: // Copy vararg slots to destination slots.
| lfd f0, 0(RC)
| addi RC, RC, 8
| stfd f0, 0(RA)
| cmplw RA, TMP2
| cmplw cr1, RC, TMP3
| bge >3 // All destination slots filled?
| addi RA, RA, 8
| blt cr1, <1 // More vararg slots?
|2: // Fill up remainder with nil.
| stw TISNIL, 0(RA)
| cmplw RA, TMP2
| addi RA, RA, 8
| blt <2
|3:
| ins_next
|
|5: // Copy all varargs.
| lwz TMP0, L->maxstack
| li MULTRES, 8 // MULTRES = (0+1)*8
| bley <3 // No vararg slots?
| add TMP2, RA, TMP1
| cmplw TMP2, TMP0
| addi MULTRES, TMP1, 8
| bgt >7
|6:
| lfd f0, 0(RC)
| addi RC, RC, 8
| stfd f0, 0(RA)
| cmplw RC, TMP3
| addi RA, RA, 8
| blt <6 // More vararg slots?
| b <3
|
|7: // Grow stack for varargs.
| mr CARG1, L
| stp RA, L->top
| sub SAVE0, RC, BASE // Need delta, because BASE may change.
| stp BASE, L->base
| sub RA, RA, BASE
| stw PC, SAVE_PC
| srwi CARG2, TMP1, 3
| bl extern lj_state_growstack // (lua_State *L, int n)
| lp BASE, L->base
| add RA, BASE, RA
| add RC, BASE, SAVE0
| subi TMP3, BASE, 8
| b <6
break;
/* -- Returns ----------------------------------------------------------- */
case BC_RETM:
| // RA = results*8, RD = extra_nresults*8
| add RD, RD, MULTRES // MULTRES >= 8, so RD >= 8.
| // Fall through. Assumes BC_RET follows.
break;
case BC_RET:
| // RA = results*8, RD = (nresults+1)*8
| lwz PC, FRAME_PC(BASE)
| add RA, BASE, RA
| mr MULTRES, RD
|1:
| andix. TMP0, PC, FRAME_TYPE
| xori TMP1, PC, FRAME_VARG
| bne ->BC_RETV_Z
|
|->BC_RET_Z:
| // BASE = base, RA = resultptr, RD = (nresults+1)*8, PC = return
| lwz INS, -4(PC)
| cmpwi RD, 8
| subi TMP2, BASE, 8
| subi RC, RD, 8
| decode_RB8 RB, INS
| beq >3
| li TMP1, 0
|2:
| addi TMP3, TMP1, 8
| lfdx f0, RA, TMP1
| cmpw TMP3, RC
| stfdx f0, TMP2, TMP1
| beq >3
| addi TMP1, TMP3, 8
| lfdx f1, RA, TMP3
| cmpw TMP1, RC
| stfdx f1, TMP2, TMP3
| bne <2
|3:
|5:
| cmplw RB, RD
| decode_RA8 RA, INS
| bgt >6
| sub BASE, TMP2, RA
| lwz LFUNC:TMP1, FRAME_FUNC(BASE)
| ins_next1
| lwz TMP1, LFUNC:TMP1->pc
| lwz KBASE, PC2PROTO(k)(TMP1)
| ins_next2
|
|6: // Fill up results with nil.
| subi TMP1, RD, 8
| addi RD, RD, 8
| stwx TISNIL, TMP2, TMP1
| b <5
|
|->BC_RETV_Z: // Non-standard return case.
| andix. TMP2, TMP1, FRAME_TYPEP
| bne ->vm_return
| // Return from vararg function: relocate BASE down.
| sub BASE, BASE, TMP1
| lwz PC, FRAME_PC(BASE)
| b <1
break;
case BC_RET0: case BC_RET1:
| // RA = results*8, RD = (nresults+1)*8
| lwz PC, FRAME_PC(BASE)
| add RA, BASE, RA
| mr MULTRES, RD
| andix. TMP0, PC, FRAME_TYPE
| xori TMP1, PC, FRAME_VARG
| bney ->BC_RETV_Z
|
| lwz INS, -4(PC)
| subi TMP2, BASE, 8
| decode_RB8 RB, INS
if (op == BC_RET1) {
| lfd f0, 0(RA)
| stfd f0, 0(TMP2)
}
|5:
| cmplw RB, RD
| decode_RA8 RA, INS
| bgt >6
| sub BASE, TMP2, RA
| lwz LFUNC:TMP1, FRAME_FUNC(BASE)
| ins_next1
| lwz TMP1, LFUNC:TMP1->pc
| lwz KBASE, PC2PROTO(k)(TMP1)
| ins_next2
|
|6: // Fill up results with nil.
| subi TMP1, RD, 8
| addi RD, RD, 8
| stwx TISNIL, TMP2, TMP1
| b <5
break;
/* -- Loops and branches ------------------------------------------------ */
case BC_FORL:
|.if JIT
| hotloop
|.endif
| // Fall through. Assumes BC_IFORL follows.
break;
case BC_JFORI:
case BC_JFORL:
#if !LJ_HASJIT
break;
#endif
case BC_FORI:
case BC_IFORL:
| // RA = base*8, RD = target (after end of loop or start of loop)
vk = (op == BC_IFORL || op == BC_JFORL);
|.if DUALNUM
| // Integer loop.
| lwzux TMP1, RA, BASE
| lwz CARG1, FORL_IDX*8+4(RA)
| cmplw cr0, TMP1, TISNUM
if (vk) {
| lwz CARG3, FORL_STEP*8+4(RA)
| bne >9
|.if GPR64
| // Need to check overflow for (a<<32) + (b<<32).
| rldicr TMP0, CARG1, 32, 31
| rldicr TMP2, CARG3, 32, 31
| add CARG1, CARG1, CARG3
| addo. TMP0, TMP0, TMP2
|.else
| addo. CARG1, CARG1, CARG3
|.endif
| cmpwi cr6, CARG3, 0
| lwz CARG2, FORL_STOP*8+4(RA)
| bso >6
|4:
| stw CARG1, FORL_IDX*8+4(RA)
} else {
| lwz TMP3, FORL_STEP*8(RA)
| lwz CARG3, FORL_STEP*8+4(RA)
| lwz TMP2, FORL_STOP*8(RA)
| lwz CARG2, FORL_STOP*8+4(RA)
| cmplw cr7, TMP3, TISNUM
| cmplw cr1, TMP2, TISNUM
| crand 4*cr0+eq, 4*cr0+eq, 4*cr7+eq
| crand 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
| cmpwi cr6, CARG3, 0
| bne >9
}
| blt cr6, >5
| cmpw CARG1, CARG2
|1:
| stw TISNUM, FORL_EXT*8(RA)
if (op != BC_JFORL) {
| srwi RD, RD, 1
}
| stw CARG1, FORL_EXT*8+4(RA)
if (op != BC_JFORL) {
| add RD, PC, RD
}
if (op == BC_FORI) {
| bgt >3 // See FP loop below.
} else if (op == BC_JFORI) {
| addis PC, RD, -(BCBIAS_J*4 >> 16)
| bley >7
} else if (op == BC_IFORL) {
| bgt >2
| addis PC, RD, -(BCBIAS_J*4 >> 16)
} else {
| bley =>BC_JLOOP
}
|2:
| ins_next
|5: // Invert check for negative step.
| cmpw CARG2, CARG1
| b <1
if (vk) {
|6: // Potential overflow.
| checkov TMP0, <4 // Ignore unrelated overflow.
| b <2
}
|.endif
if (vk) {
|.if DUALNUM
|9: // FP loop.
| lfd f1, FORL_IDX*8(RA)
|.else
| lfdux f1, RA, BASE
|.endif
| lfd f3, FORL_STEP*8(RA)
| lfd f2, FORL_STOP*8(RA)
| lwz TMP3, FORL_STEP*8(RA)
| fadd f1, f1, f3
| stfd f1, FORL_IDX*8(RA)
} else {
|.if DUALNUM
|9: // FP loop.
|.else
| lwzux TMP1, RA, BASE
| lwz TMP3, FORL_STEP*8(RA)
| lwz TMP2, FORL_STOP*8(RA)
| cmplw cr0, TMP1, TISNUM
| cmplw cr7, TMP3, TISNUM
| cmplw cr1, TMP2, TISNUM
|.endif
| lfd f1, FORL_IDX*8(RA)
| crand 4*cr0+lt, 4*cr0+lt, 4*cr7+lt
| crand 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
| lfd f2, FORL_STOP*8(RA)
| bge ->vmeta_for
}
| cmpwi cr6, TMP3, 0
if (op != BC_JFORL) {
| srwi RD, RD, 1
}
| stfd f1, FORL_EXT*8(RA)
if (op != BC_JFORL) {
| add RD, PC, RD
}
| fcmpu cr0, f1, f2
if (op == BC_JFORI) {
| addis PC, RD, -(BCBIAS_J*4 >> 16)
}
| blt cr6, >5
if (op == BC_FORI) {
| bgt >3
} else if (op == BC_IFORL) {
|.if DUALNUM
| bgty <2
|.else
| bgt >2
|.endif
|1:
| addis PC, RD, -(BCBIAS_J*4 >> 16)
} else if (op == BC_JFORI) {
| bley >7
} else {
| bley =>BC_JLOOP
}
|.if DUALNUM
| b <2
|.else
|2:
| ins_next
|.endif
|5: // Negative step.
if (op == BC_FORI) {
| bge <2
|3: // Used by integer loop, too.
| addis PC, RD, -(BCBIAS_J*4 >> 16)
} else if (op == BC_IFORL) {
| bgey <1
} else if (op == BC_JFORI) {
| bgey >7
} else {
| bgey =>BC_JLOOP
}
| b <2
if (op == BC_JFORI) {
|7:
| lwz INS, -4(PC)
| decode_RD8 RD, INS
| b =>BC_JLOOP
}
break;
case BC_ITERL:
|.if JIT
| hotloop
|.endif
| // Fall through. Assumes BC_IITERL follows.
break;
case BC_JITERL:
#if !LJ_HASJIT
break;
#endif
case BC_IITERL:
| // RA = base*8, RD = target
| lwzux TMP1, RA, BASE
| lwz TMP2, 4(RA)
| checknil TMP1; beq >1 // Stop if iterator returned nil.
if (op == BC_JITERL) {
| stw TMP1, -8(RA)
| stw TMP2, -4(RA)
| b =>BC_JLOOP
} else {
| branch_RD // Otherwise save control var + branch.
| stw TMP1, -8(RA)
| stw TMP2, -4(RA)
}
|1:
| ins_next
break;
case BC_LOOP:
| // RA = base*8, RD = target (loop extent)
| // Note: RA/RD is only used by trace recorder to determine scope/extent
| // This opcode does NOT jump, it's only purpose is to detect a hot loop.
|.if JIT
| hotloop
|.endif
| // Fall through. Assumes BC_ILOOP follows.
break;
case BC_ILOOP:
| // RA = base*8, RD = target (loop extent)
| ins_next
break;
case BC_JLOOP:
|.if JIT
| // RA = base*8 (ignored), RD = traceno*8
| lwz TMP1, DISPATCH_J(trace)(DISPATCH)
| srwi RD, RD, 1
| // Traces on PPC don't store the trace number, so use 0.
| stw ZERO, DISPATCH_GL(vmstate)(DISPATCH)
| lwzx TRACE:TMP2, TMP1, RD
| clrso TMP1
| lp TMP2, TRACE:TMP2->mcode
| stw BASE, DISPATCH_GL(jit_base)(DISPATCH)
| mtctr TMP2
| addi JGL, DISPATCH, GG_DISP2G+32768
| stw L, DISPATCH_GL(tmpbuf.L)(DISPATCH)
| bctr
|.endif
break;
case BC_JMP:
| // RA = base*8 (only used by trace recorder), RD = target
| branch_RD
| ins_next
break;
/* -- Function headers -------------------------------------------------- */
case BC_FUNCF:
|.if JIT
| hotcall
|.endif
case BC_FUNCV: /* NYI: compiled vararg functions. */
| // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow.
break;
case BC_JFUNCF:
#if !LJ_HASJIT
break;
#endif
case BC_IFUNCF:
| // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
| lwz TMP2, L->maxstack
| lbz TMP1, -4+PC2PROTO(numparams)(PC)
| lwz KBASE, -4+PC2PROTO(k)(PC)
| cmplw RA, TMP2
| slwi TMP1, TMP1, 3
| bgt ->vm_growstack_l
if (op != BC_JFUNCF) {
| ins_next1
}
|2:
| cmplw NARGS8:RC, TMP1 // Check for missing parameters.
| blt >3
if (op == BC_JFUNCF) {
| decode_RD8 RD, INS
| b =>BC_JLOOP
} else {
| ins_next2
}
|
|3: // Clear missing parameters.
| stwx TISNIL, BASE, NARGS8:RC
| addi NARGS8:RC, NARGS8:RC, 8
| b <2
break;
case BC_JFUNCV:
#if !LJ_HASJIT
break;
#endif
| NYI // NYI: compiled vararg functions
break; /* NYI: compiled vararg functions. */
case BC_IFUNCV:
| // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
| lwz TMP2, L->maxstack
| add TMP1, BASE, RC
| add TMP0, RA, RC
| stw LFUNC:RB, 4(TMP1) // Store copy of LFUNC.
| addi TMP3, RC, 8+FRAME_VARG
| lwz KBASE, -4+PC2PROTO(k)(PC)
| cmplw TMP0, TMP2
| stw TMP3, 0(TMP1) // Store delta + FRAME_VARG.
| bge ->vm_growstack_l
| lbz TMP2, -4+PC2PROTO(numparams)(PC)
| mr RA, BASE
| mr RC, TMP1
| ins_next1
| cmpwi TMP2, 0
| addi BASE, TMP1, 8
| beq >3
|1:
| cmplw RA, RC // Less args than parameters?
| lwz TMP0, 0(RA)
| lwz TMP3, 4(RA)
| bge >4
| stw TISNIL, 0(RA) // Clear old fixarg slot (help the GC).
| addi RA, RA, 8
|2:
| addic. TMP2, TMP2, -1
| stw TMP0, 8(TMP1)
| stw TMP3, 12(TMP1)
| addi TMP1, TMP1, 8
| bne <1
|3:
| ins_next2
|
|4: // Clear missing parameters.
| li TMP0, LJ_TNIL
| b <2
break;
case BC_FUNCC:
case BC_FUNCCW:
| // BASE = new base, RA = BASE+framesize*8, RB = CFUNC, RC = nargs*8
if (op == BC_FUNCC) {
| lp RD, CFUNC:RB->f
} else {
| lp RD, DISPATCH_GL(wrapf)(DISPATCH)
}
| add TMP1, RA, NARGS8:RC
| lwz TMP2, L->maxstack
| .toc lp TMP3, 0(RD)
| add RC, BASE, NARGS8:RC
| stp BASE, L->base
| cmplw TMP1, TMP2
| stp RC, L->top
| li_vmstate C
|.if TOC
| mtctr TMP3
|.else
| mtctr RD
|.endif
if (op == BC_FUNCCW) {
| lp CARG2, CFUNC:RB->f
}
| mr CARG1, L
| bgt ->vm_growstack_c // Need to grow stack.
| .toc lp TOCREG, TOC_OFS(RD)
| .tocenv lp ENVREG, ENV_OFS(RD)
| st_vmstate
| bctrl // (lua_State *L [, lua_CFunction f])
| // Returns nresults.
| lp BASE, L->base
| .toc ld TOCREG, SAVE_TOC
| slwi RD, CRET1, 3
| lp TMP1, L->top
| li_vmstate INTERP
| lwz PC, FRAME_PC(BASE) // Fetch PC of caller.
| stw L, DISPATCH_GL(cur_L)(DISPATCH)
| sub RA, TMP1, RD // RA = L->top - nresults*8
| st_vmstate
| b ->vm_returnc
break;
/* ---------------------------------------------------------------------- */
default:
fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
exit(2);
break;
}
}
static int build_backend(BuildCtx *ctx)
{
int op;
dasm_growpc(Dst, BC__MAX);
build_subroutines(ctx);
|.code_op
for (op = 0; op < BC__MAX; op++)
build_ins(ctx, (BCOp)op, op);
return BC__MAX;
}
/* Emit pseudo frame-info for all assembler functions. */
static void emit_asm_debug(BuildCtx *ctx)
{
int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code);
int i;
switch (ctx->mode) {
case BUILD_elfasm:
fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n");
fprintf(ctx->fp,
".Lframe0:\n"
"\t.long .LECIE0-.LSCIE0\n"
".LSCIE0:\n"
"\t.long 0xffffffff\n"
"\t.byte 0x1\n"
"\t.string \"\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -4\n"
"\t.byte 65\n"
"\t.byte 0xc\n\t.uleb128 1\n\t.uleb128 0\n"
"\t.align 2\n"
".LECIE0:\n\n");
fprintf(ctx->fp,
".LSFDE0:\n"
"\t.long .LEFDE0-.LASFDE0\n"
".LASFDE0:\n"
"\t.long .Lframe0\n"
"\t.long .Lbegin\n"
"\t.long %d\n"
"\t.byte 0xe\n\t.uleb128 %d\n"
"\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
"\t.byte 0x5\n\t.uleb128 70\n\t.uleb128 55\n",
fcofs, CFRAME_SIZE);
for (i = 14; i <= 31; i++)
fprintf(ctx->fp,
"\t.byte %d\n\t.uleb128 %d\n"
"\t.byte %d\n\t.uleb128 %d\n",
0x80+i, 37+(31-i), 0x80+32+i, 2+2*(31-i));
fprintf(ctx->fp,
"\t.align 2\n"
".LEFDE0:\n\n");
#if LJ_HASFFI
fprintf(ctx->fp,
".LSFDE1:\n"
"\t.long .LEFDE1-.LASFDE1\n"
".LASFDE1:\n"
"\t.long .Lframe0\n"
#if LJ_TARGET_PS3
"\t.long .lj_vm_ffi_call\n"
#else
"\t.long lj_vm_ffi_call\n"
#endif
"\t.long %d\n"
"\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
"\t.byte 0x8e\n\t.uleb128 2\n"
"\t.byte 0xd\n\t.uleb128 0xe\n"
"\t.align 2\n"
".LEFDE1:\n\n", (int)ctx->codesz - fcofs);
#endif
#if !LJ_NO_UNWIND
fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n");
fprintf(ctx->fp,
".Lframe1:\n"
"\t.long .LECIE1-.LSCIE1\n"
".LSCIE1:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.string \"zPR\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -4\n"
"\t.byte 65\n"
"\t.uleb128 6\n" /* augmentation length */
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.long lj_err_unwind_dwarf-.\n"
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.uleb128 1\n\t.uleb128 0\n"
"\t.align 2\n"
".LECIE1:\n\n");
fprintf(ctx->fp,
".LSFDE2:\n"
"\t.long .LEFDE2-.LASFDE2\n"
".LASFDE2:\n"
"\t.long .LASFDE2-.Lframe1\n"
"\t.long .Lbegin-.\n"
"\t.long %d\n"
"\t.uleb128 0\n" /* augmentation length */
"\t.byte 0xe\n\t.uleb128 %d\n"
"\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
"\t.byte 0x5\n\t.uleb128 70\n\t.uleb128 55\n",
fcofs, CFRAME_SIZE);
for (i = 14; i <= 31; i++)
fprintf(ctx->fp,
"\t.byte %d\n\t.uleb128 %d\n"
"\t.byte %d\n\t.uleb128 %d\n",
0x80+i, 37+(31-i), 0x80+32+i, 2+2*(31-i));
fprintf(ctx->fp,
"\t.align 2\n"
".LEFDE2:\n\n");
#if LJ_HASFFI
fprintf(ctx->fp,
".Lframe2:\n"
"\t.long .LECIE2-.LSCIE2\n"
".LSCIE2:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.string \"zR\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -4\n"
"\t.byte 65\n"
"\t.uleb128 1\n" /* augmentation length */
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.uleb128 1\n\t.uleb128 0\n"
"\t.align 2\n"
".LECIE2:\n\n");
fprintf(ctx->fp,
".LSFDE3:\n"
"\t.long .LEFDE3-.LASFDE3\n"
".LASFDE3:\n"
"\t.long .LASFDE3-.Lframe2\n"
"\t.long lj_vm_ffi_call-.\n"
"\t.long %d\n"
"\t.uleb128 0\n" /* augmentation length */
"\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
"\t.byte 0x8e\n\t.uleb128 2\n"
"\t.byte 0xd\n\t.uleb128 0xe\n"
"\t.align 2\n"
".LEFDE3:\n\n", (int)ctx->codesz - fcofs);
#endif
#endif
break;
default:
break;
}
}
| xLua/build/luajit-2.1.0b2/src/vm_ppc.dasc/0 | {
"file_path": "xLua/build/luajit-2.1.0b2/src/vm_ppc.dasc",
"repo_id": "xLua",
"token_count": 74382
} | 2,116 |
<!DOCTYPE html>
<html>
<head>
<title>ffi.* API Functions</title>
<meta charset="utf-8">
<meta name="Copyright" content="Copyright (C) 2005-2021">
<meta name="Language" content="en">
<link rel="stylesheet" type="text/css" href="bluequad.css" media="screen">
<link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print">
<style type="text/css">
table.abitable { width: 30em; line-height: 1.2; }
tr.abihead td { font-weight: bold; }
td.abiparam { font-weight: bold; width: 6em; }
</style>
</head>
<body>
<div id="site">
<a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a>
</div>
<div id="head">
<h1><tt>ffi.*</tt> API Functions</h1>
</div>
<div id="nav">
<ul><li>
<a href="luajit.html">LuaJIT</a>
<ul><li>
<a href="https://luajit.org/download.html">Download <span class="ext">»</span></a>
</li><li>
<a href="install.html">Installation</a>
</li><li>
<a href="running.html">Running</a>
</li></ul>
</li><li>
<a href="extensions.html">Extensions</a>
<ul><li>
<a href="ext_ffi.html">FFI Library</a>
<ul><li>
<a href="ext_ffi_tutorial.html">FFI Tutorial</a>
</li><li>
<a class="current" href="ext_ffi_api.html">ffi.* API</a>
</li><li>
<a href="ext_ffi_semantics.html">FFI Semantics</a>
</li></ul>
</li><li>
<a href="ext_buffer.html">String Buffers</a>
</li><li>
<a href="ext_jit.html">jit.* Library</a>
</li><li>
<a href="ext_c_api.html">Lua/C API</a>
</li><li>
<a href="ext_profiler.html">Profiler</a>
</li></ul>
</li><li>
<a href="status.html">Status</a>
</li><li>
<a href="faq.html">FAQ</a>
</li><li>
<a href="http://wiki.luajit.org/">Wiki <span class="ext">»</span></a>
</li><li>
<a href="https://luajit.org/list.html">Mailing List <span class="ext">»</span></a>
</li></ul>
</div>
<div id="main">
<p>
This page describes the API functions provided by the FFI library in
detail. It's recommended to read through the
<a href="ext_ffi.html">introduction</a> and the
<a href="ext_ffi_tutorial.html">FFI tutorial</a> first.
</p>
<h2 id="glossary">Glossary</h2>
<ul>
<li><b>cdecl</b> — An abstract C type declaration (a Lua
string).</li>
<li><b>ctype</b> — A C type object. This is a special kind of
<b>cdata</b> returned by <tt>ffi.typeof()</tt>. It serves as a
<b>cdata</b> <a href="#ffi_new">constructor</a> when called.</li>
<li><b>cdata</b> — A C data object. It holds a value of the
corresponding <b>ctype</b>.</li>
<li><b>ct</b> — A C type specification which can be used for
most of the API functions. Either a <b>cdecl</b>, a <b>ctype</b> or a
<b>cdata</b> serving as a template type.</li>
<li><b>cb</b> — A callback object. This is a C data object
holding a special function pointer. Calling this function from
C code runs an associated Lua function.</li>
<li><b>VLA</b> — A variable-length array is declared with a
<tt>?</tt> instead of the number of elements, e.g. <tt>"int[?]"</tt>.
The number of elements (<tt>nelem</tt>) must be given when it's
<a href="#ffi_new">created</a>.</li>
<li><b>VLS</b> — A variable-length struct is a <tt>struct</tt> C
type where the last element is a <b>VLA</b>. The same rules for
declaration and creation apply.</li>
</ul>
<h2 id="decl">Declaring and Accessing External Symbols</h2>
<p>
External symbols must be declared first and can then be accessed by
indexing a <a href="ext_ffi_semantics.html#clib">C library
namespace</a>, which automatically binds the symbol to a specific
library.
</p>
<h3 id="ffi_cdef"><tt>ffi.cdef(def)</tt></h3>
<p>
Adds multiple C declarations for types or external symbols (named
variables or functions). <tt>def</tt> must be a Lua string. It's
recommended to use the syntactic sugar for string arguments as
follows:
</p>
<pre class="code">
ffi.cdef[[
<span style="color:#00a000;">typedef struct foo { int a, b; } foo_t; // Declare a struct and typedef.
int dofoo(foo_t *f, int n); /* Declare an external C function. */</span>
]]
</pre>
<p>
The contents of the string (the part in green above) must be a
sequence of
<a href="ext_ffi_semantics.html#clang">C declarations</a>,
separated by semicolons. The trailing semicolon for a single
declaration may be omitted.
</p>
<p>
Please note that external symbols are only <em>declared</em>, but they
are <em>not bound</em> to any specific address, yet. Binding is
achieved with C library namespaces (see below).
</p>
<p style="color: #c00000;">
C declarations are not passed through a C pre-processor,
yet. No pre-processor tokens are allowed, except for
<tt>#pragma pack</tt>. Replace <tt>#define</tt> in existing
C header files with <tt>enum</tt>, <tt>static const</tt>
or <tt>typedef</tt> and/or pass the files through an external
C pre-processor (once). Be careful not to include unneeded or
redundant declarations from unrelated header files.
</p>
<h3 id="ffi_C"><tt>ffi.C</tt></h3>
<p>
This is the default C library namespace — note the
uppercase <tt>'C'</tt>. It binds to the default set of symbols or
libraries on the target system. These are more or less the same as a
C compiler would offer by default, without specifying extra link
libraries.
</p>
<p>
On POSIX systems, this binds to symbols in the default or global
namespace. This includes all exported symbols from the executable and
any libraries loaded into the global namespace. This includes at least
<tt>libc</tt>, <tt>libm</tt>, <tt>libdl</tt> (on Linux),
<tt>libgcc</tt> (if compiled with GCC), as well as any exported
symbols from the Lua/C API provided by LuaJIT itself.
</p>
<p>
On Windows systems, this binds to symbols exported from the
<tt>*.exe</tt>, the <tt>lua51.dll</tt> (i.e. the Lua/C API
provided by LuaJIT itself), the C runtime library LuaJIT was linked
with (<tt>msvcrt*.dll</tt>), <tt>kernel32.dll</tt>,
<tt>user32.dll</tt> and <tt>gdi32.dll</tt>.
</p>
<h3 id="ffi_load"><tt>clib = ffi.load(name [,global])</tt></h3>
<p>
This loads the dynamic library given by <tt>name</tt> and returns
a new C library namespace which binds to its symbols. On POSIX
systems, if <tt>global</tt> is <tt>true</tt>, the library symbols are
loaded into the global namespace, too.
</p>
<p>
If <tt>name</tt> is a path, the library is loaded from this path.
Otherwise <tt>name</tt> is canonicalized in a system-dependent way and
searched in the default search path for dynamic libraries:
</p>
<p>
On POSIX systems, if the name contains no dot, the extension
<tt>.so</tt> is appended. Also, the <tt>lib</tt> prefix is prepended
if necessary. So <tt>ffi.load("z")</tt> looks for <tt>"libz.so"</tt>
in the default shared library search path.
</p>
<p>
On Windows systems, if the name contains no dot, the extension
<tt>.dll</tt> is appended. So <tt>ffi.load("ws2_32")</tt> looks for
<tt>"ws2_32.dll"</tt> in the default DLL search path.
</p>
<h2 id="create">Creating cdata Objects</h2>
<p>
The following API functions create cdata objects (<tt>type()</tt>
returns <tt>"cdata"</tt>). All created cdata objects are
<a href="ext_ffi_semantics.html#gc">garbage collected</a>.
</p>
<h3 id="ffi_new"><tt>cdata = ffi.new(ct [,nelem] [,init...])<br>
cdata = <em>ctype</em>([nelem,] [init...])</tt></h3>
<p>
Creates a cdata object for the given <tt>ct</tt>. VLA/VLS types
require the <tt>nelem</tt> argument. The second syntax uses a ctype as
a constructor and is otherwise fully equivalent.
</p>
<p>
The cdata object is initialized according to the
<a href="ext_ffi_semantics.html#init">rules for initializers</a>,
using the optional <tt>init</tt> arguments. Excess initializers cause
an error.
</p>
<p>
Performance notice: if you want to create many objects of one kind,
parse the cdecl only once and get its ctype with
<tt>ffi.typeof()</tt>. Then use the ctype as a constructor repeatedly.
</p>
<p style="font-size: 8pt;">
Please note that an anonymous <tt>struct</tt> declaration implicitly
creates a new and distinguished ctype every time you use it for
<tt>ffi.new()</tt>. This is probably <b>not</b> what you want,
especially if you create more than one cdata object. Different anonymous
<tt>structs</tt> are not considered assignment-compatible by the
C standard, even though they may have the same fields! Also, they
are considered different types by the JIT-compiler, which may cause an
excessive number of traces. It's strongly suggested to either declare
a named <tt>struct</tt> or <tt>typedef</tt> with <tt>ffi.cdef()</tt>
or to create a single ctype object for an anonymous <tt>struct</tt>
with <tt>ffi.typeof()</tt>.
</p>
<h3 id="ffi_typeof"><tt>ctype = ffi.typeof(ct)</tt></h3>
<p>
Creates a ctype object for the given <tt>ct</tt>.
</p>
<p>
This function is especially useful to parse a cdecl only once and then
use the resulting ctype object as a <a href="#ffi_new">constructor</a>.
</p>
<h3 id="ffi_cast"><tt>cdata = ffi.cast(ct, init)</tt></h3>
<p>
Creates a scalar cdata object for the given <tt>ct</tt>. The cdata
object is initialized with <tt>init</tt> using the "cast" variant of
the <a href="ext_ffi_semantics.html#convert">C type conversion
rules</a>.
</p>
<p>
This functions is mainly useful to override the pointer compatibility
checks or to convert pointers to addresses or vice versa.
</p>
<h3 id="ffi_metatype"><tt>ctype = ffi.metatype(ct, metatable)</tt></h3>
<p>
Creates a ctype object for the given <tt>ct</tt> and associates it with
a metatable. Only <tt>struct</tt>/<tt>union</tt> types, complex numbers
and vectors are allowed. Other types may be wrapped in a
<tt>struct</tt>, if needed.
</p>
<p>
The association with a metatable is permanent and cannot be changed
afterwards. Neither the contents of the <tt>metatable</tt> nor the
contents of an <tt>__index</tt> table (if any) may be modified
afterwards. The associated metatable automatically applies to all uses
of this type, no matter how the objects are created or where they
originate from. Note that pre-defined operations on types have
precedence (e.g. declared field names cannot be overridden).
</p>
<p>
All standard Lua metamethods are implemented. These are called directly,
without shortcuts and on any mix of types. For binary operations, the
left operand is checked first for a valid ctype metamethod. The
<tt>__gc</tt> metamethod only applies to <tt>struct</tt>/<tt>union</tt>
types and performs an implicit <a href="#ffi_gc"><tt>ffi.gc()</tt></a>
call during creation of an instance.
</p>
<h3 id="ffi_gc"><tt>cdata = ffi.gc(cdata, finalizer)</tt></h3>
<p>
Associates a finalizer with a pointer or aggregate cdata object. The
cdata object is returned unchanged.
</p>
<p>
This function allows safe integration of unmanaged resources into the
automatic memory management of the LuaJIT garbage collector. Typical
usage:
</p>
<pre class="code">
local p = ffi.gc(ffi.C.malloc(n), ffi.C.free)
...
p = nil -- Last reference to p is gone.
-- GC will eventually run finalizer: ffi.C.free(p)
</pre>
<p>
A cdata finalizer works like the <tt>__gc</tt> metamethod for userdata
objects: when the last reference to a cdata object is gone, the
associated finalizer is called with the cdata object as an argument. The
finalizer can be a Lua function or a cdata function or cdata function
pointer. An existing finalizer can be removed by setting a <tt>nil</tt>
finalizer, e.g. right before explicitly deleting a resource:
</p>
<pre class="code">
ffi.C.free(ffi.gc(p, nil)) -- Manually free the memory.
</pre>
<h2 id="info">C Type Information</h2>
<p>
The following API functions return information about C types.
They are most useful for inspecting cdata objects.
</p>
<h3 id="ffi_sizeof"><tt>size = ffi.sizeof(ct [,nelem])</tt></h3>
<p>
Returns the size of <tt>ct</tt> in bytes. Returns <tt>nil</tt> if
the size is not known (e.g. for <tt>"void"</tt> or function types).
Requires <tt>nelem</tt> for VLA/VLS types, except for cdata objects.
</p>
<h3 id="ffi_alignof"><tt>align = ffi.alignof(ct)</tt></h3>
<p>
Returns the minimum required alignment for <tt>ct</tt> in bytes.
</p>
<h3 id="ffi_offsetof"><tt>ofs [,bpos,bsize] = ffi.offsetof(ct, field)</tt></h3>
<p>
Returns the offset (in bytes) of <tt>field</tt> relative to the start
of <tt>ct</tt>, which must be a <tt>struct</tt>. Additionally returns
the position and the field size (in bits) for bit fields.
</p>
<h3 id="ffi_istype"><tt>status = ffi.istype(ct, obj)</tt></h3>
<p>
Returns <tt>true</tt> if <tt>obj</tt> has the C type given by
<tt>ct</tt>. Returns <tt>false</tt> otherwise.
</p>
<p>
C type qualifiers (<tt>const</tt> etc.) are ignored. Pointers are
checked with the standard pointer compatibility rules, but without any
special treatment for <tt>void *</tt>. If <tt>ct</tt> specifies a
<tt>struct</tt>/<tt>union</tt>, then a pointer to this type is accepted,
too. Otherwise the types must match exactly.
</p>
<p>
Note: this function accepts all kinds of Lua objects for the
<tt>obj</tt> argument, but always returns <tt>false</tt> for non-cdata
objects.
</p>
<h2 id="util">Utility Functions</h2>
<h3 id="ffi_errno"><tt>err = ffi.errno([newerr])</tt></h3>
<p>
Returns the error number set by the last C function call which
indicated an error condition. If the optional <tt>newerr</tt> argument
is present, the error number is set to the new value and the previous
value is returned.
</p>
<p>
This function offers a portable and OS-independent way to get and set the
error number. Note that only <em>some</em> C functions set the error
number. And it's only significant if the function actually indicated an
error condition (e.g. with a return value of <tt>-1</tt> or
<tt>NULL</tt>). Otherwise, it may or may not contain any previously set
value.
</p>
<p>
You're advised to call this function only when needed and as close as
possible after the return of the related C function. The
<tt>errno</tt> value is preserved across hooks, memory allocations,
invocations of the JIT compiler and other internal VM activity. The same
applies to the value returned by <tt>GetLastError()</tt> on Windows, but
you need to declare and call it yourself.
</p>
<h3 id="ffi_string"><tt>str = ffi.string(ptr [,len])</tt></h3>
<p>
Creates an interned Lua string from the data pointed to by
<tt>ptr</tt>.
</p>
<p>
If the optional argument <tt>len</tt> is missing, <tt>ptr</tt> is
converted to a <tt>"char *"</tt> and the data is assumed to be
zero-terminated. The length of the string is computed with
<tt>strlen()</tt>.
</p>
<p>
Otherwise <tt>ptr</tt> is converted to a <tt>"void *"</tt> and
<tt>len</tt> gives the length of the data. The data may contain
embedded zeros and need not be byte-oriented (though this may cause
endianess issues).
</p>
<p>
This function is mainly useful to convert (temporary)
<tt>"const char *"</tt> pointers returned by
C functions to Lua strings and store them or pass them to other
functions expecting a Lua string. The Lua string is an (interned) copy
of the data and bears no relation to the original data area anymore.
Lua strings are 8 bit clean and may be used to hold arbitrary,
non-character data.
</p>
<p>
Performance notice: it's faster to pass the length of the string, if
it's known. E.g. when the length is returned by a C call like
<tt>sprintf()</tt>.
</p>
<h3 id="ffi_copy"><tt>ffi.copy(dst, src, len)<br>
ffi.copy(dst, str)</tt></h3>
<p>
Copies the data pointed to by <tt>src</tt> to <tt>dst</tt>.
<tt>dst</tt> is converted to a <tt>"void *"</tt> and <tt>src</tt>
is converted to a <tt>"const void *"</tt>.
</p>
<p>
In the first syntax, <tt>len</tt> gives the number of bytes to copy.
Caveat: if <tt>src</tt> is a Lua string, then <tt>len</tt> must not
exceed <tt>#src+1</tt>.
</p>
<p>
In the second syntax, the source of the copy must be a Lua string. All
bytes of the string <em>plus a zero-terminator</em> are copied to
<tt>dst</tt> (i.e. <tt>#src+1</tt> bytes).
</p>
<p>
Performance notice: <tt>ffi.copy()</tt> may be used as a faster
(inlinable) replacement for the C library functions
<tt>memcpy()</tt>, <tt>strcpy()</tt> and <tt>strncpy()</tt>.
</p>
<h3 id="ffi_fill"><tt>ffi.fill(dst, len [,c])</tt></h3>
<p>
Fills the data pointed to by <tt>dst</tt> with <tt>len</tt> constant
bytes, given by <tt>c</tt>. If <tt>c</tt> is omitted, the data is
zero-filled.
</p>
<p>
Performance notice: <tt>ffi.fill()</tt> may be used as a faster
(inlinable) replacement for the C library function
<tt>memset(dst, c, len)</tt>. Please note the different
order of arguments!
</p>
<h2 id="target">Target-specific Information</h2>
<h3 id="ffi_abi"><tt>status = ffi.abi(param)</tt></h3>
<p>
Returns <tt>true</tt> if <tt>param</tt> (a Lua string) applies for the
target ABI (Application Binary Interface). Returns <tt>false</tt>
otherwise. The following parameters are currently defined:
</p>
<table class="abitable">
<tr class="abihead">
<td class="abiparam">Parameter</td>
<td class="abidesc">Description</td>
</tr>
<tr class="odd separate">
<td class="abiparam">32bit</td><td class="abidesc">32 bit architecture</td></tr>
<tr class="even">
<td class="abiparam">64bit</td><td class="abidesc">64 bit architecture</td></tr>
<tr class="odd separate">
<td class="abiparam">le</td><td class="abidesc">Little-endian architecture</td></tr>
<tr class="even">
<td class="abiparam">be</td><td class="abidesc">Big-endian architecture</td></tr>
<tr class="odd separate">
<td class="abiparam">fpu</td><td class="abidesc">Target has a hardware FPU</td></tr>
<tr class="even">
<td class="abiparam">softfp</td><td class="abidesc">softfp calling conventions</td></tr>
<tr class="odd">
<td class="abiparam">hardfp</td><td class="abidesc">hardfp calling conventions</td></tr>
<tr class="even separate">
<td class="abiparam">eabi</td><td class="abidesc">EABI variant of the standard ABI</td></tr>
<tr class="odd">
<td class="abiparam">win</td><td class="abidesc">Windows variant of the standard ABI</td></tr>
<tr class="even">
<td class="abiparam">uwp</td><td class="abidesc">Universal Windows Platform</td></tr>
<tr class="odd">
<td class="abiparam">gc64</td><td class="abidesc">64 bit GC references</td></tr>
</table>
<h3 id="ffi_os"><tt>ffi.os</tt></h3>
<p>
Contains the target OS name. Same contents as
<a href="ext_jit.html#jit_os"><tt>jit.os</tt></a>.
</p>
<h3 id="ffi_arch"><tt>ffi.arch</tt></h3>
<p>
Contains the target architecture name. Same contents as
<a href="ext_jit.html#jit_arch"><tt>jit.arch</tt></a>.
</p>
<h2 id="callback">Methods for Callbacks</h2>
<p>
The C types for <a href="ext_ffi_semantics.html#callback">callbacks</a>
have some extra methods:
</p>
<h3 id="callback_free"><tt>cb:free()</tt></h3>
<p>
Free the resources associated with a callback. The associated Lua
function is unanchored and may be garbage collected. The callback
function pointer is no longer valid and must not be called anymore
(it may be reused by a subsequently created callback).
</p>
<h3 id="callback_set"><tt>cb:set(func)</tt></h3>
<p>
Associate a new Lua function with a callback. The C type of the
callback and the callback function pointer are unchanged.
</p>
<p>
This method is useful to dynamically switch the receiver of callbacks
without creating a new callback each time and registering it again (e.g.
with a GUI library).
</p>
<h2 id="extended">Extended Standard Library Functions</h2>
<p>
The following standard library functions have been extended to work
with cdata objects:
</p>
<h3 id="tonumber"><tt>n = tonumber(cdata)</tt></h3>
<p>
Converts a number cdata object to a <tt>double</tt> and returns it as
a Lua number. This is particularly useful for boxed 64 bit
integer values. Caveat: this conversion may incur a precision loss.
</p>
<h3 id="tostring"><tt>s = tostring(cdata)</tt></h3>
<p>
Returns a string representation of the value of 64 bit integers
(<tt><b>"</b>nnn<b>LL"</b></tt> or <tt><b>"</b>nnn<b>ULL"</b></tt>) or
complex numbers (<tt><b>"</b>re±im<b>i"</b></tt>). Otherwise
returns a string representation of the C type of a ctype object
(<tt><b>"ctype<</b>type<b>>"</b></tt>) or a cdata object
(<tt><b>"cdata<</b>type<b>>: </b>address"</tt>), unless you
override it with a <tt>__tostring</tt> metamethod (see
<a href="#ffi_metatype"><tt>ffi.metatype()</tt></a>).
</p>
<h3 id="pairs"><tt>iter, obj, start = pairs(cdata)<br>
iter, obj, start = ipairs(cdata)<br></tt></h3>
<p>
Calls the <tt>__pairs</tt> or <tt>__ipairs</tt> metamethod of the
corresponding ctype.
</p>
<h2 id="literals">Extensions to the Lua Parser</h2>
<p>
The parser for Lua source code treats numeric literals with the
suffixes <tt>LL</tt> or <tt>ULL</tt> as signed or unsigned 64 bit
integers. Case doesn't matter, but uppercase is recommended for
readability. It handles decimal (<tt>42LL</tt>), hexadecimal
(<tt>0x2aLL</tt>) and binary (<tt>0b101010LL</tt>) literals.
</p>
<p>
The imaginary part of complex numbers can be specified by suffixing
number literals with <tt>i</tt> or <tt>I</tt>, e.g. <tt>12.5i</tt>.
Caveat: you'll need to use <tt>1i</tt> to get an imaginary part with
the value one, since <tt>i</tt> itself still refers to a variable
named <tt>i</tt>.
</p>
<br class="flush">
</div>
<div id="foot">
<hr class="hide">
Copyright © 2005-2021
<span class="noprint">
·
<a href="contact.html">Contact</a>
</span>
</div>
</body>
</html>
| xLua/build/luajit-2.1.0b3/doc/ext_ffi_api.html/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/doc/ext_ffi_api.html",
"repo_id": "xLua",
"token_count": 7582
} | 2,117 |
----------------------------------------------------------------------------
-- LuaJIT bytecode listing module.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module lists the bytecode of a Lua function. If it's loaded by -jbc
-- it hooks into the parser and lists all functions of a chunk as they
-- are parsed.
--
-- Example usage:
--
-- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)'
-- luajit -jbc=- foo.lua
-- luajit -jbc=foo.list foo.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_LISTFILE. The file is overwritten every time the module
-- is started.
--
-- This module can also be used programmatically:
--
-- local bc = require("jit.bc")
--
-- local function foo() print("hello") end
--
-- bc.dump(foo) --> -- BYTECODE -- [...]
-- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello"
--
-- local out = {
-- -- Do something with each line:
-- write = function(t, ...) io.write(...) end,
-- close = function(t) end,
-- flush = function(t) end,
-- }
-- bc.dump(foo, out)
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local bit = require("bit")
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, band, shr = string.byte, bit.band, bit.rshift
local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck
local funcuvname = jutil.funcuvname
local bcnames = vmdef.bcnames
local stdout, stderr = io.stdout, io.stderr
------------------------------------------------------------------------------
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
else return format("\\%03d", byte(c))
end
end
-- Return one bytecode line.
local function bcline(func, pc, prefix)
local ins, m = funcbc(func, pc)
if not ins then return end
local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128)
local a = band(shr(ins, 8), 0xff)
local oidx = 6*band(ins, 0xff)
local op = sub(bcnames, oidx+1, oidx+6)
local s = format("%04d %s %-6s %3s ",
pc, prefix or " ", op, ma == 0 and "" or a)
local d = shr(ins, 16)
if mc == 13*128 then -- BCMjump
return format("%s=> %04d\n", s, pc+d-0x7fff)
end
if mb ~= 0 then
d = band(d, 0xff)
elseif mc == 0 then
return s.."\n"
end
local kc
if mc == 10*128 then -- BCMstr
kc = funck(func, -d-1)
kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub))
elseif mc == 9*128 then -- BCMnum
kc = funck(func, d)
if op == "TSETM " then kc = kc - 2^52 end
elseif mc == 12*128 then -- BCMfunc
local fi = funcinfo(funck(func, -d-1))
if fi.ffid then
kc = vmdef.ffnames[fi.ffid]
else
kc = fi.loc
end
elseif mc == 5*128 then -- BCMuv
kc = funcuvname(func, d)
end
if ma == 5 then -- BCMuv
local ka = funcuvname(func, a)
if kc then kc = ka.." ; "..kc else kc = ka end
end
if mb ~= 0 then
local b = shr(ins, 24)
if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end
return format("%s%3d %3d\n", s, b, d)
end
if kc then return format("%s%3d ; %s\n", s, d, kc) end
if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits
return format("%s%3d\n", s, d)
end
-- Collect branch targets of a function.
local function bctargets(func)
local target = {}
for pc=1,1000000000 do
local ins, m = funcbc(func, pc)
if not ins then break end
if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end
end
return target
end
-- Dump bytecode instructions of a function.
local function bcdump(func, out, all)
if not out then out = stdout end
local fi = funcinfo(func)
if all and fi.children then
for n=-1,-1000000000,-1 do
local k = funck(func, n)
if not k then break end
if type(k) == "proto" then bcdump(k, out, true) end
end
end
out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined))
local target = bctargets(func)
for pc=1,1000000000 do
local s = bcline(func, pc, target[pc] and "=>")
if not s then break end
out:write(s)
end
out:write("\n")
out:flush()
end
------------------------------------------------------------------------------
-- Active flag and output file handle.
local active, out
-- List handler.
local function h_list(func)
return bcdump(func, out)
end
-- Detach list handler.
local function bclistoff()
if active then
active = false
jit.attach(h_list)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach list handler.
local function bcliston(outfile)
if active then bclistoff() end
if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(h_list, "bc")
active = true
end
-- Public module functions.
return {
line = bcline,
dump = bcdump,
targets = bctargets,
on = bcliston,
off = bclistoff,
start = bcliston -- For -j command line option.
}
| xLua/build/luajit-2.1.0b3/src/jit/bc.lua/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/jit/bc.lua",
"repo_id": "xLua",
"token_count": 2122
} | 2,118 |
----------------------------------------------------------------------------
-- Verbose mode of the LuaJIT compiler.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module shows verbose information about the progress of the
-- JIT compiler. It prints one line for each generated trace. This module
-- is useful to see which code has been compiled or where the compiler
-- punts and falls back to the interpreter.
--
-- Example usage:
--
-- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end"
-- luajit -jv=myapp.out myapp.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the
-- module is started.
--
-- The output from the first example should look like this:
--
-- [TRACE 1 (command line):1 loop]
-- [TRACE 2 (1/3) (command line):1 -> 1]
--
-- The first number in each line is the internal trace number. Next are
-- the file name ('(command line)') and the line number (':1') where the
-- trace has started. Side traces also show the parent trace number and
-- the exit number where they are attached to in parentheses ('(1/3)').
-- An arrow at the end shows where the trace links to ('-> 1'), unless
-- it loops to itself.
--
-- In this case the inner loop gets hot and is traced first, generating
-- a root trace. Then the last exit from the 1st trace gets hot, too,
-- and triggers generation of the 2nd trace. The side trace follows the
-- path along the outer loop and *around* the inner loop, back to its
-- start, and then links to the 1st trace. Yes, this may seem unusual,
-- if you know how traditional compilers work. Trace compilers are full
-- of surprises like this -- have fun! :-)
--
-- Aborted traces are shown like this:
--
-- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50]
--
-- Don't worry -- trace aborts are quite common, even in programs which
-- can be fully compiled. The compiler may retry several times until it
-- finds a suitable trace.
--
-- Of course this doesn't work with features that are not-yet-implemented
-- (NYI error messages). The VM simply falls back to the interpreter. This
-- may not matter at all if the particular trace is not very high up in
-- the CPU usage profile. Oh, and the interpreter is quite fast, too.
--
-- Also check out the -jdump module, which prints all the gory details.
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
local type, format = type, string.format
local stdout, stderr = io.stdout, io.stderr
-- Active flag and output file handle.
local active, out
------------------------------------------------------------------------------
local startloc, startex
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "start" then
startloc = fmtfunc(func, pc)
startex = otr and "("..otr.."/"..(oex == -1 and "stitch" or oex)..") " or ""
else
if what == "abort" then
local loc = fmtfunc(func, pc)
if loc ~= startloc then
out:write(format("[TRACE --- %s%s -- %s at %s]\n",
startex, startloc, fmterr(otr, oex), loc))
else
out:write(format("[TRACE --- %s%s -- %s]\n",
startex, startloc, fmterr(otr, oex)))
end
elseif what == "stop" then
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if ltype == "interpreter" then
out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
tr, startex, startloc))
elseif ltype == "stitch" then
out:write(format("[TRACE %3s %s%s %s %s]\n",
tr, startex, startloc, ltype, fmtfunc(func, pc)))
elseif link == tr or link == 0 then
out:write(format("[TRACE %3s %s%s %s]\n",
tr, startex, startloc, ltype))
elseif ltype == "root" then
out:write(format("[TRACE %3s %s%s -> %d]\n",
tr, startex, startloc, link))
else
out:write(format("[TRACE %3s %s%s -> %d %s]\n",
tr, startex, startloc, link, ltype))
end
else
out:write(format("[TRACE %s]\n", what))
end
out:flush()
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(outfile)
if active then dumpoff() end
if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(dump_trace, "trace")
active = true
end
-- Public module functions.
return {
on = dumpon,
off = dumpoff,
start = dumpon -- For -j command line option.
}
| xLua/build/luajit-2.1.0b3/src/jit/v.lua/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/jit/v.lua",
"repo_id": "xLua",
"token_count": 1872
} | 2,119 |
/*
** Table library.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
**
** Major portions taken verbatim or adapted from the Lua interpreter.
** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
*/
#define lib_table_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "lj_obj.h"
#include "lj_gc.h"
#include "lj_err.h"
#include "lj_buf.h"
#include "lj_tab.h"
#include "lj_ff.h"
#include "lj_lib.h"
/* ------------------------------------------------------------------------ */
#define LJLIB_MODULE_table
LJLIB_LUA(table_foreachi) /*
function(t, f)
CHECK_tab(t)
CHECK_func(f)
for i=1,#t do
local r = f(i, t[i])
if r ~= nil then return r end
end
end
*/
LJLIB_LUA(table_foreach) /*
function(t, f)
CHECK_tab(t)
CHECK_func(f)
for k, v in PAIRS(t) do
local r = f(k, v)
if r ~= nil then return r end
end
end
*/
LJLIB_LUA(table_getn) /*
function(t)
CHECK_tab(t)
return #t
end
*/
LJLIB_CF(table_maxn)
{
GCtab *t = lj_lib_checktab(L, 1);
TValue *array = tvref(t->array);
Node *node;
lua_Number m = 0;
ptrdiff_t i;
for (i = (ptrdiff_t)t->asize - 1; i >= 0; i--)
if (!tvisnil(&array[i])) {
m = (lua_Number)(int32_t)i;
break;
}
node = noderef(t->node);
for (i = (ptrdiff_t)t->hmask; i >= 0; i--)
if (!tvisnil(&node[i].val) && tvisnumber(&node[i].key)) {
lua_Number n = numberVnum(&node[i].key);
if (n > m) m = n;
}
setnumV(L->top-1, m);
return 1;
}
LJLIB_CF(table_insert) LJLIB_REC(.)
{
GCtab *t = lj_lib_checktab(L, 1);
int32_t n, i = (int32_t)lj_tab_len(t) + 1;
int nargs = (int)((char *)L->top - (char *)L->base);
if (nargs != 2*sizeof(TValue)) {
if (nargs != 3*sizeof(TValue))
lj_err_caller(L, LJ_ERR_TABINS);
/* NOBARRIER: This just moves existing elements around. */
for (n = lj_lib_checkint(L, 2); i > n; i--) {
/* The set may invalidate the get pointer, so need to do it first! */
TValue *dst = lj_tab_setint(L, t, i);
cTValue *src = lj_tab_getint(t, i-1);
if (src) {
copyTV(L, dst, src);
} else {
setnilV(dst);
}
}
i = n;
}
{
TValue *dst = lj_tab_setint(L, t, i);
copyTV(L, dst, L->top-1); /* Set new value. */
lj_gc_barriert(L, t, dst);
}
return 0;
}
LJLIB_LUA(table_remove) /*
function(t, pos)
CHECK_tab(t)
local len = #t
if pos == nil then
if len ~= 0 then
local old = t[len]
t[len] = nil
return old
end
else
CHECK_int(pos)
if pos >= 1 and pos <= len then
local old = t[pos]
for i=pos+1,len do
t[i-1] = t[i]
end
t[len] = nil
return old
end
end
end
*/
LJLIB_LUA(table_move) /*
function(a1, f, e, t, a2)
CHECK_tab(a1)
CHECK_int(f)
CHECK_int(e)
CHECK_int(t)
if a2 == nil then a2 = a1 end
CHECK_tab(a2)
if e >= f then
local d = t - f
if t > e or t <= f or a2 ~= a1 then
for i=f,e do a2[i+d] = a1[i] end
else
for i=e,f,-1 do a2[i+d] = a1[i] end
end
end
return a2
end
*/
LJLIB_CF(table_concat) LJLIB_REC(.)
{
GCtab *t = lj_lib_checktab(L, 1);
GCstr *sep = lj_lib_optstr(L, 2);
int32_t i = lj_lib_optint(L, 3, 1);
int32_t e = (L->base+3 < L->top && !tvisnil(L->base+3)) ?
lj_lib_checkint(L, 4) : (int32_t)lj_tab_len(t);
SBuf *sb = lj_buf_tmp_(L);
SBuf *sbx = lj_buf_puttab(sb, t, sep, i, e);
if (LJ_UNLIKELY(!sbx)) { /* Error: bad element type. */
int32_t idx = (int32_t)(intptr_t)sb->w;
cTValue *o = lj_tab_getint(t, idx);
lj_err_callerv(L, LJ_ERR_TABCAT,
lj_obj_itypename[o ? itypemap(o) : ~LJ_TNIL], idx);
}
setstrV(L, L->top-1, lj_buf_str(L, sbx));
lj_gc_check(L);
return 1;
}
/* ------------------------------------------------------------------------ */
static void set2(lua_State *L, int i, int j)
{
lua_rawseti(L, 1, i);
lua_rawseti(L, 1, j);
}
static int sort_comp(lua_State *L, int a, int b)
{
if (!lua_isnil(L, 2)) { /* function? */
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_call(L, 2, 1);
res = lua_toboolean(L, -1);
lua_pop(L, 1);
return res;
} else { /* a < b? */
return lua_lessthan(L, a, b);
}
}
static void auxsort(lua_State *L, 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);
if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
set2(L, 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);
if (sort_comp(L, -2, -1)) { /* a[i]<a[l]? */
set2(L, i, l);
} else {
lua_pop(L, 1); /* remove a[l] */
lua_rawgeti(L, 1, u);
if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
set2(L, i, u);
else
lua_pop(L, 2);
}
if (u-l == 2) break; /* only 3 elements */
lua_rawgeti(L, 1, i); /* Pivot */
lua_pushvalue(L, -1);
lua_rawgeti(L, 1, u-1);
set2(L, 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)) {
if (i>=u) lj_err_caller(L, LJ_ERR_TABSORT);
lua_pop(L, 1); /* remove a[i] */
}
/* repeat --j until a[j] <= P */
while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
if (j<=l) lj_err_caller(L, LJ_ERR_TABSORT);
lua_pop(L, 1); /* remove a[j] */
}
if (j<i) {
lua_pop(L, 3); /* pop pivot, a[i], a[j] */
break;
}
set2(L, 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] */
/* 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) {
j=l; i=i-1; l=i+2;
} else {
j=i+1; i=u; u=j-2;
}
auxsort(L, j, i); /* call recursively the smaller one */
} /* repeat the routine for the larger one */
}
LJLIB_CF(table_sort)
{
GCtab *t = lj_lib_checktab(L, 1);
int32_t n = (int32_t)lj_tab_len(t);
lua_settop(L, 2);
if (!tvisnil(L->base+1))
lj_lib_checkfunc(L, 2);
auxsort(L, 1, n);
return 0;
}
#if LJ_52
LJLIB_PUSH("n")
LJLIB_CF(table_pack)
{
TValue *array, *base = L->base;
MSize i, n = (uint32_t)(L->top - base);
GCtab *t = lj_tab_new(L, n ? n+1 : 0, 1);
/* NOBARRIER: The table is new (marked white). */
setintV(lj_tab_setstr(L, t, strV(lj_lib_upvalue(L, 1))), (int32_t)n);
for (array = tvref(t->array) + 1, i = 0; i < n; i++)
copyTV(L, &array[i], &base[i]);
settabV(L, base, t);
L->top = base+1;
lj_gc_check(L);
return 1;
}
#endif
LJLIB_NOREG LJLIB_CF(table_new) LJLIB_REC(.)
{
int32_t a = lj_lib_checkint(L, 1);
int32_t h = lj_lib_checkint(L, 2);
lua_createtable(L, a, h);
return 1;
}
LJLIB_NOREG LJLIB_CF(table_clear) LJLIB_REC(.)
{
lj_tab_clear(lj_lib_checktab(L, 1));
return 0;
}
static int luaopen_table_new(lua_State *L)
{
return lj_lib_postreg(L, lj_cf_table_new, FF_table_new, "new");
}
static int luaopen_table_clear(lua_State *L)
{
return lj_lib_postreg(L, lj_cf_table_clear, FF_table_clear, "clear");
}
/* ------------------------------------------------------------------------ */
#include "lj_libdef.h"
LUALIB_API int luaopen_table(lua_State *L)
{
LJ_LIB_REG(L, LUA_TABLIBNAME, table);
#if LJ_52
lua_getglobal(L, "unpack");
lua_setfield(L, -2, "unpack");
#endif
lj_lib_prereg(L, LUA_TABLIBNAME ".new", luaopen_table_new, tabV(L->top-1));
lj_lib_prereg(L, LUA_TABLIBNAME ".clear", luaopen_table_clear, tabV(L->top-1));
return 1;
}
| xLua/build/luajit-2.1.0b3/src/lib_table.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lib_table.c",
"repo_id": "xLua",
"token_count": 4112
} | 2,120 |
/*
** Bytecode dump definitions.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_BCDUMP_H
#define _LJ_BCDUMP_H
#include "lj_obj.h"
#include "lj_lex.h"
/* -- Bytecode dump format ------------------------------------------------ */
/*
** dump = header proto+ 0U
** header = ESC 'L' 'J' versionB flagsU [namelenU nameB*]
** proto = lengthU pdata
** pdata = phead bcinsW* uvdataH* kgc* knum* [debugB*]
** phead = flagsB numparamsB framesizeB numuvB numkgcU numknU numbcU
** [debuglenU [firstlineU numlineU]]
** kgc = kgctypeU { ktab | (loU hiU) | (rloU rhiU iloU ihiU) | strB* }
** knum = intU0 | (loU1 hiU)
** ktab = narrayU nhashU karray* khash*
** karray = ktabk
** khash = ktabk ktabk
** ktabk = ktabtypeU { intU | (loU hiU) | strB* }
**
** B = 8 bit, H = 16 bit, W = 32 bit, U = ULEB128 of W, U0/U1 = ULEB128 of W+1
*/
/* Bytecode dump header. */
#define BCDUMP_HEAD1 0x1b
#define BCDUMP_HEAD2 0x4c
#define BCDUMP_HEAD3 0x4a
/* If you perform *any* kind of private modifications to the bytecode itself
** or to the dump format, you *must* set BCDUMP_VERSION to 0x80 or higher.
*/
#define BCDUMP_VERSION 2
/* Compatibility flags. */
#define BCDUMP_F_BE 0x01
#define BCDUMP_F_STRIP 0x02
#define BCDUMP_F_FFI 0x04
#define BCDUMP_F_FR2 0x08
#define BCDUMP_F_KNOWN (BCDUMP_F_FR2*2-1)
/* Type codes for the GC constants of a prototype. Plus length for strings. */
enum {
BCDUMP_KGC_CHILD, BCDUMP_KGC_TAB, BCDUMP_KGC_I64, BCDUMP_KGC_U64,
BCDUMP_KGC_COMPLEX, BCDUMP_KGC_STR
};
/* Type codes for the keys/values of a constant table. */
enum {
BCDUMP_KTAB_NIL, BCDUMP_KTAB_FALSE, BCDUMP_KTAB_TRUE,
BCDUMP_KTAB_INT, BCDUMP_KTAB_NUM, BCDUMP_KTAB_STR
};
/* -- Bytecode reader/writer ---------------------------------------------- */
LJ_FUNC int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer,
void *data, int strip);
LJ_FUNC GCproto *lj_bcread_proto(LexState *ls);
LJ_FUNC GCproto *lj_bcread(LexState *ls);
#endif
| xLua/build/luajit-2.1.0b3/src/lj_bcdump.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_bcdump.h",
"repo_id": "xLua",
"token_count": 880
} | 2,121 |
/*
** Character types.
** Donated to the public domain.
*/
#ifndef _LJ_CHAR_H
#define _LJ_CHAR_H
#include "lj_def.h"
#define LJ_CHAR_CNTRL 0x01
#define LJ_CHAR_SPACE 0x02
#define LJ_CHAR_PUNCT 0x04
#define LJ_CHAR_DIGIT 0x08
#define LJ_CHAR_XDIGIT 0x10
#define LJ_CHAR_UPPER 0x20
#define LJ_CHAR_LOWER 0x40
#define LJ_CHAR_IDENT 0x80
#define LJ_CHAR_ALPHA (LJ_CHAR_LOWER|LJ_CHAR_UPPER)
#define LJ_CHAR_ALNUM (LJ_CHAR_ALPHA|LJ_CHAR_DIGIT)
#define LJ_CHAR_GRAPH (LJ_CHAR_ALNUM|LJ_CHAR_PUNCT)
/* Only pass -1 or 0..255 to these macros. Never pass a signed char! */
#define lj_char_isa(c, t) ((lj_char_bits+1)[(c)] & t)
#define lj_char_iscntrl(c) lj_char_isa((c), LJ_CHAR_CNTRL)
#define lj_char_isspace(c) lj_char_isa((c), LJ_CHAR_SPACE)
#define lj_char_ispunct(c) lj_char_isa((c), LJ_CHAR_PUNCT)
#define lj_char_isdigit(c) lj_char_isa((c), LJ_CHAR_DIGIT)
#define lj_char_isxdigit(c) lj_char_isa((c), LJ_CHAR_XDIGIT)
#define lj_char_isupper(c) lj_char_isa((c), LJ_CHAR_UPPER)
#define lj_char_islower(c) lj_char_isa((c), LJ_CHAR_LOWER)
#define lj_char_isident(c) lj_char_isa((c), LJ_CHAR_IDENT)
#define lj_char_isalpha(c) lj_char_isa((c), LJ_CHAR_ALPHA)
#define lj_char_isalnum(c) lj_char_isa((c), LJ_CHAR_ALNUM)
#define lj_char_isgraph(c) lj_char_isa((c), LJ_CHAR_GRAPH)
#define lj_char_toupper(c) ((c) - (lj_char_islower(c) >> 1))
#define lj_char_tolower(c) ((c) + lj_char_isupper(c))
LJ_DATA const uint8_t lj_char_bits[257];
#endif
| xLua/build/luajit-2.1.0b3/src/lj_char.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_char.h",
"repo_id": "xLua",
"token_count": 747
} | 2,122 |
/*
** MIPS instruction emitter.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#if LJ_64
static intptr_t get_k64val(ASMState *as, IRRef ref)
{
IRIns *ir = IR(ref);
if (ir->o == IR_KINT64) {
return (intptr_t)ir_kint64(ir)->u64;
} else if (ir->o == IR_KGC) {
return (intptr_t)ir_kgc(ir);
} else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
return (intptr_t)ir_kptr(ir);
} else if (LJ_SOFTFP && ir->o == IR_KNUM) {
return (intptr_t)ir_knum(ir)->u64;
} else {
lj_assertA(ir->o == IR_KINT || ir->o == IR_KNULL,
"bad 64 bit const IR op %d", ir->o);
return ir->i; /* Sign-extended. */
}
}
#endif
#if LJ_64
#define get_kval(as, ref) get_k64val(as, ref)
#else
#define get_kval(as, ref) (IR((ref))->i)
#endif
/* -- Emit basic instructions --------------------------------------------- */
static void emit_dst(ASMState *as, MIPSIns mi, Reg rd, Reg rs, Reg rt)
{
*--as->mcp = mi | MIPSF_D(rd) | MIPSF_S(rs) | MIPSF_T(rt);
}
static void emit_dta(ASMState *as, MIPSIns mi, Reg rd, Reg rt, uint32_t a)
{
*--as->mcp = mi | MIPSF_D(rd) | MIPSF_T(rt) | MIPSF_A(a);
}
#define emit_ds(as, mi, rd, rs) emit_dst(as, (mi), (rd), (rs), 0)
#define emit_tg(as, mi, rt, rg) emit_dst(as, (mi), (rg)&31, 0, (rt))
static void emit_tsi(ASMState *as, MIPSIns mi, Reg rt, Reg rs, int32_t i)
{
*--as->mcp = mi | MIPSF_T(rt) | MIPSF_S(rs) | (i & 0xffff);
}
#define emit_ti(as, mi, rt, i) emit_tsi(as, (mi), (rt), 0, (i))
#define emit_hsi(as, mi, rh, rs, i) emit_tsi(as, (mi), (rh) & 31, (rs), (i))
static void emit_fgh(ASMState *as, MIPSIns mi, Reg rf, Reg rg, Reg rh)
{
*--as->mcp = mi | MIPSF_F(rf&31) | MIPSF_G(rg&31) | MIPSF_H(rh&31);
}
#define emit_fg(as, mi, rf, rg) emit_fgh(as, (mi), (rf), (rg), 0)
static void emit_rotr(ASMState *as, Reg dest, Reg src, Reg tmp, uint32_t shift)
{
if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) {
emit_dta(as, MIPSI_ROTR, dest, src, shift);
} else {
emit_dst(as, MIPSI_OR, dest, dest, tmp);
emit_dta(as, MIPSI_SLL, dest, src, (-shift)&31);
emit_dta(as, MIPSI_SRL, tmp, src, shift);
}
}
#if LJ_64 || LJ_HASBUFFER
static void emit_tsml(ASMState *as, MIPSIns mi, Reg rt, Reg rs, uint32_t msb,
uint32_t lsb)
{
*--as->mcp = mi | MIPSF_T(rt) | MIPSF_S(rs) | MIPSF_M(msb) | MIPSF_L(lsb);
}
#endif
/* -- Emit loads/stores --------------------------------------------------- */
/* Prefer rematerialization of BASE/L from global_State over spills. */
#define emit_canremat(ref) ((ref) <= REF_BASE)
/* Try to find a one step delta relative to another constant. */
static int emit_kdelta1(ASMState *as, Reg rd, intptr_t i)
{
RegSet work = ~as->freeset & RSET_GPR;
while (work) {
Reg r = rset_picktop(work);
IRRef ref = regcost_ref(as->cost[r]);
lj_assertA(r != rd, "dest reg %d not free", rd);
if (ref < ASMREF_L) {
intptr_t delta = (intptr_t)((uintptr_t)i -
(uintptr_t)(ra_iskref(ref) ? ra_krefk(as, ref) : get_kval(as, ref)));
if (checki16(delta)) {
emit_tsi(as, MIPSI_AADDIU, rd, r, delta);
return 1;
}
}
rset_clear(work, r);
}
return 0; /* Failed. */
}
/* Load a 32 bit constant into a GPR. */
static void emit_loadi(ASMState *as, Reg r, int32_t i)
{
if (checki16(i)) {
emit_ti(as, MIPSI_LI, r, i);
} else {
if ((i & 0xffff)) {
intptr_t jgl = (intptr_t)(void *)J2G(as->J);
if ((uintptr_t)(i-jgl) < 65536) {
emit_tsi(as, MIPSI_ADDIU, r, RID_JGL, i-jgl-32768);
return;
} else if (emit_kdelta1(as, r, i)) {
return;
} else if ((i >> 16) == 0) {
emit_tsi(as, MIPSI_ORI, r, RID_ZERO, i);
return;
}
emit_tsi(as, MIPSI_ORI, r, r, i);
}
emit_ti(as, MIPSI_LUI, r, (i >> 16));
}
}
#if LJ_64
/* Load a 64 bit constant into a GPR. */
static void emit_loadu64(ASMState *as, Reg r, uint64_t u64)
{
if (checki32((int64_t)u64)) {
emit_loadi(as, r, (int32_t)u64);
} else {
uint64_t delta = u64 - (uint64_t)(void *)J2G(as->J);
if (delta < 65536) {
emit_tsi(as, MIPSI_DADDIU, r, RID_JGL, (int32_t)(delta-32768));
} else if (emit_kdelta1(as, r, (intptr_t)u64)) {
return;
} else {
/* TODO MIPSR6: Use DAHI & DATI. Caveat: sign-extension. */
if ((u64 & 0xffff)) {
emit_tsi(as, MIPSI_ORI, r, r, u64 & 0xffff);
}
if (((u64 >> 16) & 0xffff)) {
emit_dta(as, MIPSI_DSLL, r, r, 16);
emit_tsi(as, MIPSI_ORI, r, r, (u64 >> 16) & 0xffff);
emit_dta(as, MIPSI_DSLL, r, r, 16);
} else {
emit_dta(as, MIPSI_DSLL32, r, r, 0);
}
emit_loadi(as, r, (int32_t)(u64 >> 32));
}
/* TODO: There are probably more optimization opportunities. */
}
}
#define emit_loada(as, r, addr) emit_loadu64(as, (r), u64ptr((addr)))
#else
#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr)))
#endif
static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
static void ra_allockreg(ASMState *as, intptr_t k, Reg r);
/* Get/set from constant pointer. */
static void emit_lsptr(ASMState *as, MIPSIns mi, Reg r, void *p, RegSet allow)
{
intptr_t jgl = (intptr_t)(J2G(as->J));
intptr_t i = (intptr_t)(p);
Reg base;
if ((uint32_t)(i-jgl) < 65536) {
i = i-jgl-32768;
base = RID_JGL;
} else {
base = ra_allock(as, i-(int16_t)i, allow);
}
emit_tsi(as, mi, r, base, i);
}
#if LJ_64
static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
{
const uint64_t *k = &ir_k64(ir)->u64;
Reg r64 = r;
if (rset_test(RSET_FPR, r)) {
r64 = RID_TMP;
emit_tg(as, MIPSI_DMTC1, r64, r);
}
if ((uint32_t)((intptr_t)k-(intptr_t)J2G(as->J)) < 65536)
emit_lsptr(as, MIPSI_LD, r64, (void *)k, 0);
else
emit_loadu64(as, r64, *k);
}
#else
#define emit_loadk64(as, r, ir) \
emit_lsptr(as, MIPSI_LDC1, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR)
#endif
/* Get/set global_State fields. */
static void emit_lsglptr(ASMState *as, MIPSIns mi, Reg r, int32_t ofs)
{
emit_tsi(as, mi, r, RID_JGL, ofs-32768);
}
#define emit_getgl(as, r, field) \
emit_lsglptr(as, MIPSI_AL, (r), (int32_t)offsetof(global_State, field))
#define emit_setgl(as, r, field) \
emit_lsglptr(as, MIPSI_AS, (r), (int32_t)offsetof(global_State, field))
/* Trace number is determined from per-trace exit stubs. */
#define emit_setvmstate(as, i) UNUSED(i)
/* -- Emit control-flow instructions -------------------------------------- */
/* Label for internal jumps. */
typedef MCode *MCLabel;
/* Return label pointing to current PC. */
#define emit_label(as) ((as)->mcp)
static void emit_branch(ASMState *as, MIPSIns mi, Reg rs, Reg rt, MCode *target)
{
MCode *p = as->mcp;
ptrdiff_t delta = target - p;
lj_assertA(((delta + 0x8000) >> 16) == 0, "branch target out of range");
*--p = mi | MIPSF_S(rs) | MIPSF_T(rt) | ((uint32_t)delta & 0xffffu);
as->mcp = p;
}
static void emit_jmp(ASMState *as, MCode *target)
{
*--as->mcp = MIPSI_NOP;
emit_branch(as, MIPSI_B, RID_ZERO, RID_ZERO, (target));
}
static void emit_call(ASMState *as, void *target, int needcfa)
{
MCode *p = as->mcp;
#if LJ_TARGET_MIPSR6
ptrdiff_t delta = (char *)target - (char *)p;
if ((((delta>>2) + 0x02000000) >> 26) == 0) { /* Try compact call first. */
*--p = MIPSI_BALC | (((uintptr_t)delta >>2) & 0x03ffffffu);
as->mcp = p;
return;
}
#endif
*--p = MIPSI_NOP; /* Delay slot. */
if ((((uintptr_t)target ^ (uintptr_t)p) >> 28) == 0) {
#if !LJ_TARGET_MIPSR6
*--p = (((uintptr_t)target & 1) ? MIPSI_JALX : MIPSI_JAL) |
(((uintptr_t)target >>2) & 0x03ffffffu);
#else
*--p = MIPSI_JAL | (((uintptr_t)target >>2) & 0x03ffffffu);
#endif
} else { /* Target out of range: need indirect call. */
*--p = MIPSI_JALR | MIPSF_S(RID_CFUNCADDR);
needcfa = 1;
}
as->mcp = p;
if (needcfa) ra_allockreg(as, (intptr_t)target, RID_CFUNCADDR);
}
/* -- Emit generic operations --------------------------------------------- */
#define emit_move(as, dst, src) \
emit_ds(as, MIPSI_MOVE, (dst), (src))
/* Generic move between two regs. */
static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
{
if (dst < RID_MAX_GPR)
emit_move(as, dst, src);
else
emit_fg(as, irt_isnum(ir->t) ? MIPSI_MOV_D : MIPSI_MOV_S, dst, src);
}
/* Generic load of register with base and (small) offset address. */
static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
{
if (r < RID_MAX_GPR)
emit_tsi(as, irt_is64(ir->t) ? MIPSI_LD : MIPSI_LW, r, base, ofs);
else
emit_tsi(as, irt_isnum(ir->t) ? MIPSI_LDC1 : MIPSI_LWC1,
(r & 31), base, ofs);
}
/* Generic store of register with base and (small) offset address. */
static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
{
if (r < RID_MAX_GPR)
emit_tsi(as, irt_is64(ir->t) ? MIPSI_SD : MIPSI_SW, r, base, ofs);
else
emit_tsi(as, irt_isnum(ir->t) ? MIPSI_SDC1 : MIPSI_SWC1,
(r&31), base, ofs);
}
/* Add offset to pointer. */
static void emit_addptr(ASMState *as, Reg r, int32_t ofs)
{
if (ofs) {
lj_assertA(checki16(ofs), "offset %d out of range", ofs);
emit_tsi(as, MIPSI_AADDIU, r, r, ofs);
}
}
#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs))
| xLua/build/luajit-2.1.0b3/src/lj_emit_mips.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_emit_mips.h",
"repo_id": "xLua",
"token_count": 4445
} | 2,123 |
/*
** SSA IR (Intermediate Representation) emitter.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_ir_c
#define LUA_CORE
/* For pointers to libc/libm functions. */
#include <stdio.h>
#include <math.h>
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_gc.h"
#include "lj_buf.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_ircall.h"
#include "lj_iropt.h"
#include "lj_trace.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#include "lj_cdata.h"
#include "lj_carith.h"
#endif
#include "lj_vm.h"
#include "lj_strscan.h"
#include "lj_serialize.h"
#include "lj_strfmt.h"
#include "lj_prng.h"
/* Some local macros to save typing. Undef'd at the end. */
#define IR(ref) (&J->cur.ir[(ref)])
#define fins (&J->fold.ins)
/* Pass IR on to next optimization in chain (FOLD). */
#define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
/* -- IR tables ----------------------------------------------------------- */
/* IR instruction modes. */
LJ_DATADEF const uint8_t lj_ir_mode[IR__MAX+1] = {
IRDEF(IRMODE)
0
};
/* IR type sizes. */
LJ_DATADEF const uint8_t lj_ir_type_size[IRT__MAX+1] = {
#define IRTSIZE(name, size) size,
IRTDEF(IRTSIZE)
#undef IRTSIZE
0
};
/* C call info for CALL* instructions. */
LJ_DATADEF const CCallInfo lj_ir_callinfo[] = {
#define IRCALLCI(cond, name, nargs, kind, type, flags) \
{ (ASMFunction)IRCALLCOND_##cond(name), \
(nargs)|(CCI_CALL_##kind)|(IRT_##type<<CCI_OTSHIFT)|(flags) },
IRCALLDEF(IRCALLCI)
#undef IRCALLCI
{ NULL, 0 }
};
/* -- IR emitter ---------------------------------------------------------- */
/* Grow IR buffer at the top. */
void LJ_FASTCALL lj_ir_growtop(jit_State *J)
{
IRIns *baseir = J->irbuf + J->irbotlim;
MSize szins = J->irtoplim - J->irbotlim;
if (szins) {
baseir = (IRIns *)lj_mem_realloc(J->L, baseir, szins*sizeof(IRIns),
2*szins*sizeof(IRIns));
J->irtoplim = J->irbotlim + 2*szins;
} else {
baseir = (IRIns *)lj_mem_realloc(J->L, NULL, 0, LJ_MIN_IRSZ*sizeof(IRIns));
J->irbotlim = REF_BASE - LJ_MIN_IRSZ/4;
J->irtoplim = J->irbotlim + LJ_MIN_IRSZ;
}
J->cur.ir = J->irbuf = baseir - J->irbotlim;
}
/* Grow IR buffer at the bottom or shift it up. */
static void lj_ir_growbot(jit_State *J)
{
IRIns *baseir = J->irbuf + J->irbotlim;
MSize szins = J->irtoplim - J->irbotlim;
lj_assertJ(szins != 0, "zero IR size");
lj_assertJ(J->cur.nk == J->irbotlim || J->cur.nk-1 == J->irbotlim,
"unexpected IR growth");
if (J->cur.nins + (szins >> 1) < J->irtoplim) {
/* More than half of the buffer is free on top: shift up by a quarter. */
MSize ofs = szins >> 2;
memmove(baseir + ofs, baseir, (J->cur.nins - J->irbotlim)*sizeof(IRIns));
J->irbotlim -= ofs;
J->irtoplim -= ofs;
J->cur.ir = J->irbuf = baseir - J->irbotlim;
} else {
/* Double the buffer size, but split the growth amongst top/bottom. */
IRIns *newbase = lj_mem_newt(J->L, 2*szins*sizeof(IRIns), IRIns);
MSize ofs = szins >= 256 ? 128 : (szins >> 1); /* Limit bottom growth. */
memcpy(newbase + ofs, baseir, (J->cur.nins - J->irbotlim)*sizeof(IRIns));
lj_mem_free(G(J->L), baseir, szins*sizeof(IRIns));
J->irbotlim -= ofs;
J->irtoplim = J->irbotlim + 2*szins;
J->cur.ir = J->irbuf = newbase - J->irbotlim;
}
}
/* Emit IR without any optimizations. */
TRef LJ_FASTCALL lj_ir_emit(jit_State *J)
{
IRRef ref = lj_ir_nextins(J);
IRIns *ir = IR(ref);
IROp op = fins->o;
ir->prev = J->chain[op];
J->chain[op] = (IRRef1)ref;
ir->o = op;
ir->op1 = fins->op1;
ir->op2 = fins->op2;
J->guardemit.irt |= fins->t.irt;
return TREF(ref, irt_t((ir->t = fins->t)));
}
/* Emit call to a C function. */
TRef lj_ir_call(jit_State *J, IRCallID id, ...)
{
const CCallInfo *ci = &lj_ir_callinfo[id];
uint32_t n = CCI_NARGS(ci);
TRef tr = TREF_NIL;
va_list argp;
va_start(argp, id);
if ((ci->flags & CCI_L)) n--;
if (n > 0)
tr = va_arg(argp, IRRef);
while (n-- > 1)
tr = emitir(IRT(IR_CARG, IRT_NIL), tr, va_arg(argp, IRRef));
va_end(argp);
if (CCI_OP(ci) == IR_CALLS)
J->needsnap = 1; /* Need snapshot after call with side effect. */
return emitir(CCI_OPTYPE(ci), tr, id);
}
/* Load field of type t from GG_State + offset. Must be 32 bit aligned. */
TRef lj_ir_ggfload(jit_State *J, IRType t, uintptr_t ofs)
{
lj_assertJ((ofs & 3) == 0, "unaligned GG_State field offset");
ofs >>= 2;
lj_assertJ(ofs >= IRFL__MAX && ofs <= 0x3ff,
"GG_State field offset breaks 10 bit FOLD key limit");
lj_ir_set(J, IRT(IR_FLOAD, t), REF_NIL, ofs);
return lj_opt_fold(J);
}
/* -- Interning of constants ---------------------------------------------- */
/*
** IR instructions for constants are kept between J->cur.nk >= ref < REF_BIAS.
** They are chained like all other instructions, but grow downwards.
** The are interned (like strings in the VM) to facilitate reference
** comparisons. The same constant must get the same reference.
*/
/* Get ref of next IR constant and optionally grow IR.
** Note: this may invalidate all IRIns *!
*/
static LJ_AINLINE IRRef ir_nextk(jit_State *J)
{
IRRef ref = J->cur.nk;
if (LJ_UNLIKELY(ref <= J->irbotlim)) lj_ir_growbot(J);
J->cur.nk = --ref;
return ref;
}
/* Get ref of next 64 bit IR constant and optionally grow IR.
** Note: this may invalidate all IRIns *!
*/
static LJ_AINLINE IRRef ir_nextk64(jit_State *J)
{
IRRef ref = J->cur.nk - 2;
lj_assertJ(J->state != LJ_TRACE_ASM, "bad JIT state");
if (LJ_UNLIKELY(ref < J->irbotlim)) lj_ir_growbot(J);
J->cur.nk = ref;
return ref;
}
#if LJ_GC64
#define ir_nextkgc ir_nextk64
#else
#define ir_nextkgc ir_nextk
#endif
/* Intern int32_t constant. */
TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k)
{
IRIns *ir, *cir = J->cur.ir;
IRRef ref;
for (ref = J->chain[IR_KINT]; ref; ref = cir[ref].prev)
if (cir[ref].i == k)
goto found;
ref = ir_nextk(J);
ir = IR(ref);
ir->i = k;
ir->t.irt = IRT_INT;
ir->o = IR_KINT;
ir->prev = J->chain[IR_KINT];
J->chain[IR_KINT] = (IRRef1)ref;
found:
return TREF(ref, IRT_INT);
}
/* Intern 64 bit constant, given by its 64 bit pattern. */
TRef lj_ir_k64(jit_State *J, IROp op, uint64_t u64)
{
IRIns *ir, *cir = J->cur.ir;
IRRef ref;
IRType t = op == IR_KNUM ? IRT_NUM : IRT_I64;
for (ref = J->chain[op]; ref; ref = cir[ref].prev)
if (ir_k64(&cir[ref])->u64 == u64)
goto found;
ref = ir_nextk64(J);
ir = IR(ref);
ir[1].tv.u64 = u64;
ir->t.irt = t;
ir->o = op;
ir->op12 = 0;
ir->prev = J->chain[op];
J->chain[op] = (IRRef1)ref;
found:
return TREF(ref, t);
}
/* Intern FP constant, given by its 64 bit pattern. */
TRef lj_ir_knum_u64(jit_State *J, uint64_t u64)
{
return lj_ir_k64(J, IR_KNUM, u64);
}
/* Intern 64 bit integer constant. */
TRef lj_ir_kint64(jit_State *J, uint64_t u64)
{
return lj_ir_k64(J, IR_KINT64, u64);
}
/* Check whether a number is int and return it. -0 is NOT considered an int. */
static int numistrueint(lua_Number n, int32_t *kp)
{
int32_t k = lj_num2int(n);
if (n == (lua_Number)k) {
if (kp) *kp = k;
if (k == 0) { /* Special check for -0. */
TValue tv;
setnumV(&tv, n);
if (tv.u32.hi != 0)
return 0;
}
return 1;
}
return 0;
}
/* Intern number as int32_t constant if possible, otherwise as FP constant. */
TRef lj_ir_knumint(jit_State *J, lua_Number n)
{
int32_t k;
if (numistrueint(n, &k))
return lj_ir_kint(J, k);
else
return lj_ir_knum(J, n);
}
/* Intern GC object "constant". */
TRef lj_ir_kgc(jit_State *J, GCobj *o, IRType t)
{
IRIns *ir, *cir = J->cur.ir;
IRRef ref;
lj_assertJ(!isdead(J2G(J), o), "interning of dead GC object");
for (ref = J->chain[IR_KGC]; ref; ref = cir[ref].prev)
if (ir_kgc(&cir[ref]) == o)
goto found;
ref = ir_nextkgc(J);
ir = IR(ref);
/* NOBARRIER: Current trace is a GC root. */
ir->op12 = 0;
setgcref(ir[LJ_GC64].gcr, o);
ir->t.irt = (uint8_t)t;
ir->o = IR_KGC;
ir->prev = J->chain[IR_KGC];
J->chain[IR_KGC] = (IRRef1)ref;
found:
return TREF(ref, t);
}
/* Allocate GCtrace constant placeholder (no interning). */
TRef lj_ir_ktrace(jit_State *J)
{
IRRef ref = ir_nextkgc(J);
IRIns *ir = IR(ref);
lj_assertJ(irt_toitype_(IRT_P64) == LJ_TTRACE, "mismatched type mapping");
ir->t.irt = IRT_P64;
ir->o = LJ_GC64 ? IR_KNUM : IR_KNULL; /* Not IR_KGC yet, but same size. */
ir->op12 = 0;
ir->prev = 0;
return TREF(ref, IRT_P64);
}
/* Intern pointer constant. */
TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr)
{
IRIns *ir, *cir = J->cur.ir;
IRRef ref;
#if LJ_64 && !LJ_GC64
lj_assertJ((void *)(uintptr_t)u32ptr(ptr) == ptr, "out-of-range GC pointer");
#endif
for (ref = J->chain[op]; ref; ref = cir[ref].prev)
if (ir_kptr(&cir[ref]) == ptr)
goto found;
#if LJ_GC64
ref = ir_nextk64(J);
#else
ref = ir_nextk(J);
#endif
ir = IR(ref);
ir->op12 = 0;
setmref(ir[LJ_GC64].ptr, ptr);
ir->t.irt = IRT_PGC;
ir->o = op;
ir->prev = J->chain[op];
J->chain[op] = (IRRef1)ref;
found:
return TREF(ref, IRT_PGC);
}
/* Intern typed NULL constant. */
TRef lj_ir_knull(jit_State *J, IRType t)
{
IRIns *ir, *cir = J->cur.ir;
IRRef ref;
for (ref = J->chain[IR_KNULL]; ref; ref = cir[ref].prev)
if (irt_t(cir[ref].t) == t)
goto found;
ref = ir_nextk(J);
ir = IR(ref);
ir->i = 0;
ir->t.irt = (uint8_t)t;
ir->o = IR_KNULL;
ir->prev = J->chain[IR_KNULL];
J->chain[IR_KNULL] = (IRRef1)ref;
found:
return TREF(ref, t);
}
/* Intern key slot. */
TRef lj_ir_kslot(jit_State *J, TRef key, IRRef slot)
{
IRIns *ir, *cir = J->cur.ir;
IRRef2 op12 = IRREF2((IRRef1)key, (IRRef1)slot);
IRRef ref;
/* Const part is not touched by CSE/DCE, so 0-65535 is ok for IRMlit here. */
lj_assertJ(tref_isk(key) && slot == (IRRef)(IRRef1)slot,
"out-of-range key/slot");
for (ref = J->chain[IR_KSLOT]; ref; ref = cir[ref].prev)
if (cir[ref].op12 == op12)
goto found;
ref = ir_nextk(J);
ir = IR(ref);
ir->op12 = op12;
ir->t.irt = IRT_P32;
ir->o = IR_KSLOT;
ir->prev = J->chain[IR_KSLOT];
J->chain[IR_KSLOT] = (IRRef1)ref;
found:
return TREF(ref, IRT_P32);
}
/* -- Access to IR constants ---------------------------------------------- */
/* Copy value of IR constant. */
void lj_ir_kvalue(lua_State *L, TValue *tv, const IRIns *ir)
{
UNUSED(L);
lj_assertL(ir->o != IR_KSLOT, "unexpected KSLOT"); /* Common mistake. */
switch (ir->o) {
case IR_KPRI: setpriV(tv, irt_toitype(ir->t)); break;
case IR_KINT: setintV(tv, ir->i); break;
case IR_KGC: setgcV(L, tv, ir_kgc(ir), irt_toitype(ir->t)); break;
case IR_KPTR: case IR_KKPTR:
setnumV(tv, (lua_Number)(uintptr_t)ir_kptr(ir));
break;
case IR_KNULL: setintV(tv, 0); break;
case IR_KNUM: setnumV(tv, ir_knum(ir)->n); break;
#if LJ_HASFFI
case IR_KINT64: {
GCcdata *cd = lj_cdata_new_(L, CTID_INT64, 8);
*(uint64_t *)cdataptr(cd) = ir_kint64(ir)->u64;
setcdataV(L, tv, cd);
break;
}
#endif
default: lj_assertL(0, "bad IR constant op %d", ir->o); break;
}
}
/* -- Convert IR operand types -------------------------------------------- */
/* Convert from string to number. */
TRef LJ_FASTCALL lj_ir_tonumber(jit_State *J, TRef tr)
{
if (!tref_isnumber(tr)) {
if (tref_isstr(tr))
tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
else
lj_trace_err(J, LJ_TRERR_BADTYPE);
}
return tr;
}
/* Convert from integer or string to number. */
TRef LJ_FASTCALL lj_ir_tonum(jit_State *J, TRef tr)
{
if (!tref_isnum(tr)) {
if (tref_isinteger(tr))
tr = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
else if (tref_isstr(tr))
tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
else
lj_trace_err(J, LJ_TRERR_BADTYPE);
}
return tr;
}
/* Convert from integer or number to string. */
TRef LJ_FASTCALL lj_ir_tostr(jit_State *J, TRef tr)
{
if (!tref_isstr(tr)) {
if (!tref_isnumber(tr))
lj_trace_err(J, LJ_TRERR_BADTYPE);
tr = emitir(IRT(IR_TOSTR, IRT_STR), tr,
tref_isnum(tr) ? IRTOSTR_NUM : IRTOSTR_INT);
}
return tr;
}
/* -- Miscellaneous IR ops ------------------------------------------------ */
/* Evaluate numeric comparison. */
int lj_ir_numcmp(lua_Number a, lua_Number b, IROp op)
{
switch (op) {
case IR_EQ: return (a == b);
case IR_NE: return (a != b);
case IR_LT: return (a < b);
case IR_GE: return (a >= b);
case IR_LE: return (a <= b);
case IR_GT: return (a > b);
case IR_ULT: return !(a >= b);
case IR_UGE: return !(a < b);
case IR_ULE: return !(a > b);
case IR_UGT: return !(a <= b);
default: lj_assertX(0, "bad IR op %d", op); return 0;
}
}
/* Evaluate string comparison. */
int lj_ir_strcmp(GCstr *a, GCstr *b, IROp op)
{
int res = lj_str_cmp(a, b);
switch (op) {
case IR_LT: return (res < 0);
case IR_GE: return (res >= 0);
case IR_LE: return (res <= 0);
case IR_GT: return (res > 0);
default: lj_assertX(0, "bad IR op %d", op); return 0;
}
}
/* Rollback IR to previous state. */
void lj_ir_rollback(jit_State *J, IRRef ref)
{
IRRef nins = J->cur.nins;
while (nins > ref) {
IRIns *ir;
nins--;
ir = IR(nins);
J->chain[ir->o] = ir->prev;
}
J->cur.nins = nins;
}
#undef IR
#undef fins
#undef emitir
#endif
| xLua/build/luajit-2.1.0b3/src/lj_ir.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_ir.c",
"repo_id": "xLua",
"token_count": 6075
} | 2,124 |
/*
** DCE: Dead Code Elimination. Pre-LOOP only -- ASM already performs DCE.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_opt_dce_c
#define LUA_CORE
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_iropt.h"
/* Some local macros to save typing. Undef'd at the end. */
#define IR(ref) (&J->cur.ir[(ref)])
/* Scan through all snapshots and mark all referenced instructions. */
static void dce_marksnap(jit_State *J)
{
SnapNo i, nsnap = J->cur.nsnap;
for (i = 0; i < nsnap; i++) {
SnapShot *snap = &J->cur.snap[i];
SnapEntry *map = &J->cur.snapmap[snap->mapofs];
MSize n, nent = snap->nent;
for (n = 0; n < nent; n++) {
IRRef ref = snap_ref(map[n]);
if (ref >= REF_FIRST)
irt_setmark(IR(ref)->t);
}
}
}
/* Backwards propagate marks. Replace unused instructions with NOPs. */
static void dce_propagate(jit_State *J)
{
IRRef1 *pchain[IR__MAX];
IRRef ins;
uint32_t i;
for (i = 0; i < IR__MAX; i++) pchain[i] = &J->chain[i];
for (ins = J->cur.nins-1; ins >= REF_FIRST; ins--) {
IRIns *ir = IR(ins);
if (irt_ismarked(ir->t)) {
irt_clearmark(ir->t);
pchain[ir->o] = &ir->prev;
} else if (!ir_sideeff(ir)) {
*pchain[ir->o] = ir->prev; /* Reroute original instruction chain. */
lj_ir_nop(ir);
continue;
}
if (ir->op1 >= REF_FIRST) irt_setmark(IR(ir->op1)->t);
if (ir->op2 >= REF_FIRST) irt_setmark(IR(ir->op2)->t);
}
}
/* Dead Code Elimination.
**
** First backpropagate marks for all used instructions. Then replace
** the unused ones with a NOP. Note that compressing the IR to eliminate
** the NOPs does not pay off.
*/
void lj_opt_dce(jit_State *J)
{
if ((J->flags & JIT_F_OPT_DCE)) {
dce_marksnap(J);
dce_propagate(J);
memset(J->bpropcache, 0, sizeof(J->bpropcache)); /* Invalidate cache. */
}
}
#undef IR
#endif
| xLua/build/luajit-2.1.0b3/src/lj_opt_dce.c/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_opt_dce.c",
"repo_id": "xLua",
"token_count": 858
} | 2,125 |
/*
** Object de/serialization.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_SERIALIZE_H
#define _LJ_SERIALIZE_H
#include "lj_obj.h"
#include "lj_buf.h"
#if LJ_HASBUFFER
#define LJ_SERIALIZE_DEPTH 100 /* Default depth. */
LJ_FUNC void LJ_FASTCALL lj_serialize_dict_prep_str(lua_State *L, GCtab *dict);
LJ_FUNC void LJ_FASTCALL lj_serialize_dict_prep_mt(lua_State *L, GCtab *dict);
LJ_FUNC SBufExt * LJ_FASTCALL lj_serialize_put(SBufExt *sbx, cTValue *o);
LJ_FUNC char * LJ_FASTCALL lj_serialize_get(SBufExt *sbx, TValue *o);
LJ_FUNC GCstr * LJ_FASTCALL lj_serialize_encode(lua_State *L, cTValue *o);
LJ_FUNC void lj_serialize_decode(lua_State *L, TValue *o, GCstr *str);
#if LJ_HASJIT
LJ_FUNC MSize LJ_FASTCALL lj_serialize_peektype(SBufExt *sbx);
#endif
#endif
#endif
| xLua/build/luajit-2.1.0b3/src/lj_serialize.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_serialize.h",
"repo_id": "xLua",
"token_count": 391
} | 2,126 |
/*
** Definitions for ARM64 CPUs.
** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
*/
#ifndef _LJ_TARGET_ARM64_H
#define _LJ_TARGET_ARM64_H
/* -- Registers IDs ------------------------------------------------------- */
#define GPRDEF(_) \
_(X0) _(X1) _(X2) _(X3) _(X4) _(X5) _(X6) _(X7) \
_(X8) _(X9) _(X10) _(X11) _(X12) _(X13) _(X14) _(X15) \
_(X16) _(X17) _(X18) _(X19) _(X20) _(X21) _(X22) _(X23) \
_(X24) _(X25) _(X26) _(X27) _(X28) _(FP) _(LR) _(SP)
#define FPRDEF(_) \
_(D0) _(D1) _(D2) _(D3) _(D4) _(D5) _(D6) _(D7) \
_(D8) _(D9) _(D10) _(D11) _(D12) _(D13) _(D14) _(D15) \
_(D16) _(D17) _(D18) _(D19) _(D20) _(D21) _(D22) _(D23) \
_(D24) _(D25) _(D26) _(D27) _(D28) _(D29) _(D30) _(D31)
#define VRIDDEF(_)
#define RIDENUM(name) RID_##name,
enum {
GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */
FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */
RID_MAX,
RID_TMP = RID_LR,
RID_ZERO = RID_SP,
/* Calling conventions. */
RID_RET = RID_X0,
RID_RETLO = RID_X0,
RID_RETHI = RID_X1,
RID_FPRET = RID_D0,
/* These definitions must match with the *.dasc file(s): */
RID_BASE = RID_X19, /* Interpreter BASE. */
RID_LPC = RID_X21, /* Interpreter PC. */
RID_GL = RID_X22, /* Interpreter GL. */
RID_LREG = RID_X23, /* Interpreter L. */
/* Register ranges [min, max) and number of registers. */
RID_MIN_GPR = RID_X0,
RID_MAX_GPR = RID_SP+1,
RID_MIN_FPR = RID_MAX_GPR,
RID_MAX_FPR = RID_D31+1,
RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR,
RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR
};
#define RID_NUM_KREF RID_NUM_GPR
#define RID_MIN_KREF RID_X0
/* -- Register sets ------------------------------------------------------- */
/* Make use of all registers, except for x18, fp, lr and sp. */
#define RSET_FIXED \
(RID2RSET(RID_X18)|RID2RSET(RID_FP)|RID2RSET(RID_LR)|RID2RSET(RID_SP)|\
RID2RSET(RID_GL))
#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED)
#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)
#define RSET_ALL (RSET_GPR|RSET_FPR)
#define RSET_INIT RSET_ALL
/* lr is an implicit scratch register. */
#define RSET_SCRATCH_GPR (RSET_RANGE(RID_X0, RID_X17+1))
#define RSET_SCRATCH_FPR \
(RSET_RANGE(RID_D0, RID_D7+1)|RSET_RANGE(RID_D16, RID_D31+1))
#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR)
#define REGARG_FIRSTGPR RID_X0
#define REGARG_LASTGPR RID_X7
#define REGARG_NUMGPR 8
#define REGARG_FIRSTFPR RID_D0
#define REGARG_LASTFPR RID_D7
#define REGARG_NUMFPR 8
/* -- Spill slots --------------------------------------------------------- */
/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs.
**
** SPS_FIXED: Available fixed spill slots in interpreter frame.
** This definition must match with the vm_arm64.dasc file.
** Pre-allocate some slots to avoid sp adjust in every root trace.
**
** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots.
*/
#define SPS_FIXED 4
#define SPS_FIRST 2
#define SPOFS_TMP 0
#define sps_scale(slot) (4 * (int32_t)(slot))
#define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3)
/* -- Exit state ---------------------------------------------------------- */
/* This definition must match with the *.dasc file(s). */
typedef struct {
lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */
intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */
int32_t spill[256]; /* Spill slots. */
} ExitState;
/* Highest exit + 1 indicates stack check. */
#define EXITSTATE_CHECKEXIT 1
/* Return the address of a per-trace exit stub. */
static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p, uint32_t exitno)
{
while (*p == (LJ_LE ? 0xd503201f : 0x1f2003d5)) p++; /* Skip A64I_NOP. */
return p + 3 + exitno;
}
/* Avoid dependence on lj_jit.h if only including lj_target.h. */
#define exitstub_trace_addr(T, exitno) \
exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode), (exitno))
/* -- Instructions -------------------------------------------------------- */
/* ARM64 instructions are always little-endian. Swap for ARM64BE. */
#if LJ_BE
#define A64I_LE(x) (lj_bswap(x))
#else
#define A64I_LE(x) (x)
#endif
/* Instruction fields. */
#define A64F_D(r) (r)
#define A64F_N(r) ((r) << 5)
#define A64F_A(r) ((r) << 10)
#define A64F_M(r) ((r) << 16)
#define A64F_IMMS(x) ((x) << 10)
#define A64F_IMMR(x) ((x) << 16)
#define A64F_U16(x) ((x) << 5)
#define A64F_U12(x) ((x) << 10)
#define A64F_S26(x) (((uint32_t)(x) & 0x03ffffffu))
#define A64F_S19(x) (((uint32_t)(x) & 0x7ffffu) << 5)
#define A64F_S14(x) (((uint32_t)(x) & 0x3fffu) << 5)
#define A64F_S9(x) ((x) << 12)
#define A64F_BIT(x) ((x) << 19)
#define A64F_SH(sh, x) (((sh) << 22) | ((x) << 10))
#define A64F_EX(ex) (A64I_EX | ((ex) << 13))
#define A64F_EXSH(ex,x) (A64I_EX | ((ex) << 13) | ((x) << 10))
#define A64F_FP8(x) ((x) << 13)
#define A64F_CC(cc) ((cc) << 12)
#define A64F_LSL16(x) (((x) / 16) << 21)
#define A64F_BSH(sh) ((sh) << 10)
/* Check for valid field range. */
#define A64F_S_OK(x, b) ((((x) + (1 << (b-1))) >> (b)) == 0)
typedef enum A64Ins {
A64I_S = 0x20000000,
A64I_X = 0x80000000,
A64I_EX = 0x00200000,
A64I_ON = 0x00200000,
A64I_K12 = 0x1a000000,
A64I_K13 = 0x18000000,
A64I_LS_U = 0x01000000,
A64I_LS_S = 0x00800000,
A64I_LS_R = 0x01200800,
A64I_LS_SH = 0x00001000,
A64I_LS_UXTWx = 0x00004000,
A64I_LS_SXTWx = 0x0000c000,
A64I_LS_SXTXx = 0x0000e000,
A64I_LS_LSLx = 0x00006000,
A64I_ADDw = 0x0b000000,
A64I_ADDx = 0x8b000000,
A64I_ADDSw = 0x2b000000,
A64I_ADDSx = 0xab000000,
A64I_NEGw = 0x4b0003e0,
A64I_NEGx = 0xcb0003e0,
A64I_SUBw = 0x4b000000,
A64I_SUBx = 0xcb000000,
A64I_SUBSw = 0x6b000000,
A64I_SUBSx = 0xeb000000,
A64I_MULw = 0x1b007c00,
A64I_MULx = 0x9b007c00,
A64I_SMULL = 0x9b207c00,
A64I_ANDw = 0x0a000000,
A64I_ANDx = 0x8a000000,
A64I_ANDSw = 0x6a000000,
A64I_ANDSx = 0xea000000,
A64I_EORw = 0x4a000000,
A64I_EORx = 0xca000000,
A64I_ORRw = 0x2a000000,
A64I_ORRx = 0xaa000000,
A64I_TSTw = 0x6a00001f,
A64I_TSTx = 0xea00001f,
A64I_CMPw = 0x6b00001f,
A64I_CMPx = 0xeb00001f,
A64I_CMNw = 0x2b00001f,
A64I_CMNx = 0xab00001f,
A64I_CCMPw = 0x7a400000,
A64I_CCMPx = 0xfa400000,
A64I_CSELw = 0x1a800000,
A64I_CSELx = 0x9a800000,
A64I_ASRw = 0x13007c00,
A64I_ASRx = 0x9340fc00,
A64I_LSLx = 0xd3400000,
A64I_LSRx = 0xd340fc00,
A64I_SHRw = 0x1ac02000,
A64I_SHRx = 0x9ac02000, /* lsl/lsr/asr/ror x0, x0, x0 */
A64I_REVw = 0x5ac00800,
A64I_REVx = 0xdac00c00,
A64I_EXTRw = 0x13800000,
A64I_EXTRx = 0x93c00000,
A64I_BFMw = 0x33000000,
A64I_BFMx = 0xb3400000,
A64I_SBFMw = 0x13000000,
A64I_SBFMx = 0x93400000,
A64I_SXTBw = 0x13001c00,
A64I_SXTHw = 0x13003c00,
A64I_SXTW = 0x93407c00,
A64I_UBFMw = 0x53000000,
A64I_UBFMx = 0xd3400000,
A64I_UXTBw = 0x53001c00,
A64I_UXTHw = 0x53003c00,
A64I_MOVw = 0x2a0003e0,
A64I_MOVx = 0xaa0003e0,
A64I_MVNw = 0x2a2003e0,
A64I_MVNx = 0xaa2003e0,
A64I_MOVKw = 0x72800000,
A64I_MOVKx = 0xf2800000,
A64I_MOVZw = 0x52800000,
A64I_MOVZx = 0xd2800000,
A64I_MOVNw = 0x12800000,
A64I_MOVNx = 0x92800000,
A64I_LDRB = 0x39400000,
A64I_LDRH = 0x79400000,
A64I_LDRw = 0xb9400000,
A64I_LDRx = 0xf9400000,
A64I_LDRLw = 0x18000000,
A64I_LDRLx = 0x58000000,
A64I_STRB = 0x39000000,
A64I_STRH = 0x79000000,
A64I_STRw = 0xb9000000,
A64I_STRx = 0xf9000000,
A64I_STPw = 0x29000000,
A64I_STPx = 0xa9000000,
A64I_LDPw = 0x29400000,
A64I_LDPx = 0xa9400000,
A64I_B = 0x14000000,
A64I_BCC = 0x54000000,
A64I_BL = 0x94000000,
A64I_BR = 0xd61f0000,
A64I_BLR = 0xd63f0000,
A64I_TBZ = 0x36000000,
A64I_TBNZ = 0x37000000,
A64I_CBZ = 0x34000000,
A64I_CBNZ = 0x35000000,
A64I_NOP = 0xd503201f,
/* FP */
A64I_FADDd = 0x1e602800,
A64I_FSUBd = 0x1e603800,
A64I_FMADDd = 0x1f400000,
A64I_FMSUBd = 0x1f408000,
A64I_FNMADDd = 0x1f600000,
A64I_FNMSUBd = 0x1f608000,
A64I_FMULd = 0x1e600800,
A64I_FDIVd = 0x1e601800,
A64I_FNEGd = 0x1e614000,
A64I_FABS = 0x1e60c000,
A64I_FSQRTd = 0x1e61c000,
A64I_LDRs = 0xbd400000,
A64I_LDRd = 0xfd400000,
A64I_STRs = 0xbd000000,
A64I_STRd = 0xfd000000,
A64I_LDPs = 0x2d400000,
A64I_LDPd = 0x6d400000,
A64I_STPs = 0x2d000000,
A64I_STPd = 0x6d000000,
A64I_FCMPd = 0x1e602000,
A64I_FCMPZd = 0x1e602008,
A64I_FCSELd = 0x1e600c00,
A64I_FRINTMd = 0x1e654000,
A64I_FRINTPd = 0x1e64c000,
A64I_FRINTZd = 0x1e65c000,
A64I_FCVT_F32_F64 = 0x1e624000,
A64I_FCVT_F64_F32 = 0x1e22c000,
A64I_FCVT_F32_S32 = 0x1e220000,
A64I_FCVT_F64_S32 = 0x1e620000,
A64I_FCVT_F32_U32 = 0x1e230000,
A64I_FCVT_F64_U32 = 0x1e630000,
A64I_FCVT_F32_S64 = 0x9e220000,
A64I_FCVT_F64_S64 = 0x9e620000,
A64I_FCVT_F32_U64 = 0x9e230000,
A64I_FCVT_F64_U64 = 0x9e630000,
A64I_FCVT_S32_F64 = 0x1e780000,
A64I_FCVT_S32_F32 = 0x1e380000,
A64I_FCVT_U32_F64 = 0x1e790000,
A64I_FCVT_U32_F32 = 0x1e390000,
A64I_FCVT_S64_F64 = 0x9e780000,
A64I_FCVT_S64_F32 = 0x9e380000,
A64I_FCVT_U64_F64 = 0x9e790000,
A64I_FCVT_U64_F32 = 0x9e390000,
A64I_FMOV_S = 0x1e204000,
A64I_FMOV_D = 0x1e604000,
A64I_FMOV_R_S = 0x1e260000,
A64I_FMOV_S_R = 0x1e270000,
A64I_FMOV_R_D = 0x9e660000,
A64I_FMOV_D_R = 0x9e670000,
A64I_FMOV_DI = 0x1e601000,
} A64Ins;
typedef enum A64Shift {
A64SH_LSL, A64SH_LSR, A64SH_ASR, A64SH_ROR
} A64Shift;
typedef enum A64Extend {
A64EX_UXTB, A64EX_UXTH, A64EX_UXTW, A64EX_UXTX,
A64EX_SXTB, A64EX_SXTH, A64EX_SXTW, A64EX_SXTX,
} A64Extend;
/* ARM condition codes. */
typedef enum A64CC {
CC_EQ, CC_NE, CC_CS, CC_CC, CC_MI, CC_PL, CC_VS, CC_VC,
CC_HI, CC_LS, CC_GE, CC_LT, CC_GT, CC_LE, CC_AL,
CC_HS = CC_CS, CC_LO = CC_CC
} A64CC;
#endif
| xLua/build/luajit-2.1.0b3/src/lj_target_arm64.h/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lj_target_arm64.h",
"repo_id": "xLua",
"token_count": 5250
} | 2,127 |
// C++ wrapper for LuaJIT header files.
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "luajit.h"
}
| xLua/build/luajit-2.1.0b3/src/lua.hpp/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/lua.hpp",
"repo_id": "xLua",
"token_count": 59
} | 2,128 |
|// Low-level VM code for x86 CPUs.
|// Bytecode interpreter, fast functions and helper functions.
|// Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
|
|.if P64
|.arch x64
|.else
|.arch x86
|.endif
|.section code_op, code_sub
|
|.actionlist build_actionlist
|.globals GLOB_
|.globalnames globnames
|.externnames extnames
|
|//-----------------------------------------------------------------------
|
|.if P64
|.define X64, 1
|.if WIN
|.define X64WIN, 1
|.endif
|.endif
|
|// Fixed register assignments for the interpreter.
|// This is very fragile and has many dependencies. Caveat emptor.
|.define BASE, edx // Not C callee-save, refetched anyway.
|.if not X64
|.define KBASE, edi // Must be C callee-save.
|.define KBASEa, KBASE
|.define PC, esi // Must be C callee-save.
|.define PCa, PC
|.define DISPATCH, ebx // Must be C callee-save.
|.elif X64WIN
|.define KBASE, edi // Must be C callee-save.
|.define KBASEa, rdi
|.define PC, esi // Must be C callee-save.
|.define PCa, rsi
|.define DISPATCH, ebx // Must be C callee-save.
|.else
|.define KBASE, r15d // Must be C callee-save.
|.define KBASEa, r15
|.define PC, ebx // Must be C callee-save.
|.define PCa, rbx
|.define DISPATCH, r14d // Must be C callee-save.
|.endif
|
|.define RA, ecx
|.define RAH, ch
|.define RAL, cl
|.define RB, ebp // Must be ebp (C callee-save).
|.define RC, eax // Must be eax.
|.define RCW, ax
|.define RCH, ah
|.define RCL, al
|.define OP, RB
|.define RD, RC
|.define RDW, RCW
|.define RDL, RCL
|.if X64
|.define RAa, rcx
|.define RBa, rbp
|.define RCa, rax
|.define RDa, rax
|.else
|.define RAa, RA
|.define RBa, RB
|.define RCa, RC
|.define RDa, RD
|.endif
|
|.if not X64
|.define FCARG1, ecx // x86 fastcall arguments.
|.define FCARG2, edx
|.elif X64WIN
|.define CARG1, rcx // x64/WIN64 C call arguments.
|.define CARG2, rdx
|.define CARG3, r8
|.define CARG4, r9
|.define CARG1d, ecx
|.define CARG2d, edx
|.define CARG3d, r8d
|.define CARG4d, r9d
|.define FCARG1, CARG1d // Upwards compatible to x86 fastcall.
|.define FCARG2, CARG2d
|.else
|.define CARG1, rdi // x64/POSIX C call arguments.
|.define CARG2, rsi
|.define CARG3, rdx
|.define CARG4, rcx
|.define CARG5, r8
|.define CARG6, r9
|.define CARG1d, edi
|.define CARG2d, esi
|.define CARG3d, edx
|.define CARG4d, ecx
|.define CARG5d, r8d
|.define CARG6d, r9d
|.define FCARG1, CARG1d // Simulate x86 fastcall.
|.define FCARG2, CARG2d
|.endif
|
|// Type definitions. Some of these are only used for documentation.
|.type L, lua_State
|.type GL, global_State
|.type TVALUE, TValue
|.type GCOBJ, GCobj
|.type STR, GCstr
|.type TAB, GCtab
|.type LFUNC, GCfuncL
|.type CFUNC, GCfuncC
|.type PROTO, GCproto
|.type UPVAL, GCupval
|.type NODE, Node
|.type NARGS, int
|.type TRACE, GCtrace
|.type SBUF, SBuf
|
|// Stack layout while in interpreter. Must match with lj_frame.h.
|//-----------------------------------------------------------------------
|.if not X64 // x86 stack layout.
|
|.if WIN
|
|.define CFRAME_SPACE, aword*9 // Delta for esp (see <--).
|.macro saveregs_
| push edi; push esi; push ebx
| push extern lj_err_unwind_win
| fs; push dword [0]
| fs; mov [0], esp
| sub esp, CFRAME_SPACE
|.endmacro
|.macro restoreregs
| add esp, CFRAME_SPACE
| fs; pop dword [0]
| pop edi // Short for esp += 4.
| pop ebx; pop esi; pop edi; pop ebp
|.endmacro
|
|.else
|
|.define CFRAME_SPACE, aword*7 // Delta for esp (see <--).
|.macro saveregs_
| push edi; push esi; push ebx
| sub esp, CFRAME_SPACE
|.endmacro
|.macro restoreregs
| add esp, CFRAME_SPACE
| pop ebx; pop esi; pop edi; pop ebp
|.endmacro
|
|.endif
|
|.macro saveregs
| push ebp; saveregs_
|.endmacro
|
|.if WIN
|.define SAVE_ERRF, aword [esp+aword*19] // vm_pcall/vm_cpcall only.
|.define SAVE_NRES, aword [esp+aword*18]
|.define SAVE_CFRAME, aword [esp+aword*17]
|.define SAVE_L, aword [esp+aword*16]
|//----- 16 byte aligned, ^^^ arguments from C caller
|.define SAVE_RET, aword [esp+aword*15] //<-- esp entering interpreter.
|.define SAVE_R4, aword [esp+aword*14]
|.define SAVE_R3, aword [esp+aword*13]
|.define SAVE_R2, aword [esp+aword*12]
|//----- 16 byte aligned
|.define SAVE_R1, aword [esp+aword*11]
|.define SEH_FUNC, aword [esp+aword*10]
|.define SEH_NEXT, aword [esp+aword*9] //<-- esp after register saves.
|.define UNUSED2, aword [esp+aword*8]
|//----- 16 byte aligned
|.define UNUSED1, aword [esp+aword*7]
|.define SAVE_PC, aword [esp+aword*6]
|.define TMP2, aword [esp+aword*5]
|.define TMP1, aword [esp+aword*4]
|//----- 16 byte aligned
|.define ARG4, aword [esp+aword*3]
|.define ARG3, aword [esp+aword*2]
|.define ARG2, aword [esp+aword*1]
|.define ARG1, aword [esp] //<-- esp while in interpreter.
|//----- 16 byte aligned, ^^^ arguments for C callee
|.else
|.define SAVE_ERRF, aword [esp+aword*15] // vm_pcall/vm_cpcall only.
|.define SAVE_NRES, aword [esp+aword*14]
|.define SAVE_CFRAME, aword [esp+aword*13]
|.define SAVE_L, aword [esp+aword*12]
|//----- 16 byte aligned, ^^^ arguments from C caller
|.define SAVE_RET, aword [esp+aword*11] //<-- esp entering interpreter.
|.define SAVE_R4, aword [esp+aword*10]
|.define SAVE_R3, aword [esp+aword*9]
|.define SAVE_R2, aword [esp+aword*8]
|//----- 16 byte aligned
|.define SAVE_R1, aword [esp+aword*7] //<-- esp after register saves.
|.define SAVE_PC, aword [esp+aword*6]
|.define TMP2, aword [esp+aword*5]
|.define TMP1, aword [esp+aword*4]
|//----- 16 byte aligned
|.define ARG4, aword [esp+aword*3]
|.define ARG3, aword [esp+aword*2]
|.define ARG2, aword [esp+aword*1]
|.define ARG1, aword [esp] //<-- esp while in interpreter.
|//----- 16 byte aligned, ^^^ arguments for C callee
|.endif
|
|// FPARGx overlaps ARGx and ARG(x+1) on x86.
|.define FPARG3, qword [esp+qword*1]
|.define FPARG1, qword [esp]
|// TMPQ overlaps TMP1/TMP2. ARG5/MULTRES overlap TMP1/TMP2 (and TMPQ).
|.define TMPQ, qword [esp+aword*4]
|.define TMP3, ARG4
|.define ARG5, TMP1
|.define TMPa, TMP1
|.define MULTRES, TMP2
|
|// Arguments for vm_call and vm_pcall.
|.define INARG_BASE, SAVE_CFRAME // Overwritten by SAVE_CFRAME!
|
|// Arguments for vm_cpcall.
|.define INARG_CP_CALL, SAVE_ERRF
|.define INARG_CP_UD, SAVE_NRES
|.define INARG_CP_FUNC, SAVE_CFRAME
|
|//-----------------------------------------------------------------------
|.elif X64WIN // x64/Windows stack layout
|
|.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--).
|.macro saveregs_
| push rdi; push rsi; push rbx
| sub rsp, CFRAME_SPACE
|.endmacro
|.macro saveregs
| push rbp; saveregs_
|.endmacro
|.macro restoreregs
| add rsp, CFRAME_SPACE
| pop rbx; pop rsi; pop rdi; pop rbp
|.endmacro
|
|.define SAVE_CFRAME, aword [rsp+aword*13]
|.define SAVE_PC, dword [rsp+dword*25]
|.define SAVE_L, dword [rsp+dword*24]
|.define SAVE_ERRF, dword [rsp+dword*23]
|.define SAVE_NRES, dword [rsp+dword*22]
|.define TMP2, dword [rsp+dword*21]
|.define TMP1, dword [rsp+dword*20]
|//----- 16 byte aligned, ^^^ 32 byte register save area, owned by interpreter
|.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter.
|.define SAVE_R4, aword [rsp+aword*8]
|.define SAVE_R3, aword [rsp+aword*7]
|.define SAVE_R2, aword [rsp+aword*6]
|.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves.
|.define ARG5, aword [rsp+aword*4]
|.define CSAVE_4, aword [rsp+aword*3]
|.define CSAVE_3, aword [rsp+aword*2]
|.define CSAVE_2, aword [rsp+aword*1]
|.define CSAVE_1, aword [rsp] //<-- rsp while in interpreter.
|//----- 16 byte aligned, ^^^ 32 byte register save area, owned by callee
|
|// TMPQ overlaps TMP1/TMP2. MULTRES overlaps TMP2 (and TMPQ).
|.define TMPQ, qword [rsp+aword*10]
|.define MULTRES, TMP2
|.define TMPa, ARG5
|.define ARG5d, dword [rsp+aword*4]
|.define TMP3, ARG5d
|
|//-----------------------------------------------------------------------
|.else // x64/POSIX stack layout
|
|.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--).
|.macro saveregs_
| push rbx; push r15; push r14
|.if NO_UNWIND
| push r13; push r12
|.endif
| sub rsp, CFRAME_SPACE
|.endmacro
|.macro saveregs
| push rbp; saveregs_
|.endmacro
|.macro restoreregs
| add rsp, CFRAME_SPACE
|.if NO_UNWIND
| pop r12; pop r13
|.endif
| pop r14; pop r15; pop rbx; pop rbp
|.endmacro
|
|//----- 16 byte aligned,
|.if NO_UNWIND
|.define SAVE_RET, aword [rsp+aword*11] //<-- rsp entering interpreter.
|.define SAVE_R4, aword [rsp+aword*10]
|.define SAVE_R3, aword [rsp+aword*9]
|.define SAVE_R2, aword [rsp+aword*8]
|.define SAVE_R1, aword [rsp+aword*7]
|.define SAVE_RU2, aword [rsp+aword*6]
|.define SAVE_RU1, aword [rsp+aword*5] //<-- rsp after register saves.
|.else
|.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter.
|.define SAVE_R4, aword [rsp+aword*8]
|.define SAVE_R3, aword [rsp+aword*7]
|.define SAVE_R2, aword [rsp+aword*6]
|.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves.
|.endif
|.define SAVE_CFRAME, aword [rsp+aword*4]
|.define SAVE_PC, dword [rsp+dword*7]
|.define SAVE_L, dword [rsp+dword*6]
|.define SAVE_ERRF, dword [rsp+dword*5]
|.define SAVE_NRES, dword [rsp+dword*4]
|.define TMPa, aword [rsp+aword*1]
|.define TMP2, dword [rsp+dword*1]
|.define TMP1, dword [rsp] //<-- rsp while in interpreter.
|//----- 16 byte aligned
|
|// TMPQ overlaps TMP1/TMP2. MULTRES overlaps TMP2 (and TMPQ).
|.define TMPQ, qword [rsp]
|.define TMP3, dword [rsp+aword*1]
|.define MULTRES, TMP2
|
|.endif
|
|//-----------------------------------------------------------------------
|
|// Instruction headers.
|.macro ins_A; .endmacro
|.macro ins_AD; .endmacro
|.macro ins_AJ; .endmacro
|.macro ins_ABC; movzx RB, RCH; movzx RC, RCL; .endmacro
|.macro ins_AB_; movzx RB, RCH; .endmacro
|.macro ins_A_C; movzx RC, RCL; .endmacro
|.macro ins_AND; not RDa; .endmacro
|
|// Instruction decode+dispatch. Carefully tuned (nope, lodsd is not faster).
|.macro ins_NEXT
| mov RC, [PC]
| movzx RA, RCH
| movzx OP, RCL
| add PC, 4
| shr RC, 16
|.if X64
| jmp aword [DISPATCH+OP*8]
|.else
| jmp aword [DISPATCH+OP*4]
|.endif
|.endmacro
|
|// Instruction footer.
|.if 1
| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
| .define ins_next, ins_NEXT
| .define ins_next_, ins_NEXT
|.else
| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
| // Affects only certain kinds of benchmarks (and only with -j off).
| // Around 10%-30% slower on Core2, a lot more slower on P4.
| .macro ins_next
| jmp ->ins_next
| .endmacro
| .macro ins_next_
| ->ins_next:
| ins_NEXT
| .endmacro
|.endif
|
|// Call decode and dispatch.
|.macro ins_callt
| // BASE = new base, RB = LFUNC, RD = nargs+1, [BASE-4] = PC
| mov PC, LFUNC:RB->pc
| mov RA, [PC]
| movzx OP, RAL
| movzx RA, RAH
| add PC, 4
|.if X64
| jmp aword [DISPATCH+OP*8]
|.else
| jmp aword [DISPATCH+OP*4]
|.endif
|.endmacro
|
|.macro ins_call
| // BASE = new base, RB = LFUNC, RD = nargs+1
| mov [BASE-4], PC
| ins_callt
|.endmacro
|
|//-----------------------------------------------------------------------
|
|// Macros to test operand types.
|.macro checktp, reg, tp; cmp dword [BASE+reg*8+4], tp; .endmacro
|.macro checknum, reg, target; checktp reg, LJ_TISNUM; jae target; .endmacro
|.macro checkint, reg, target; checktp reg, LJ_TISNUM; jne target; .endmacro
|.macro checkstr, reg, target; checktp reg, LJ_TSTR; jne target; .endmacro
|.macro checktab, reg, target; checktp reg, LJ_TTAB; jne target; .endmacro
|
|// These operands must be used with movzx.
|.define PC_OP, byte [PC-4]
|.define PC_RA, byte [PC-3]
|.define PC_RB, byte [PC-1]
|.define PC_RC, byte [PC-2]
|.define PC_RD, word [PC-2]
|
|.macro branchPC, reg
| lea PC, [PC+reg*4-BCBIAS_J*4]
|.endmacro
|
|// Assumes DISPATCH is relative to GL.
#define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field))
#define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field))
|
#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
|
|// Decrement hashed hotcount and trigger trace recorder if zero.
|.macro hotloop, reg
| mov reg, PC
| shr reg, 1
| and reg, HOTCOUNT_PCMASK
| sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_LOOP
| jb ->vm_hotloop
|.endmacro
|
|.macro hotcall, reg
| mov reg, PC
| shr reg, 1
| and reg, HOTCOUNT_PCMASK
| sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_CALL
| jb ->vm_hotcall
|.endmacro
|
|// Set current VM state.
|.macro set_vmstate, st
| mov dword [DISPATCH+DISPATCH_GL(vmstate)], ~LJ_VMST_..st
|.endmacro
|
|// x87 compares.
|.macro fcomparepp // Compare and pop st0 >< st1.
| fucomip st1
| fpop
|.endmacro
|
|.macro fpop1; fstp st1; .endmacro
|
|// Synthesize SSE FP constants.
|.macro sseconst_abs, reg, tmp // Synthesize abs mask.
|.if X64
| mov64 tmp, U64x(7fffffff,ffffffff); movd reg, tmp
|.else
| pxor reg, reg; pcmpeqd reg, reg; psrlq reg, 1
|.endif
|.endmacro
|
|.macro sseconst_hi, reg, tmp, val // Synthesize hi-32 bit const.
|.if X64
| mov64 tmp, U64x(val,00000000); movd reg, tmp
|.else
| mov tmp, 0x .. val; movd reg, tmp; pshufd reg, reg, 0x51
|.endif
|.endmacro
|
|.macro sseconst_sign, reg, tmp // Synthesize sign mask.
| sseconst_hi reg, tmp, 80000000
|.endmacro
|.macro sseconst_1, reg, tmp // Synthesize 1.0.
| sseconst_hi reg, tmp, 3ff00000
|.endmacro
|.macro sseconst_m1, reg, tmp // Synthesize -1.0.
| sseconst_hi reg, tmp, bff00000
|.endmacro
|.macro sseconst_2p52, reg, tmp // Synthesize 2^52.
| sseconst_hi reg, tmp, 43300000
|.endmacro
|.macro sseconst_tobit, reg, tmp // Synthesize 2^52 + 2^51.
| sseconst_hi reg, tmp, 43380000
|.endmacro
|
|// Move table write barrier back. Overwrites reg.
|.macro barrierback, tab, reg
| and byte tab->marked, (uint8_t)~LJ_GC_BLACK // black2gray(tab)
| mov reg, [DISPATCH+DISPATCH_GL(gc.grayagain)]
| mov [DISPATCH+DISPATCH_GL(gc.grayagain)], tab
| mov tab->gclist, reg
|.endmacro
|
|//-----------------------------------------------------------------------
/* Generate subroutines used by opcodes and other parts of the VM. */
/* The .code_sub section should be last to help static branch prediction. */
static void build_subroutines(BuildCtx *ctx)
{
|.code_sub
|
|//-----------------------------------------------------------------------
|//-- Return handling ----------------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_returnp:
| test PC, FRAME_P
| jz ->cont_dispatch
|
| // Return from pcall or xpcall fast func.
| and PC, -8
| sub BASE, PC // Restore caller base.
| lea RAa, [RA+PC-8] // Rebase RA and prepend one result.
| mov PC, [BASE-4] // Fetch PC of previous frame.
| // Prepending may overwrite the pcall frame, so do it at the end.
| mov dword [BASE+RA+4], LJ_TTRUE // Prepend true to results.
|
|->vm_returnc:
| add RD, 1 // RD = nresults+1
| jz ->vm_unwind_yield
| mov MULTRES, RD
| test PC, FRAME_TYPE
| jz ->BC_RET_Z // Handle regular return to Lua.
|
|->vm_return:
| // BASE = base, RA = resultofs, RD = nresults+1 (= MULTRES), PC = return
| xor PC, FRAME_C
| test PC, FRAME_TYPE
| jnz ->vm_returnp
|
| // Return to C.
| set_vmstate C
| and PC, -8
| sub PC, BASE
| neg PC // Previous base = BASE - delta.
|
| sub RD, 1
| jz >2
|1: // Move results down.
|.if X64
| mov RBa, [BASE+RA]
| mov [BASE-8], RBa
|.else
| mov RB, [BASE+RA]
| mov [BASE-8], RB
| mov RB, [BASE+RA+4]
| mov [BASE-4], RB
|.endif
| add BASE, 8
| sub RD, 1
| jnz <1
|2:
| mov L:RB, SAVE_L
| mov L:RB->base, PC
|3:
| mov RD, MULTRES
| mov RA, SAVE_NRES // RA = wanted nresults+1
|4:
| cmp RA, RD
| jne >6 // More/less results wanted?
|5:
| sub BASE, 8
| mov L:RB->top, BASE
|
|->vm_leave_cp:
| mov RAa, SAVE_CFRAME // Restore previous C frame.
| mov L:RB->cframe, RAa
| xor eax, eax // Ok return status for vm_pcall.
|
|->vm_leave_unw:
| restoreregs
| ret
|
|6:
| jb >7 // Less results wanted?
| // More results wanted. Check stack size and fill up results with nil.
| cmp BASE, L:RB->maxstack
| ja >8
| mov dword [BASE-4], LJ_TNIL
| add BASE, 8
| add RD, 1
| jmp <4
|
|7: // Less results wanted.
| test RA, RA
| jz <5 // But check for LUA_MULTRET+1.
| sub RA, RD // Negative result!
| lea BASE, [BASE+RA*8] // Correct top.
| jmp <5
|
|8: // Corner case: need to grow stack for filling up results.
| // This can happen if:
| // - A C function grows the stack (a lot).
| // - The GC shrinks the stack in between.
| // - A return back from a lua_call() with (high) nresults adjustment.
| mov L:RB->top, BASE // Save current top held in BASE (yes).
| mov MULTRES, RD // Need to fill only remainder with nil.
| mov FCARG2, RA
| mov FCARG1, L:RB
| call extern lj_state_growstack@8 // (lua_State *L, int n)
| mov BASE, L:RB->top // Need the (realloced) L->top in BASE.
| jmp <3
|
|->vm_unwind_yield:
| mov al, LUA_YIELD
| jmp ->vm_unwind_c_eh
|
|->vm_unwind_c@8: // Unwind C stack, return from vm_pcall.
| // (void *cframe, int errcode)
|.if X64
| mov eax, CARG2d // Error return status for vm_pcall.
| mov rsp, CARG1
|.else
| mov eax, FCARG2 // Error return status for vm_pcall.
| mov esp, FCARG1
|.if WIN
| lea FCARG1, SEH_NEXT
| fs; mov [0], FCARG1
|.endif
|.endif
|->vm_unwind_c_eh: // Landing pad for external unwinder.
| mov L:RB, SAVE_L
| mov GL:RB, L:RB->glref
| mov dword GL:RB->vmstate, ~LJ_VMST_C
| jmp ->vm_leave_unw
|
|->vm_unwind_rethrow:
|.if X64 and not X64WIN
| mov FCARG1, SAVE_L
| mov FCARG2, eax
| restoreregs
| jmp extern lj_err_throw@8 // (lua_State *L, int errcode)
|.endif
|
|->vm_unwind_ff@4: // Unwind C stack, return from ff pcall.
| // (void *cframe)
|.if X64
| and CARG1, CFRAME_RAWMASK
| mov rsp, CARG1
|.else
| and FCARG1, CFRAME_RAWMASK
| mov esp, FCARG1
|.if WIN
| lea FCARG1, SEH_NEXT
| fs; mov [0], FCARG1
|.endif
|.endif
|->vm_unwind_ff_eh: // Landing pad for external unwinder.
| mov L:RB, SAVE_L
| mov RAa, -8 // Results start at BASE+RA = BASE-8.
| mov RD, 1+1 // Really 1+2 results, incr. later.
| mov BASE, L:RB->base
| mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
| add DISPATCH, GG_G2DISP
| mov PC, [BASE-4] // Fetch PC of previous frame.
| mov dword [BASE-4], LJ_TFALSE // Prepend false to error message.
| set_vmstate INTERP
| jmp ->vm_returnc // Increments RD/MULTRES and returns.
|
|.if WIN and not X64
|->vm_rtlunwind@16: // Thin layer around RtlUnwind.
| // (void *cframe, void *excptrec, void *unwinder, int errcode)
| mov [esp], FCARG1 // Return value for RtlUnwind.
| push FCARG2 // Exception record for RtlUnwind.
| push 0 // Ignored by RtlUnwind.
| push dword [FCARG1+CFRAME_OFS_SEH]
| call extern RtlUnwind@16 // Violates ABI (clobbers too much).
| mov FCARG1, eax
| mov FCARG2, [esp+4] // errcode (for vm_unwind_c).
| ret // Jump to unwinder.
|.endif
|
|//-----------------------------------------------------------------------
|//-- Grow stack for calls -----------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_growstack_c: // Grow stack for C function.
| mov FCARG2, LUA_MINSTACK
| jmp >2
|
|->vm_growstack_v: // Grow stack for vararg Lua function.
| sub RD, 8
| jmp >1
|
|->vm_growstack_f: // Grow stack for fixarg Lua function.
| // BASE = new base, RD = nargs+1, RB = L, PC = first PC
| lea RD, [BASE+NARGS:RD*8-8]
|1:
| movzx RA, byte [PC-4+PC2PROTO(framesize)]
| add PC, 4 // Must point after first instruction.
| mov L:RB->base, BASE
| mov L:RB->top, RD
| mov SAVE_PC, PC
| mov FCARG2, RA
|2:
| // RB = L, L->base = new base, L->top = top
| mov FCARG1, L:RB
| call extern lj_state_growstack@8 // (lua_State *L, int n)
| mov BASE, L:RB->base
| mov RD, L:RB->top
| mov LFUNC:RB, [BASE-8]
| sub RD, BASE
| shr RD, 3
| add NARGS:RD, 1
| // BASE = new base, RB = LFUNC, RD = nargs+1
| ins_callt // Just retry the call.
|
|//-----------------------------------------------------------------------
|//-- Entry points into the assembler VM ---------------------------------
|//-----------------------------------------------------------------------
|
|->vm_resume: // Setup C frame and resume thread.
| // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
| saveregs
|.if X64
| mov L:RB, CARG1d // Caveat: CARG1d may be RA.
| mov SAVE_L, CARG1d
| mov RA, CARG2d
|.else
| mov L:RB, SAVE_L
| mov RA, INARG_BASE // Caveat: overlaps SAVE_CFRAME!
|.endif
| mov PC, FRAME_CP
| xor RD, RD
| lea KBASEa, [esp+CFRAME_RESUME]
| mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
| add DISPATCH, GG_G2DISP
| mov SAVE_PC, RD // Any value outside of bytecode is ok.
| mov SAVE_CFRAME, RDa
|.if X64
| mov SAVE_NRES, RD
| mov SAVE_ERRF, RD
|.endif
| mov L:RB->cframe, KBASEa
| cmp byte L:RB->status, RDL
| je >2 // Initial resume (like a call).
|
| // Resume after yield (like a return).
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
| set_vmstate INTERP
| mov byte L:RB->status, RDL
| mov BASE, L:RB->base
| mov RD, L:RB->top
| sub RD, RA
| shr RD, 3
| add RD, 1 // RD = nresults+1
| sub RA, BASE // RA = resultofs
| mov PC, [BASE-4]
| mov MULTRES, RD
| test PC, FRAME_TYPE
| jz ->BC_RET_Z
| jmp ->vm_return
|
|->vm_pcall: // Setup protected C frame and enter VM.
| // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
| saveregs
| mov PC, FRAME_CP
|.if X64
| mov SAVE_ERRF, CARG4d
|.endif
| jmp >1
|
|->vm_call: // Setup C frame and enter VM.
| // (lua_State *L, TValue *base, int nres1)
| saveregs
| mov PC, FRAME_C
|
|1: // Entry point for vm_pcall above (PC = ftype).
|.if X64
| mov SAVE_NRES, CARG3d
| mov L:RB, CARG1d // Caveat: CARG1d may be RA.
| mov SAVE_L, CARG1d
| mov RA, CARG2d
|.else
| mov L:RB, SAVE_L
| mov RA, INARG_BASE // Caveat: overlaps SAVE_CFRAME!
|.endif
|
| mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
| mov KBASEa, L:RB->cframe // Add our C frame to cframe chain.
| mov SAVE_CFRAME, KBASEa
| mov SAVE_PC, L:RB // Any value outside of bytecode is ok.
| add DISPATCH, GG_G2DISP
|.if X64
| mov L:RB->cframe, rsp
|.else
| mov L:RB->cframe, esp
|.endif
|
|2: // Entry point for vm_resume/vm_cpcall (RA = base, RB = L, PC = ftype).
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
| set_vmstate INTERP
| mov BASE, L:RB->base // BASE = old base (used in vmeta_call).
| add PC, RA
| sub PC, BASE // PC = frame delta + frame type
|
| mov RD, L:RB->top
| sub RD, RA
| shr NARGS:RD, 3
| add NARGS:RD, 1 // RD = nargs+1
|
|->vm_call_dispatch:
| mov LFUNC:RB, [RA-8]
| cmp dword [RA-4], LJ_TFUNC
| jne ->vmeta_call // Ensure KBASE defined and != BASE.
|
|->vm_call_dispatch_f:
| mov BASE, RA
| ins_call
| // BASE = new base, RB = func, RD = nargs+1, PC = caller PC
|
|->vm_cpcall: // Setup protected C frame, call C.
| // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
| saveregs
|.if X64
| mov L:RB, CARG1d // Caveat: CARG1d may be RA.
| mov SAVE_L, CARG1d
|.else
| mov L:RB, SAVE_L
| // Caveat: INARG_CP_* and SAVE_CFRAME/SAVE_NRES/SAVE_ERRF overlap!
| mov RC, INARG_CP_UD // Get args before they are overwritten.
| mov RA, INARG_CP_FUNC
| mov BASE, INARG_CP_CALL
|.endif
| mov SAVE_PC, L:RB // Any value outside of bytecode is ok.
|
| mov KBASE, L:RB->stack // Compute -savestack(L, L->top).
| sub KBASE, L:RB->top
| mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
| mov SAVE_ERRF, 0 // No error function.
| mov SAVE_NRES, KBASE // Neg. delta means cframe w/o frame.
| add DISPATCH, GG_G2DISP
| // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe).
|
|.if X64
| mov KBASEa, L:RB->cframe // Add our C frame to cframe chain.
| mov SAVE_CFRAME, KBASEa
| mov L:RB->cframe, rsp
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
|
| call CARG4 // (lua_State *L, lua_CFunction func, void *ud)
|.else
| mov ARG3, RC // Have to copy args downwards.
| mov ARG2, RA
| mov ARG1, L:RB
|
| mov KBASE, L:RB->cframe // Add our C frame to cframe chain.
| mov SAVE_CFRAME, KBASE
| mov L:RB->cframe, esp
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
|
| call BASE // (lua_State *L, lua_CFunction func, void *ud)
|.endif
| // TValue * (new base) or NULL returned in eax (RC).
| test RC, RC
| jz ->vm_leave_cp // No base? Just remove C frame.
| mov RA, RC
| mov PC, FRAME_CP
| jmp <2 // Else continue with the call.
|
|//-----------------------------------------------------------------------
|//-- Metamethod handling ------------------------------------------------
|//-----------------------------------------------------------------------
|
|//-- Continuation dispatch ----------------------------------------------
|
|->cont_dispatch:
| // BASE = meta base, RA = resultofs, RD = nresults+1 (also in MULTRES)
| add RA, BASE
| and PC, -8
| mov RB, BASE
| sub BASE, PC // Restore caller BASE.
| mov dword [RA+RD*8-4], LJ_TNIL // Ensure one valid arg.
| mov RC, RA // ... in [RC]
| mov PC, [RB-12] // Restore PC from [cont|PC].
|.if X64
| movsxd RAa, dword [RB-16] // May be negative on WIN64 with debug.
|.if FFI
| cmp RA, 1
| jbe >1
|.endif
| lea KBASEa, qword [=>0]
| add RAa, KBASEa
|.else
| mov RA, dword [RB-16]
|.if FFI
| cmp RA, 1
| jbe >1
|.endif
|.endif
| mov LFUNC:KBASE, [BASE-8]
| mov KBASE, LFUNC:KBASE->pc
| mov KBASE, [KBASE+PC2PROTO(k)]
| // BASE = base, RC = result, RB = meta base
| jmp RAa // Jump to continuation.
|
|.if FFI
|1:
| je ->cont_ffi_callback // cont = 1: return from FFI callback.
| // cont = 0: Tail call from C function.
| sub RB, BASE
| shr RB, 3
| lea RD, [RB-1]
| jmp ->vm_call_tail
|.endif
|
|->cont_cat: // BASE = base, RC = result, RB = mbase
| movzx RA, PC_RB
| sub RB, 16
| lea RA, [BASE+RA*8]
| sub RA, RB
| je ->cont_ra
| neg RA
| shr RA, 3
|.if X64WIN
| mov CARG3d, RA
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE
| mov RCa, [RC]
| mov [RB], RCa
| mov CARG2d, RB
|.elif X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE
| mov CARG3d, RA
| mov RAa, [RC]
| mov [RB], RAa
| mov CARG2d, RB
|.else
| mov ARG3, RA
| mov RA, [RC+4]
| mov RC, [RC]
| mov [RB+4], RA
| mov [RB], RC
| mov ARG2, RB
|.endif
| jmp ->BC_CAT_Z
|
|//-- Table indexing metamethods -----------------------------------------
|
|->vmeta_tgets:
| mov TMP1, RC // RC = GCstr *
| mov TMP2, LJ_TSTR
| lea RCa, TMP1 // Store temp. TValue in TMP1/TMP2.
| cmp PC_OP, BC_GGET
| jne >1
| lea RA, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv.
| mov [RA], TAB:RB // RB = GCtab *
| mov dword [RA+4], LJ_TTAB
| mov RB, RA
| jmp >2
|
|->vmeta_tgetb:
| movzx RC, PC_RC
|.if DUALNUM
| mov TMP2, LJ_TISNUM
| mov TMP1, RC
|.else
| cvtsi2sd xmm0, RC
| movsd TMPQ, xmm0
|.endif
| lea RCa, TMPQ // Store temp. TValue in TMPQ.
| jmp >1
|
|->vmeta_tgetv:
| movzx RC, PC_RC // Reload TValue *k from RC.
| lea RC, [BASE+RC*8]
|1:
| movzx RB, PC_RB // Reload TValue *t from RB.
| lea RB, [BASE+RB*8]
|2:
|.if X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG2d, RB
| mov CARG3, RCa // May be 64 bit ptr to stack.
| mov L:RB, L:CARG1d
|.else
| mov ARG2, RB
| mov L:RB, SAVE_L
| mov ARG3, RC
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
| // TValue * (finished) or NULL (metamethod) returned in eax (RC).
| mov BASE, L:RB->base
| test RC, RC
| jz >3
|->cont_ra: // BASE = base, RC = result
| movzx RA, PC_RA
|.if X64
| mov RBa, [RC]
| mov [BASE+RA*8], RBa
|.else
| mov RB, [RC+4]
| mov RC, [RC]
| mov [BASE+RA*8+4], RB
| mov [BASE+RA*8], RC
|.endif
| ins_next
|
|3: // Call __index metamethod.
| // BASE = base, L->top = new base, stack = cont/func/t/k
| mov RA, L:RB->top
| mov [RA-12], PC // [cont|PC]
| lea PC, [RA+FRAME_CONT]
| sub PC, BASE
| mov LFUNC:RB, [RA-8] // Guaranteed to be a function here.
| mov NARGS:RD, 2+1 // 2 args for func(t, k).
| jmp ->vm_call_dispatch_f
|
|->vmeta_tgetr:
| mov FCARG1, TAB:RB
| mov RB, BASE // Save BASE.
| mov FCARG2, RC // Caveat: FCARG2 == BASE
| call extern lj_tab_getinth@8 // (GCtab *t, int32_t key)
| // cTValue * or NULL returned in eax (RC).
| movzx RA, PC_RA
| mov BASE, RB // Restore BASE.
| test RC, RC
| jnz ->BC_TGETR_Z
| mov dword [BASE+RA*8+4], LJ_TNIL
| jmp ->BC_TGETR2_Z
|
|//-----------------------------------------------------------------------
|
|->vmeta_tsets:
| mov TMP1, RC // RC = GCstr *
| mov TMP2, LJ_TSTR
| lea RCa, TMP1 // Store temp. TValue in TMP1/TMP2.
| cmp PC_OP, BC_GSET
| jne >1
| lea RA, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv.
| mov [RA], TAB:RB // RB = GCtab *
| mov dword [RA+4], LJ_TTAB
| mov RB, RA
| jmp >2
|
|->vmeta_tsetb:
| movzx RC, PC_RC
|.if DUALNUM
| mov TMP2, LJ_TISNUM
| mov TMP1, RC
|.else
| cvtsi2sd xmm0, RC
| movsd TMPQ, xmm0
|.endif
| lea RCa, TMPQ // Store temp. TValue in TMPQ.
| jmp >1
|
|->vmeta_tsetv:
| movzx RC, PC_RC // Reload TValue *k from RC.
| lea RC, [BASE+RC*8]
|1:
| movzx RB, PC_RB // Reload TValue *t from RB.
| lea RB, [BASE+RB*8]
|2:
|.if X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG2d, RB
| mov CARG3, RCa // May be 64 bit ptr to stack.
| mov L:RB, L:CARG1d
|.else
| mov ARG2, RB
| mov L:RB, SAVE_L
| mov ARG3, RC
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
| // TValue * (finished) or NULL (metamethod) returned in eax (RC).
| mov BASE, L:RB->base
| test RC, RC
| jz >3
| // NOBARRIER: lj_meta_tset ensures the table is not black.
| movzx RA, PC_RA
|.if X64
| mov RBa, [BASE+RA*8]
| mov [RC], RBa
|.else
| mov RB, [BASE+RA*8+4]
| mov RA, [BASE+RA*8]
| mov [RC+4], RB
| mov [RC], RA
|.endif
|->cont_nop: // BASE = base, (RC = result)
| ins_next
|
|3: // Call __newindex metamethod.
| // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
| mov RA, L:RB->top
| mov [RA-12], PC // [cont|PC]
| movzx RC, PC_RA
| // Copy value to third argument.
|.if X64
| mov RBa, [BASE+RC*8]
| mov [RA+16], RBa
|.else
| mov RB, [BASE+RC*8+4]
| mov RC, [BASE+RC*8]
| mov [RA+20], RB
| mov [RA+16], RC
|.endif
| lea PC, [RA+FRAME_CONT]
| sub PC, BASE
| mov LFUNC:RB, [RA-8] // Guaranteed to be a function here.
| mov NARGS:RD, 3+1 // 3 args for func(t, k, v).
| jmp ->vm_call_dispatch_f
|
|->vmeta_tsetr:
|.if X64WIN
| mov L:CARG1d, SAVE_L
| mov CARG3d, RC
| mov L:CARG1d->base, BASE
| xchg CARG2d, TAB:RB // Caveat: CARG2d == BASE.
|.elif X64
| mov L:CARG1d, SAVE_L
| mov CARG2d, TAB:RB
| mov L:CARG1d->base, BASE
| mov RB, BASE // Save BASE.
| mov CARG3d, RC // Caveat: CARG3d == BASE.
|.else
| mov L:RA, SAVE_L
| mov ARG2, TAB:RB
| mov RB, BASE // Save BASE.
| mov ARG3, RC
| mov ARG1, L:RA
| mov L:RA->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
| // TValue * returned in eax (RC).
| movzx RA, PC_RA
| mov BASE, RB // Restore BASE.
| jmp ->BC_TSETR_Z
|
|//-- Comparison metamethods ---------------------------------------------
|
|->vmeta_comp:
|.if X64
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d/CARG3d == BASE.
|.if X64WIN
| lea CARG3d, [BASE+RD*8]
| lea CARG2d, [BASE+RA*8]
|.else
| lea CARG2d, [BASE+RA*8]
| lea CARG3d, [BASE+RD*8]
|.endif
| mov CARG1d, L:RB // Caveat: CARG1d/CARG4d == RA.
| movzx CARG4d, PC_OP
|.else
| movzx RB, PC_OP
| lea RD, [BASE+RD*8]
| lea RA, [BASE+RA*8]
| mov ARG4, RB
| mov L:RB, SAVE_L
| mov ARG3, RD
| mov ARG2, RA
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
| // 0/1 or TValue * (metamethod) returned in eax (RC).
|3:
| mov BASE, L:RB->base
| cmp RC, 1
| ja ->vmeta_binop
|4:
| lea PC, [PC+4]
| jb >6
|5:
| movzx RD, PC_RD
| branchPC RD
|6:
| ins_next
|
|->cont_condt: // BASE = base, RC = result
| add PC, 4
| cmp dword [RC+4], LJ_TISTRUECOND // Branch if result is true.
| jb <5
| jmp <6
|
|->cont_condf: // BASE = base, RC = result
| cmp dword [RC+4], LJ_TISTRUECOND // Branch if result is false.
| jmp <4
|
|->vmeta_equal:
| sub PC, 4
|.if X64WIN
| mov CARG3d, RD
| mov CARG4d, RB
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d == BASE.
| mov CARG2d, RA
| mov CARG1d, L:RB // Caveat: CARG1d == RA.
|.elif X64
| mov CARG2d, RA
| mov CARG4d, RB // Caveat: CARG4d == RA.
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG3d == BASE.
| mov CARG3d, RD
| mov CARG1d, L:RB
|.else
| mov ARG4, RB
| mov L:RB, SAVE_L
| mov ARG3, RD
| mov ARG2, RA
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
| // 0/1 or TValue * (metamethod) returned in eax (RC).
| jmp <3
|
|->vmeta_equal_cd:
|.if FFI
| sub PC, 4
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov FCARG1, L:RB
| mov FCARG2, dword [PC-4]
| mov SAVE_PC, PC
| call extern lj_meta_equal_cd@8 // (lua_State *L, BCIns ins)
| // 0/1 or TValue * (metamethod) returned in eax (RC).
| jmp <3
|.endif
|
|->vmeta_istype:
|.if X64
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG2d, RA
| movzx CARG3d, PC_RD
| mov L:CARG1d, L:RB
|.else
| movzx RD, PC_RD
| mov ARG2, RA
| mov L:RB, SAVE_L
| mov ARG3, RD
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
| mov BASE, L:RB->base
| jmp <6
|
|//-- Arithmetic metamethods ---------------------------------------------
|
|->vmeta_arith_vno:
|.if DUALNUM
| movzx RB, PC_RB
|.endif
|->vmeta_arith_vn:
| lea RC, [KBASE+RC*8]
| jmp >1
|
|->vmeta_arith_nvo:
|.if DUALNUM
| movzx RC, PC_RC
|.endif
|->vmeta_arith_nv:
| lea RC, [KBASE+RC*8]
| lea RB, [BASE+RB*8]
| xchg RB, RC
| jmp >2
|
|->vmeta_unm:
| lea RC, [BASE+RD*8]
| mov RB, RC
| jmp >2
|
|->vmeta_arith_vvo:
|.if DUALNUM
| movzx RB, PC_RB
|.endif
|->vmeta_arith_vv:
| lea RC, [BASE+RC*8]
|1:
| lea RB, [BASE+RB*8]
|2:
| lea RA, [BASE+RA*8]
|.if X64WIN
| mov CARG3d, RB
| mov CARG4d, RC
| movzx RC, PC_OP
| mov ARG5d, RC
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d == BASE.
| mov CARG2d, RA
| mov CARG1d, L:RB // Caveat: CARG1d == RA.
|.elif X64
| movzx CARG5d, PC_OP
| mov CARG2d, RA
| mov CARG4d, RC // Caveat: CARG4d == RA.
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE // Caveat: CARG3d == BASE.
| mov CARG3d, RB
| mov L:RB, L:CARG1d
|.else
| mov ARG3, RB
| mov L:RB, SAVE_L
| mov ARG4, RC
| movzx RC, PC_OP
| mov ARG2, RA
| mov ARG5, RC
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
| // NULL (finished) or TValue * (metamethod) returned in eax (RC).
| mov BASE, L:RB->base
| test RC, RC
| jz ->cont_nop
|
| // Call metamethod for binary op.
|->vmeta_binop:
| // BASE = base, RC = new base, stack = cont/func/o1/o2
| mov RA, RC
| sub RC, BASE
| mov [RA-12], PC // [cont|PC]
| lea PC, [RC+FRAME_CONT]
| mov NARGS:RD, 2+1 // 2 args for func(o1, o2).
| jmp ->vm_call_dispatch
|
|->vmeta_len:
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| lea FCARG2, [BASE+RD*8] // Caveat: FCARG2 == BASE
| mov L:FCARG1, L:RB
| mov SAVE_PC, PC
| call extern lj_meta_len@8 // (lua_State *L, TValue *o)
| // NULL (retry) or TValue * (metamethod) returned in eax (RC).
| mov BASE, L:RB->base
#if LJ_52
| test RC, RC
| jne ->vmeta_binop // Binop call for compatibility.
| movzx RD, PC_RD
| mov TAB:FCARG1, [BASE+RD*8]
| jmp ->BC_LEN_Z
#else
| jmp ->vmeta_binop // Binop call for compatibility.
#endif
|
|//-- Call metamethod ----------------------------------------------------
|
|->vmeta_call_ra:
| lea RA, [BASE+RA*8+8]
|->vmeta_call: // Resolve and call __call metamethod.
| // BASE = old base, RA = new base, RC = nargs+1, PC = return
| mov TMP2, RA // Save RA, RC for us.
| mov TMP1, NARGS:RD
| sub RA, 8
|.if X64
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG2d, RA
| lea CARG3d, [RA+NARGS:RD*8]
| mov CARG1d, L:RB // Caveat: CARG1d may be RA.
|.else
| lea RC, [RA+NARGS:RD*8]
| mov L:RB, SAVE_L
| mov ARG2, RA
| mov ARG3, RC
| mov ARG1, L:RB
| mov L:RB->base, BASE // This is the callers base!
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
| mov BASE, L:RB->base
| mov RA, TMP2
| mov NARGS:RD, TMP1
| mov LFUNC:RB, [RA-8]
| add NARGS:RD, 1
| // This is fragile. L->base must not move, KBASE must always be defined.
|.if x64
| cmp KBASEa, rdx // Continue with CALLT if flag set.
|.else
| cmp KBASE, BASE // Continue with CALLT if flag set.
|.endif
| je ->BC_CALLT_Z
| mov BASE, RA
| ins_call // Otherwise call resolved metamethod.
|
|//-- Argument coercion for 'for' statement ------------------------------
|
|->vmeta_for:
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov FCARG2, RA // Caveat: FCARG2 == BASE
| mov L:FCARG1, L:RB // Caveat: FCARG1 == RA
| mov SAVE_PC, PC
| call extern lj_meta_for@8 // (lua_State *L, TValue *base)
| mov BASE, L:RB->base
| mov RC, [PC-4]
| movzx RA, RCH
| movzx OP, RCL
| shr RC, 16
|.if X64
| jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Retry FORI or JFORI.
|.else
| jmp aword [DISPATCH+OP*4+GG_DISP2STATIC] // Retry FORI or JFORI.
|.endif
|
|//-----------------------------------------------------------------------
|//-- Fast functions -----------------------------------------------------
|//-----------------------------------------------------------------------
|
|.macro .ffunc, name
|->ff_ .. name:
|.endmacro
|
|.macro .ffunc_1, name
|->ff_ .. name:
| cmp NARGS:RD, 1+1; jb ->fff_fallback
|.endmacro
|
|.macro .ffunc_2, name
|->ff_ .. name:
| cmp NARGS:RD, 2+1; jb ->fff_fallback
|.endmacro
|
|.macro .ffunc_nsse, name, op
| .ffunc_1 name
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
| op xmm0, qword [BASE]
|.endmacro
|
|.macro .ffunc_nsse, name
| .ffunc_nsse name, movsd
|.endmacro
|
|.macro .ffunc_nnsse, name
| .ffunc_2 name
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
| cmp dword [BASE+12], LJ_TISNUM; jae ->fff_fallback
| movsd xmm0, qword [BASE]
| movsd xmm1, qword [BASE+8]
|.endmacro
|
|.macro .ffunc_nnr, name
| .ffunc_2 name
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
| cmp dword [BASE+12], LJ_TISNUM; jae ->fff_fallback
| fld qword [BASE+8]
| fld qword [BASE]
|.endmacro
|
|// Inlined GC threshold check. Caveat: uses label 1.
|.macro ffgccheck
| mov RB, [DISPATCH+DISPATCH_GL(gc.total)]
| cmp RB, [DISPATCH+DISPATCH_GL(gc.threshold)]
| jb >1
| call ->fff_gcstep
|1:
|.endmacro
|
|//-- Base library: checks -----------------------------------------------
|
|.ffunc_1 assert
| mov RB, [BASE+4]
| cmp RB, LJ_TISTRUECOND; jae ->fff_fallback
| mov PC, [BASE-4]
| mov MULTRES, RD
| mov [BASE-4], RB
| mov RB, [BASE]
| mov [BASE-8], RB
| sub RD, 2
| jz >2
| mov RA, BASE
|1:
| add RA, 8
|.if X64
| mov RBa, [RA]
| mov [RA-8], RBa
|.else
| mov RB, [RA+4]
| mov [RA-4], RB
| mov RB, [RA]
| mov [RA-8], RB
|.endif
| sub RD, 1
| jnz <1
|2:
| mov RD, MULTRES
| jmp ->fff_res_
|
|.ffunc_1 type
| mov RB, [BASE+4]
|.if X64
| mov RA, RB
| sar RA, 15
| cmp RA, -2
| je >3
|.endif
| mov RC, ~LJ_TNUMX
| not RB
| cmp RC, RB
| cmova RC, RB
|2:
| mov CFUNC:RB, [BASE-8]
| mov STR:RC, [CFUNC:RB+RC*8+((char *)(&((GCfuncC *)0)->upvalue))]
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TSTR
| mov [BASE-8], STR:RC
| jmp ->fff_res1
|.if X64
|3:
| mov RC, ~LJ_TLIGHTUD
| jmp <2
|.endif
|
|//-- Base library: getters and setters ---------------------------------
|
|.ffunc_1 getmetatable
| mov RB, [BASE+4]
| mov PC, [BASE-4]
| cmp RB, LJ_TTAB; jne >6
|1: // Field metatable must be at same offset for GCtab and GCudata!
| mov TAB:RB, [BASE]
| mov TAB:RB, TAB:RB->metatable
|2:
| test TAB:RB, TAB:RB
| mov dword [BASE-4], LJ_TNIL
| jz ->fff_res1
| mov STR:RC, [DISPATCH+DISPATCH_GL(gcroot)+4*(GCROOT_MMNAME+MM_metatable)]
| mov dword [BASE-4], LJ_TTAB // Store metatable as default result.
| mov [BASE-8], TAB:RB
| mov RA, TAB:RB->hmask
| and RA, STR:RC->sid
| imul RA, #NODE
| add NODE:RA, TAB:RB->node
|3: // Rearranged logic, because we expect _not_ to find the key.
| cmp dword NODE:RA->key.it, LJ_TSTR
| jne >4
| cmp dword NODE:RA->key.gcr, STR:RC
| je >5
|4:
| mov NODE:RA, NODE:RA->next
| test NODE:RA, NODE:RA
| jnz <3
| jmp ->fff_res1 // Not found, keep default result.
|5:
| mov RB, [RA+4]
| cmp RB, LJ_TNIL; je ->fff_res1 // Ditto for nil value.
| mov RC, [RA]
| mov [BASE-4], RB // Return value of mt.__metatable.
| mov [BASE-8], RC
| jmp ->fff_res1
|
|6:
| cmp RB, LJ_TUDATA; je <1
|.if X64
| cmp RB, LJ_TNUMX; ja >8
| cmp RB, LJ_TISNUM; jbe >7
| mov RB, LJ_TLIGHTUD
| jmp >8
|7:
|.else
| cmp RB, LJ_TISNUM; ja >8
|.endif
| mov RB, LJ_TNUMX
|8:
| not RB
| mov TAB:RB, [DISPATCH+RB*4+DISPATCH_GL(gcroot[GCROOT_BASEMT])]
| jmp <2
|
|.ffunc_2 setmetatable
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
| // Fast path: no mt for table yet and not clearing the mt.
| mov TAB:RB, [BASE]
| cmp dword TAB:RB->metatable, 0; jne ->fff_fallback
| cmp dword [BASE+12], LJ_TTAB; jne ->fff_fallback
| mov TAB:RC, [BASE+8]
| mov TAB:RB->metatable, TAB:RC
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TTAB // Return original table.
| mov [BASE-8], TAB:RB
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jz >1
| // Possible write barrier. Table is black, but skip iswhite(mt) check.
| barrierback TAB:RB, RC
|1:
| jmp ->fff_res1
|
|.ffunc_2 rawget
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
|.if X64WIN
| mov RB, BASE // Save BASE.
| lea CARG3d, [BASE+8]
| mov CARG2d, [BASE] // Caveat: CARG2d == BASE.
| mov CARG1d, SAVE_L
|.elif X64
| mov RB, BASE // Save BASE.
| mov CARG2d, [BASE]
| lea CARG3d, [BASE+8] // Caveat: CARG3d == BASE.
| mov CARG1d, SAVE_L
|.else
| mov TAB:RD, [BASE]
| mov L:RB, SAVE_L
| mov ARG2, TAB:RD
| mov ARG1, L:RB
| mov RB, BASE // Save BASE.
| add BASE, 8
| mov ARG3, BASE
|.endif
| call extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
| // cTValue * returned in eax (RD).
| mov BASE, RB // Restore BASE.
| // Copy table slot.
|.if X64
| mov RBa, [RD]
| mov PC, [BASE-4]
| mov [BASE-8], RBa
|.else
| mov RB, [RD]
| mov RD, [RD+4]
| mov PC, [BASE-4]
| mov [BASE-8], RB
| mov [BASE-4], RD
|.endif
| jmp ->fff_res1
|
|//-- Base library: conversions ------------------------------------------
|
|.ffunc tonumber
| // Only handles the number case inline (without a base argument).
| cmp NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument.
| cmp dword [BASE+4], LJ_TISNUM
|.if DUALNUM
| jne >1
| mov RB, dword [BASE]; jmp ->fff_resi
|1:
| ja ->fff_fallback
|.else
| jae ->fff_fallback
|.endif
| movsd xmm0, qword [BASE]; jmp ->fff_resxmm0
|
|.ffunc_1 tostring
| // Only handles the string or number case inline.
| mov PC, [BASE-4]
| cmp dword [BASE+4], LJ_TSTR; jne >3
| // A __tostring method in the string base metatable is ignored.
| mov STR:RD, [BASE]
|2:
| mov dword [BASE-4], LJ_TSTR
| mov [BASE-8], STR:RD
| jmp ->fff_res1
|3: // Handle numbers inline, unless a number base metatable is present.
| cmp dword [BASE+4], LJ_TISNUM; ja ->fff_fallback
| cmp dword [DISPATCH+DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])], 0
| jne ->fff_fallback
| ffgccheck // Caveat: uses label 1.
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Add frame since C call can throw.
| mov SAVE_PC, PC // Redundant (but a defined value).
|.if X64 and not X64WIN
| mov FCARG2, BASE // Otherwise: FCARG2 == BASE
|.endif
| mov L:FCARG1, L:RB
|.if DUALNUM
| call extern lj_strfmt_number@8 // (lua_State *L, cTValue *o)
|.else
| call extern lj_strfmt_num@8 // (lua_State *L, lua_Number *np)
|.endif
| // GCstr returned in eax (RD).
| mov BASE, L:RB->base
| jmp <2
|
|//-- Base library: iterators -------------------------------------------
|
|.ffunc_1 next
| je >2 // Missing 2nd arg?
|1:
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
| mov PC, [BASE-4]
| mov RB, BASE // Save BASE.
|.if X64WIN
| mov CARG1d, [BASE]
| lea CARG3d, [BASE-8]
| lea CARG2d, [BASE+8] // Caveat: CARG2d == BASE.
|.elif X64
| mov CARG1d, [BASE]
| lea CARG2d, [BASE+8]
| lea CARG3d, [BASE-8] // Caveat: CARG3d == BASE.
|.else
| mov TAB:RD, [BASE]
| mov ARG1, TAB:RD
| add BASE, 8
| mov ARG2, BASE
| sub BASE, 8+8
| mov ARG3, BASE
|.endif
| call extern lj_tab_next // (GCtab *t, cTValue *key, TValue *o)
| // 1=found, 0=end, -1=error returned in eax (RD).
| mov BASE, RB // Restore BASE.
| test RD, RD; jg ->fff_res2 // Found key/value.
| js ->fff_fallback_2 // Invalid key.
| // End of traversal: return nil.
| mov dword [BASE-4], LJ_TNIL
| jmp ->fff_res1
|2: // Set missing 2nd arg to nil.
| mov dword [BASE+12], LJ_TNIL
| jmp <1
|
|.ffunc_1 pairs
| mov TAB:RB, [BASE]
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
#if LJ_52
| cmp dword TAB:RB->metatable, 0; jne ->fff_fallback
#endif
| mov CFUNC:RB, [BASE-8]
| mov CFUNC:RD, CFUNC:RB->upvalue[0]
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TFUNC
| mov [BASE-8], CFUNC:RD
| mov dword [BASE+12], LJ_TNIL
| mov RD, 1+3
| jmp ->fff_res
|
|.ffunc_2 ipairs_aux
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
| cmp dword [BASE+12], LJ_TISNUM
|.if DUALNUM
| jne ->fff_fallback
|.else
| jae ->fff_fallback
|.endif
| mov PC, [BASE-4]
|.if DUALNUM
| mov RD, dword [BASE+8]
| add RD, 1
| mov dword [BASE-4], LJ_TISNUM
| mov dword [BASE-8], RD
|.else
| movsd xmm0, qword [BASE+8]
| sseconst_1 xmm1, RBa
| addsd xmm0, xmm1
| cvttsd2si RD, xmm0
| movsd qword [BASE-8], xmm0
|.endif
| mov TAB:RB, [BASE]
| cmp RD, TAB:RB->asize; jae >2 // Not in array part?
| shl RD, 3
| add RD, TAB:RB->array
|1:
| cmp dword [RD+4], LJ_TNIL; je ->fff_res0
| // Copy array slot.
|.if X64
| mov RBa, [RD]
| mov [BASE], RBa
|.else
| mov RB, [RD]
| mov RD, [RD+4]
| mov [BASE], RB
| mov [BASE+4], RD
|.endif
|->fff_res2:
| mov RD, 1+2
| jmp ->fff_res
|2: // Check for empty hash part first. Otherwise call C function.
| cmp dword TAB:RB->hmask, 0; je ->fff_res0
| mov FCARG1, TAB:RB
| mov RB, BASE // Save BASE.
| mov FCARG2, RD // Caveat: FCARG2 == BASE
| call extern lj_tab_getinth@8 // (GCtab *t, int32_t key)
| // cTValue * or NULL returned in eax (RD).
| mov BASE, RB
| test RD, RD
| jnz <1
|->fff_res0:
| mov RD, 1+0
| jmp ->fff_res
|
|.ffunc_1 ipairs
| mov TAB:RB, [BASE]
| cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
#if LJ_52
| cmp dword TAB:RB->metatable, 0; jne ->fff_fallback
#endif
| mov CFUNC:RB, [BASE-8]
| mov CFUNC:RD, CFUNC:RB->upvalue[0]
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TFUNC
| mov [BASE-8], CFUNC:RD
|.if DUALNUM
| mov dword [BASE+12], LJ_TISNUM
| mov dword [BASE+8], 0
|.else
| xorps xmm0, xmm0
| movsd qword [BASE+8], xmm0
|.endif
| mov RD, 1+3
| jmp ->fff_res
|
|//-- Base library: catch errors ----------------------------------------
|
|.ffunc_1 pcall
| lea RA, [BASE+8]
| sub NARGS:RD, 1
| mov PC, 8+FRAME_PCALL
|1:
| movzx RB, byte [DISPATCH+DISPATCH_GL(hookmask)]
| shr RB, HOOK_ACTIVE_SHIFT
| and RB, 1
| add PC, RB // Remember active hook before pcall.
| jmp ->vm_call_dispatch
|
|.ffunc_2 xpcall
| cmp dword [BASE+12], LJ_TFUNC; jne ->fff_fallback
| mov RB, [BASE+4] // Swap function and traceback.
| mov [BASE+12], RB
| mov dword [BASE+4], LJ_TFUNC
| mov LFUNC:RB, [BASE]
| mov PC, [BASE+8]
| mov [BASE+8], LFUNC:RB
| mov [BASE], PC
| lea RA, [BASE+16]
| sub NARGS:RD, 2
| mov PC, 16+FRAME_PCALL
| jmp <1
|
|//-- Coroutine library --------------------------------------------------
|
|.macro coroutine_resume_wrap, resume
|.if resume
|.ffunc_1 coroutine_resume
| mov L:RB, [BASE]
|.else
|.ffunc coroutine_wrap_aux
| mov CFUNC:RB, [BASE-8]
| mov L:RB, CFUNC:RB->upvalue[0].gcr
|.endif
| mov PC, [BASE-4]
| mov SAVE_PC, PC
|.if X64
| mov TMP1, L:RB
|.else
| mov ARG1, L:RB
|.endif
|.if resume
| cmp dword [BASE+4], LJ_TTHREAD; jne ->fff_fallback
|.endif
| cmp aword L:RB->cframe, 0; jne ->fff_fallback
| cmp byte L:RB->status, LUA_YIELD; ja ->fff_fallback
| mov RA, L:RB->top
| je >1 // Status != LUA_YIELD (i.e. 0)?
| cmp RA, L:RB->base // Check for presence of initial func.
| je ->fff_fallback
|1:
|.if resume
| lea PC, [RA+NARGS:RD*8-16] // Check stack space (-1-thread).
|.else
| lea PC, [RA+NARGS:RD*8-8] // Check stack space (-1).
|.endif
| cmp PC, L:RB->maxstack; ja ->fff_fallback
| mov L:RB->top, PC
|
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
|.if resume
| add BASE, 8 // Keep resumed thread in stack for GC.
|.endif
| mov L:RB->top, BASE
|.if resume
| lea RB, [BASE+NARGS:RD*8-24] // RB = end of source for stack move.
|.else
| lea RB, [BASE+NARGS:RD*8-16] // RB = end of source for stack move.
|.endif
| sub RBa, PCa // Relative to PC.
|
| cmp PC, RA
| je >3
|2: // Move args to coroutine.
|.if X64
| mov RCa, [PC+RB]
| mov [PC-8], RCa
|.else
| mov RC, [PC+RB+4]
| mov [PC-4], RC
| mov RC, [PC+RB]
| mov [PC-8], RC
|.endif
| sub PC, 8
| cmp PC, RA
| jne <2
|3:
|.if X64
| mov CARG2d, RA
| mov CARG1d, TMP1
|.else
| mov ARG2, RA
| xor RA, RA
| mov ARG4, RA
| mov ARG3, RA
|.endif
| call ->vm_resume // (lua_State *L, TValue *base, 0, 0)
|
| mov L:RB, SAVE_L
|.if X64
| mov L:PC, TMP1
|.else
| mov L:PC, ARG1 // The callee doesn't modify SAVE_L.
|.endif
| mov BASE, L:RB->base
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
| set_vmstate INTERP
|
| cmp eax, LUA_YIELD
| ja >8
|4:
| mov RA, L:PC->base
| mov KBASE, L:PC->top
| mov L:PC->top, RA // Clear coroutine stack.
| mov PC, KBASE
| sub PC, RA
| je >6 // No results?
| lea RD, [BASE+PC]
| shr PC, 3
| cmp RD, L:RB->maxstack
| ja >9 // Need to grow stack?
|
| mov RB, BASE
| sub RBa, RAa
|5: // Move results from coroutine.
|.if X64
| mov RDa, [RA]
| mov [RA+RB], RDa
|.else
| mov RD, [RA]
| mov [RA+RB], RD
| mov RD, [RA+4]
| mov [RA+RB+4], RD
|.endif
| add RA, 8
| cmp RA, KBASE
| jne <5
|6:
|.if resume
| lea RD, [PC+2] // nresults+1 = 1 + true + results.
| mov dword [BASE-4], LJ_TTRUE // Prepend true to results.
|.else
| lea RD, [PC+1] // nresults+1 = 1 + results.
|.endif
|7:
| mov PC, SAVE_PC
| mov MULTRES, RD
|.if resume
| mov RAa, -8
|.else
| xor RA, RA
|.endif
| test PC, FRAME_TYPE
| jz ->BC_RET_Z
| jmp ->vm_return
|
|8: // Coroutine returned with error (at co->top-1).
|.if resume
| mov dword [BASE-4], LJ_TFALSE // Prepend false to results.
| mov RA, L:PC->top
| sub RA, 8
| mov L:PC->top, RA // Clear error from coroutine stack.
| // Copy error message.
|.if X64
| mov RDa, [RA]
| mov [BASE], RDa
|.else
| mov RD, [RA]
| mov [BASE], RD
| mov RD, [RA+4]
| mov [BASE+4], RD
|.endif
| mov RD, 1+2 // nresults+1 = 1 + false + error.
| jmp <7
|.else
| mov FCARG2, L:PC
| mov FCARG1, L:RB
| call extern lj_ffh_coroutine_wrap_err@8 // (lua_State *L, lua_State *co)
| // Error function does not return.
|.endif
|
|9: // Handle stack expansion on return from yield.
|.if X64
| mov L:RA, TMP1
|.else
| mov L:RA, ARG1 // The callee doesn't modify SAVE_L.
|.endif
| mov L:RA->top, KBASE // Undo coroutine stack clearing.
| mov FCARG2, PC
| mov FCARG1, L:RB
| call extern lj_state_growstack@8 // (lua_State *L, int n)
|.if X64
| mov L:PC, TMP1
|.else
| mov L:PC, ARG1
|.endif
| mov BASE, L:RB->base
| jmp <4 // Retry the stack move.
|.endmacro
|
| coroutine_resume_wrap 1 // coroutine.resume
| coroutine_resume_wrap 0 // coroutine.wrap
|
|.ffunc coroutine_yield
| mov L:RB, SAVE_L
| test aword L:RB->cframe, CFRAME_RESUME
| jz ->fff_fallback
| mov L:RB->base, BASE
| lea RD, [BASE+NARGS:RD*8-8]
| mov L:RB->top, RD
| xor RD, RD
| mov aword L:RB->cframe, RDa
| mov al, LUA_YIELD
| mov byte L:RB->status, al
| jmp ->vm_leave_unw
|
|//-- Math library -------------------------------------------------------
|
|.if not DUALNUM
|->fff_resi: // Dummy.
|.endif
|
|->fff_resn:
| mov PC, [BASE-4]
| fstp qword [BASE-8]
| jmp ->fff_res1
|
| .ffunc_1 math_abs
|.if DUALNUM
| cmp dword [BASE+4], LJ_TISNUM; jne >2
| mov RB, dword [BASE]
| cmp RB, 0; jns ->fff_resi
| neg RB; js >1
|->fff_resbit:
|->fff_resi:
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TISNUM
| mov dword [BASE-8], RB
| jmp ->fff_res1
|1:
| mov PC, [BASE-4]
| mov dword [BASE-4], 0x41e00000 // 2^31.
| mov dword [BASE-8], 0
| jmp ->fff_res1
|2:
| ja ->fff_fallback
|.else
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
|.endif
| movsd xmm0, qword [BASE]
| sseconst_abs xmm1, RDa
| andps xmm0, xmm1
|->fff_resxmm0:
| mov PC, [BASE-4]
| movsd qword [BASE-8], xmm0
| // fallthrough
|
|->fff_res1:
| mov RD, 1+1
|->fff_res:
| mov MULTRES, RD
|->fff_res_:
| test PC, FRAME_TYPE
| jnz >7
|5:
| cmp PC_RB, RDL // More results expected?
| ja >6
| // Adjust BASE. KBASE is assumed to be set for the calling frame.
| movzx RA, PC_RA
| not RAa // Note: ~RA = -(RA+1)
| lea BASE, [BASE+RA*8] // base = base - (RA+1)*8
| ins_next
|
|6: // Fill up results with nil.
| mov dword [BASE+RD*8-12], LJ_TNIL
| add RD, 1
| jmp <5
|
|7: // Non-standard return case.
| mov RAa, -8 // Results start at BASE+RA = BASE-8.
| jmp ->vm_return
|
|.if X64
|.define fff_resfp, fff_resxmm0
|.else
|.define fff_resfp, fff_resn
|.endif
|
|.macro math_round, func
| .ffunc math_ .. func
|.if DUALNUM
| cmp dword [BASE+4], LJ_TISNUM; jne >1
| mov RB, dword [BASE]; jmp ->fff_resi
|1:
| ja ->fff_fallback
|.else
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
|.endif
| movsd xmm0, qword [BASE]
| call ->vm_ .. func .. _sse
|.if DUALNUM
| cvttsd2si RB, xmm0
| cmp RB, 0x80000000
| jne ->fff_resi
| cvtsi2sd xmm1, RB
| ucomisd xmm0, xmm1
| jp ->fff_resxmm0
| je ->fff_resi
|.endif
| jmp ->fff_resxmm0
|.endmacro
|
| math_round floor
| math_round ceil
|
|.ffunc_nsse math_sqrt, sqrtsd; jmp ->fff_resxmm0
|
|.ffunc math_log
| cmp NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument.
| cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
| movsd xmm0, qword [BASE]
|.if not X64
| movsd FPARG1, xmm0
|.endif
| mov RB, BASE
| call extern log
| mov BASE, RB
| jmp ->fff_resfp
|
|.macro math_extern, func
| .ffunc_nsse math_ .. func
|.if not X64
| movsd FPARG1, xmm0
|.endif
| mov RB, BASE
| call extern func
| mov BASE, RB
| jmp ->fff_resfp
|.endmacro
|
|.macro math_extern2, func
| .ffunc_nnsse math_ .. func
|.if not X64
| movsd FPARG1, xmm0
| movsd FPARG3, xmm1
|.endif
| mov RB, BASE
| call extern func
| mov BASE, RB
| jmp ->fff_resfp
|.endmacro
|
| math_extern log10
| math_extern exp
| math_extern sin
| math_extern cos
| math_extern tan
| math_extern asin
| math_extern acos
| math_extern atan
| math_extern sinh
| math_extern cosh
| math_extern tanh
| math_extern2 pow
| math_extern2 atan2
| math_extern2 fmod
|
|.ffunc_nnr math_ldexp; fscale; fpop1; jmp ->fff_resn
|
|.ffunc_1 math_frexp
| mov RB, [BASE+4]
| cmp RB, LJ_TISNUM; jae ->fff_fallback
| mov PC, [BASE-4]
| mov RC, [BASE]
| mov [BASE-4], RB; mov [BASE-8], RC
| shl RB, 1; cmp RB, 0xffe00000; jae >3
| or RC, RB; jz >3
| mov RC, 1022
| cmp RB, 0x00200000; jb >4
|1:
| shr RB, 21; sub RB, RC // Extract and unbias exponent.
| cvtsi2sd xmm0, RB
| mov RB, [BASE-4]
| and RB, 0x800fffff // Mask off exponent.
| or RB, 0x3fe00000 // Put mantissa in range [0.5,1) or 0.
| mov [BASE-4], RB
|2:
| movsd qword [BASE], xmm0
| mov RD, 1+2
| jmp ->fff_res
|3: // Return +-0, +-Inf, NaN unmodified and an exponent of 0.
| xorps xmm0, xmm0; jmp <2
|4: // Handle denormals by multiplying with 2^54 and adjusting the bias.
| movsd xmm0, qword [BASE]
| sseconst_hi xmm1, RBa, 43500000 // 2^54.
| mulsd xmm0, xmm1
| movsd qword [BASE-8], xmm0
| mov RB, [BASE-4]; mov RC, 1076; shl RB, 1; jmp <1
|
|.ffunc_nsse math_modf
| mov RB, [BASE+4]
| mov PC, [BASE-4]
| shl RB, 1; cmp RB, 0xffe00000; je >4 // +-Inf?
| movaps xmm4, xmm0
| call ->vm_trunc_sse
| subsd xmm4, xmm0
|1:
| movsd qword [BASE-8], xmm0
| movsd qword [BASE], xmm4
| mov RC, [BASE-4]; mov RB, [BASE+4]
| xor RC, RB; js >3 // Need to adjust sign?
|2:
| mov RD, 1+2
| jmp ->fff_res
|3:
| xor RB, 0x80000000; mov [BASE+4], RB // Flip sign of fraction.
| jmp <2
|4:
| xorps xmm4, xmm4; jmp <1 // Return +-Inf and +-0.
|
|.macro math_minmax, name, cmovop, sseop
| .ffunc_1 name
| mov RA, 2
| cmp dword [BASE+4], LJ_TISNUM
|.if DUALNUM
| jne >4
| mov RB, dword [BASE]
|1: // Handle integers.
| cmp RA, RD; jae ->fff_resi
| cmp dword [BASE+RA*8-4], LJ_TISNUM; jne >3
| cmp RB, dword [BASE+RA*8-8]
| cmovop RB, dword [BASE+RA*8-8]
| add RA, 1
| jmp <1
|3:
| ja ->fff_fallback
| // Convert intermediate result to number and continue below.
| cvtsi2sd xmm0, RB
| jmp >6
|4:
| ja ->fff_fallback
|.else
| jae ->fff_fallback
|.endif
|
| movsd xmm0, qword [BASE]
|5: // Handle numbers or integers.
| cmp RA, RD; jae ->fff_resxmm0
| cmp dword [BASE+RA*8-4], LJ_TISNUM
|.if DUALNUM
| jb >6
| ja ->fff_fallback
| cvtsi2sd xmm1, dword [BASE+RA*8-8]
| jmp >7
|.else
| jae ->fff_fallback
|.endif
|6:
| movsd xmm1, qword [BASE+RA*8-8]
|7:
| sseop xmm0, xmm1
| add RA, 1
| jmp <5
|.endmacro
|
| math_minmax math_min, cmovg, minsd
| math_minmax math_max, cmovl, maxsd
|
|//-- String library -----------------------------------------------------
|
|.ffunc string_byte // Only handle the 1-arg case here.
| cmp NARGS:RD, 1+1; jne ->fff_fallback
| cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
| mov STR:RB, [BASE]
| mov PC, [BASE-4]
| cmp dword STR:RB->len, 1
| jb ->fff_res0 // Return no results for empty string.
| movzx RB, byte STR:RB[1]
|.if DUALNUM
| jmp ->fff_resi
|.else
| cvtsi2sd xmm0, RB; jmp ->fff_resxmm0
|.endif
|
|.ffunc string_char // Only handle the 1-arg case here.
| ffgccheck
| cmp NARGS:RD, 1+1; jne ->fff_fallback // *Exactly* 1 arg.
| cmp dword [BASE+4], LJ_TISNUM
|.if DUALNUM
| jne ->fff_fallback
| mov RB, dword [BASE]
| cmp RB, 255; ja ->fff_fallback
| mov TMP2, RB
|.else
| jae ->fff_fallback
| cvttsd2si RB, qword [BASE]
| cmp RB, 255; ja ->fff_fallback
| mov TMP2, RB
|.endif
|.if X64
| mov TMP3, 1
|.else
| mov ARG3, 1
|.endif
| lea RDa, TMP2 // Points to stack. Little-endian.
|->fff_newstr:
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
|.if X64
| mov CARG3d, TMP3 // Zero-extended to size_t.
| mov CARG2, RDa // May be 64 bit ptr to stack.
| mov CARG1d, L:RB
|.else
| mov ARG2, RD
| mov ARG1, L:RB
|.endif
| mov SAVE_PC, PC
| call extern lj_str_new // (lua_State *L, char *str, size_t l)
|->fff_resstr:
| // GCstr * returned in eax (RD).
| mov BASE, L:RB->base
| mov PC, [BASE-4]
| mov dword [BASE-4], LJ_TSTR
| mov [BASE-8], STR:RD
| jmp ->fff_res1
|
|.ffunc string_sub
| ffgccheck
| mov TMP2, -1
| cmp NARGS:RD, 1+2; jb ->fff_fallback
| jna >1
| cmp dword [BASE+20], LJ_TISNUM
|.if DUALNUM
| jne ->fff_fallback
| mov RB, dword [BASE+16]
| mov TMP2, RB
|.else
| jae ->fff_fallback
| cvttsd2si RB, qword [BASE+16]
| mov TMP2, RB
|.endif
|1:
| cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
| cmp dword [BASE+12], LJ_TISNUM
|.if DUALNUM
| jne ->fff_fallback
|.else
| jae ->fff_fallback
|.endif
| mov STR:RB, [BASE]
| mov TMP3, STR:RB
| mov RB, STR:RB->len
|.if DUALNUM
| mov RA, dword [BASE+8]
|.else
| cvttsd2si RA, qword [BASE+8]
|.endif
| mov RC, TMP2
| cmp RB, RC // len < end? (unsigned compare)
| jb >5
|2:
| test RA, RA // start <= 0?
| jle >7
|3:
| mov STR:RB, TMP3
| sub RC, RA // start > end?
| jl ->fff_emptystr
| lea RB, [STR:RB+RA+#STR-1]
| add RC, 1
|4:
|.if X64
| mov TMP3, RC
|.else
| mov ARG3, RC
|.endif
| mov RD, RB
| jmp ->fff_newstr
|
|5: // Negative end or overflow.
| jl >6
| lea RC, [RC+RB+1] // end = end+(len+1)
| jmp <2
|6: // Overflow.
| mov RC, RB // end = len
| jmp <2
|
|7: // Negative start or underflow.
| je >8
| add RA, RB // start = start+(len+1)
| add RA, 1
| jg <3 // start > 0?
|8: // Underflow.
| mov RA, 1 // start = 1
| jmp <3
|
|->fff_emptystr: // Range underflow.
| xor RC, RC // Zero length. Any ptr in RB is ok.
| jmp <4
|
|.macro ffstring_op, name
| .ffunc_1 string_ .. name
| ffgccheck
| cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
| mov L:RB, SAVE_L
| lea SBUF:FCARG1, [DISPATCH+DISPATCH_GL(tmpbuf)]
| mov L:RB->base, BASE
| mov STR:FCARG2, [BASE] // Caveat: FCARG2 == BASE
| mov RCa, SBUF:FCARG1->b
| mov SBUF:FCARG1->L, L:RB
| mov SBUF:FCARG1->w, RCa
| mov SAVE_PC, PC
| call extern lj_buf_putstr_ .. name .. @8
| mov FCARG1, eax
| call extern lj_buf_tostr@4
| jmp ->fff_resstr
|.endmacro
|
|ffstring_op reverse
|ffstring_op lower
|ffstring_op upper
|
|//-- Bit library --------------------------------------------------------
|
|.macro .ffunc_bit, name, kind, fdef
| fdef name
|.if kind == 2
| sseconst_tobit xmm1, RBa
|.endif
| cmp dword [BASE+4], LJ_TISNUM
|.if DUALNUM
| jne >1
| mov RB, dword [BASE]
|.if kind > 0
| jmp >2
|.else
| jmp ->fff_resbit
|.endif
|1:
| ja ->fff_fallback
|.else
| jae ->fff_fallback
|.endif
| movsd xmm0, qword [BASE]
|.if kind < 2
| sseconst_tobit xmm1, RBa
|.endif
| addsd xmm0, xmm1
| movd RB, xmm0
|2:
|.endmacro
|
|.macro .ffunc_bit, name, kind
| .ffunc_bit name, kind, .ffunc_1
|.endmacro
|
|.ffunc_bit bit_tobit, 0
| jmp ->fff_resbit
|
|.macro .ffunc_bit_op, name, ins
| .ffunc_bit name, 2
| mov TMP2, NARGS:RD // Save for fallback.
| lea RD, [BASE+NARGS:RD*8-16]
|1:
| cmp RD, BASE
| jbe ->fff_resbit
| cmp dword [RD+4], LJ_TISNUM
|.if DUALNUM
| jne >2
| ins RB, dword [RD]
| sub RD, 8
| jmp <1
|2:
| ja ->fff_fallback_bit_op
|.else
| jae ->fff_fallback_bit_op
|.endif
| movsd xmm0, qword [RD]
| addsd xmm0, xmm1
| movd RA, xmm0
| ins RB, RA
| sub RD, 8
| jmp <1
|.endmacro
|
|.ffunc_bit_op bit_band, and
|.ffunc_bit_op bit_bor, or
|.ffunc_bit_op bit_bxor, xor
|
|.ffunc_bit bit_bswap, 1
| bswap RB
| jmp ->fff_resbit
|
|.ffunc_bit bit_bnot, 1
| not RB
|.if DUALNUM
| jmp ->fff_resbit
|.else
|->fff_resbit:
| cvtsi2sd xmm0, RB
| jmp ->fff_resxmm0
|.endif
|
|->fff_fallback_bit_op:
| mov NARGS:RD, TMP2 // Restore for fallback
| jmp ->fff_fallback
|
|.macro .ffunc_bit_sh, name, ins
|.if DUALNUM
| .ffunc_bit name, 1, .ffunc_2
| // Note: no inline conversion from number for 2nd argument!
| cmp dword [BASE+12], LJ_TISNUM; jne ->fff_fallback
| mov RA, dword [BASE+8]
|.else
| .ffunc_nnsse name
| sseconst_tobit xmm2, RBa
| addsd xmm0, xmm2
| addsd xmm1, xmm2
| movd RB, xmm0
| movd RA, xmm1
|.endif
| ins RB, cl // Assumes RA is ecx.
| jmp ->fff_resbit
|.endmacro
|
|.ffunc_bit_sh bit_lshift, shl
|.ffunc_bit_sh bit_rshift, shr
|.ffunc_bit_sh bit_arshift, sar
|.ffunc_bit_sh bit_rol, rol
|.ffunc_bit_sh bit_ror, ror
|
|//-----------------------------------------------------------------------
|
|->fff_fallback_2:
| mov NARGS:RD, 1+2 // Other args are ignored, anyway.
| jmp ->fff_fallback
|->fff_fallback_1:
| mov NARGS:RD, 1+1 // Other args are ignored, anyway.
|->fff_fallback: // Call fast function fallback handler.
| // BASE = new base, RD = nargs+1
| mov L:RB, SAVE_L
| mov PC, [BASE-4] // Fallback may overwrite PC.
| mov SAVE_PC, PC // Redundant (but a defined value).
| mov L:RB->base, BASE
| lea RD, [BASE+NARGS:RD*8-8]
| lea RA, [RD+8*LUA_MINSTACK] // Ensure enough space for handler.
| mov L:RB->top, RD
| mov CFUNC:RD, [BASE-8]
| cmp RA, L:RB->maxstack
| ja >5 // Need to grow stack.
|.if X64
| mov CARG1d, L:RB
|.else
| mov ARG1, L:RB
|.endif
| call aword CFUNC:RD->f // (lua_State *L)
| mov BASE, L:RB->base
| // Either throws an error, or recovers and returns -1, 0 or nresults+1.
| test RD, RD; jg ->fff_res // Returned nresults+1?
|1:
| mov RA, L:RB->top
| sub RA, BASE
| shr RA, 3
| test RD, RD
| lea NARGS:RD, [RA+1]
| mov LFUNC:RB, [BASE-8]
| jne ->vm_call_tail // Returned -1?
| ins_callt // Returned 0: retry fast path.
|
|// Reconstruct previous base for vmeta_call during tailcall.
|->vm_call_tail:
| mov RA, BASE
| test PC, FRAME_TYPE
| jnz >3
| movzx RB, PC_RA
| not RBa // Note: ~RB = -(RB+1)
| lea BASE, [BASE+RB*8] // base = base - (RB+1)*8
| jmp ->vm_call_dispatch // Resolve again for tailcall.
|3:
| mov RB, PC
| and RB, -8
| sub BASE, RB
| jmp ->vm_call_dispatch // Resolve again for tailcall.
|
|5: // Grow stack for fallback handler.
| mov FCARG2, LUA_MINSTACK
| mov FCARG1, L:RB
| call extern lj_state_growstack@8 // (lua_State *L, int n)
| mov BASE, L:RB->base
| xor RD, RD // Simulate a return 0.
| jmp <1 // Dumb retry (goes through ff first).
|
|->fff_gcstep: // Call GC step function.
| // BASE = new base, RD = nargs+1
| pop RBa // Must keep stack at same level.
| mov TMPa, RBa // Save return address
| mov L:RB, SAVE_L
| mov SAVE_PC, PC // Redundant (but a defined value).
| mov L:RB->base, BASE
| lea RD, [BASE+NARGS:RD*8-8]
| mov FCARG1, L:RB
| mov L:RB->top, RD
| call extern lj_gc_step@4 // (lua_State *L)
| mov BASE, L:RB->base
| mov RD, L:RB->top
| sub RD, BASE
| shr RD, 3
| add NARGS:RD, 1
| mov RBa, TMPa
| push RBa // Restore return address.
| ret
|
|//-----------------------------------------------------------------------
|//-- Special dispatch targets -------------------------------------------
|//-----------------------------------------------------------------------
|
|->vm_record: // Dispatch target for recording phase.
|.if JIT
| movzx RD, byte [DISPATCH+DISPATCH_GL(hookmask)]
| test RDL, HOOK_VMEVENT // No recording while in vmevent.
| jnz >5
| // Decrement the hookcount for consistency, but always do the call.
| test RDL, HOOK_ACTIVE
| jnz >1
| test RDL, LUA_MASKLINE|LUA_MASKCOUNT
| jz >1
| dec dword [DISPATCH+DISPATCH_GL(hookcount)]
| jmp >1
|.endif
|
|->vm_rethook: // Dispatch target for return hooks.
| movzx RD, byte [DISPATCH+DISPATCH_GL(hookmask)]
| test RDL, HOOK_ACTIVE // Hook already active?
| jnz >5
| jmp >1
|
|->vm_inshook: // Dispatch target for instr/line hooks.
| movzx RD, byte [DISPATCH+DISPATCH_GL(hookmask)]
| test RDL, HOOK_ACTIVE // Hook already active?
| jnz >5
|
| test RDL, LUA_MASKLINE|LUA_MASKCOUNT
| jz >5
| dec dword [DISPATCH+DISPATCH_GL(hookcount)]
| jz >1
| test RDL, LUA_MASKLINE
| jz >5
|1:
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov FCARG2, PC // Caveat: FCARG2 == BASE
| mov FCARG1, L:RB
| // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
| call extern lj_dispatch_ins@8 // (lua_State *L, const BCIns *pc)
|3:
| mov BASE, L:RB->base
|4:
| movzx RA, PC_RA
|5:
| movzx OP, PC_OP
| movzx RD, PC_RD
|.if X64
| jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Re-dispatch to static ins.
|.else
| jmp aword [DISPATCH+OP*4+GG_DISP2STATIC] // Re-dispatch to static ins.
|.endif
|
|->cont_hook: // Continue from hook yield.
| add PC, 4
| mov RA, [RB-24]
| mov MULTRES, RA // Restore MULTRES for *M ins.
| jmp <4
|
|->vm_hotloop: // Hot loop counter underflow.
|.if JIT
| mov LFUNC:RB, [BASE-8] // Same as curr_topL(L).
| mov RB, LFUNC:RB->pc
| movzx RD, byte [RB+PC2PROTO(framesize)]
| lea RD, [BASE+RD*8]
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov L:RB->top, RD
| mov FCARG2, PC
| lea FCARG1, [DISPATCH+GG_DISP2J]
| mov aword [DISPATCH+DISPATCH_J(L)], L:RBa
| mov SAVE_PC, PC
| call extern lj_trace_hot@8 // (jit_State *J, const BCIns *pc)
| jmp <3
|.endif
|
|->vm_callhook: // Dispatch target for call hooks.
| mov SAVE_PC, PC
|.if JIT
| jmp >1
|.endif
|
|->vm_hotcall: // Hot call counter underflow.
|.if JIT
| mov SAVE_PC, PC
| or PC, 1 // Marker for hot call.
|1:
|.endif
| lea RD, [BASE+NARGS:RD*8-8]
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov L:RB->top, RD
| mov FCARG2, PC
| mov FCARG1, L:RB
| call extern lj_dispatch_call@8 // (lua_State *L, const BCIns *pc)
| // ASMFunction returned in eax/rax (RDa).
| mov SAVE_PC, 0 // Invalidate for subsequent line hook.
|.if JIT
| and PC, -2
|.endif
| mov BASE, L:RB->base
| mov RAa, RDa
| mov RD, L:RB->top
| sub RD, BASE
| mov RBa, RAa
| movzx RA, PC_RA
| shr RD, 3
| add NARGS:RD, 1
| jmp RBa
|
|->cont_stitch: // Trace stitching.
|.if JIT
| // BASE = base, RC = result, RB = mbase
| mov TRACE:RA, [RB-24] // Save previous trace.
| mov TMP1, TRACE:RA
| mov TMP3, DISPATCH // Need one more register.
| mov DISPATCH, MULTRES
| movzx RA, PC_RA
| lea RA, [BASE+RA*8] // Call base.
| sub DISPATCH, 1
| jz >2
|1: // Move results down.
|.if X64
| mov RBa, [RC]
| mov [RA], RBa
|.else
| mov RB, [RC]
| mov [RA], RB
| mov RB, [RC+4]
| mov [RA+4], RB
|.endif
| add RC, 8
| add RA, 8
| sub DISPATCH, 1
| jnz <1
|2:
| movzx RC, PC_RA
| movzx RB, PC_RB
| add RC, RB
| lea RC, [BASE+RC*8-8]
|3:
| cmp RC, RA
| ja >9 // More results wanted?
|
| mov DISPATCH, TMP3
| mov TRACE:RD, TMP1 // Get previous trace.
| movzx RB, word TRACE:RD->traceno
| movzx RD, word TRACE:RD->link
| cmp RD, RB
| je ->cont_nop // Blacklisted.
| test RD, RD
| jne =>BC_JLOOP // Jump to stitched trace.
|
| // Stitch a new trace to the previous trace.
| mov [DISPATCH+DISPATCH_J(exitno)], RB
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov FCARG2, PC
| lea FCARG1, [DISPATCH+GG_DISP2J]
| mov aword [DISPATCH+DISPATCH_J(L)], L:RBa
| call extern lj_dispatch_stitch@8 // (jit_State *J, const BCIns *pc)
| mov BASE, L:RB->base
| jmp ->cont_nop
|
|9: // Fill up results with nil.
| mov dword [RA+4], LJ_TNIL
| add RA, 8
| jmp <3
|.endif
|
|->vm_profhook: // Dispatch target for profiler hook.
#if LJ_HASPROFILE
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov FCARG2, PC // Caveat: FCARG2 == BASE
| mov FCARG1, L:RB
| call extern lj_dispatch_profile@8 // (lua_State *L, const BCIns *pc)
| mov BASE, L:RB->base
| // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
| sub PC, 4
| jmp ->cont_nop
#endif
|
|//-----------------------------------------------------------------------
|//-- Trace exit handler -------------------------------------------------
|//-----------------------------------------------------------------------
|
|// Called from an exit stub with the exit number on the stack.
|// The 16 bit exit number is stored with two (sign-extended) push imm8.
|->vm_exit_handler:
|.if JIT
|.if X64
| push r13; push r12
| push r11; push r10; push r9; push r8
| push rdi; push rsi; push rbp; lea rbp, [rsp+88]; push rbp
| push rbx; push rdx; push rcx; push rax
| movzx RC, byte [rbp-8] // Reconstruct exit number.
| mov RCH, byte [rbp-16]
| mov [rbp-8], r15; mov [rbp-16], r14
|.else
| push ebp; lea ebp, [esp+12]; push ebp
| push ebx; push edx; push ecx; push eax
| movzx RC, byte [ebp-4] // Reconstruct exit number.
| mov RCH, byte [ebp-8]
| mov [ebp-4], edi; mov [ebp-8], esi
|.endif
| // Caveat: DISPATCH is ebx.
| mov DISPATCH, [ebp]
| mov RA, [DISPATCH+DISPATCH_GL(vmstate)] // Get trace number.
| set_vmstate EXIT
| mov [DISPATCH+DISPATCH_J(exitno)], RC
| mov [DISPATCH+DISPATCH_J(parent)], RA
|.if X64
|.if X64WIN
| sub rsp, 16*8+4*8 // Room for SSE regs + save area.
|.else
| sub rsp, 16*8 // Room for SSE regs.
|.endif
| add rbp, -128
| movsd qword [rbp-8], xmm15; movsd qword [rbp-16], xmm14
| movsd qword [rbp-24], xmm13; movsd qword [rbp-32], xmm12
| movsd qword [rbp-40], xmm11; movsd qword [rbp-48], xmm10
| movsd qword [rbp-56], xmm9; movsd qword [rbp-64], xmm8
| movsd qword [rbp-72], xmm7; movsd qword [rbp-80], xmm6
| movsd qword [rbp-88], xmm5; movsd qword [rbp-96], xmm4
| movsd qword [rbp-104], xmm3; movsd qword [rbp-112], xmm2
| movsd qword [rbp-120], xmm1; movsd qword [rbp-128], xmm0
|.else
| sub esp, 8*8+16 // Room for SSE regs + args.
| movsd qword [ebp-40], xmm7; movsd qword [ebp-48], xmm6
| movsd qword [ebp-56], xmm5; movsd qword [ebp-64], xmm4
| movsd qword [ebp-72], xmm3; movsd qword [ebp-80], xmm2
| movsd qword [ebp-88], xmm1; movsd qword [ebp-96], xmm0
|.endif
| // Caveat: RB is ebp.
| mov L:RB, [DISPATCH+DISPATCH_GL(cur_L)]
| mov BASE, [DISPATCH+DISPATCH_GL(jit_base)]
| mov aword [DISPATCH+DISPATCH_J(L)], L:RBa
| mov L:RB->base, BASE
|.if X64WIN
| lea CARG2, [rsp+4*8]
|.elif X64
| mov CARG2, rsp
|.else
| lea FCARG2, [esp+16]
|.endif
| lea FCARG1, [DISPATCH+GG_DISP2J]
| mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0
| call extern lj_trace_exit@8 // (jit_State *J, ExitState *ex)
| // MULTRES or negated error code returned in eax (RD).
| mov RAa, L:RB->cframe
| and RAa, CFRAME_RAWMASK
|.if X64WIN
| // Reposition stack later.
|.elif X64
| mov rsp, RAa // Reposition stack to C frame.
|.else
| mov esp, RAa // Reposition stack to C frame.
|.endif
| mov [RAa+CFRAME_OFS_L], L:RB // Set SAVE_L (on-trace resume/yield).
| mov BASE, L:RB->base
| mov PC, [RAa+CFRAME_OFS_PC] // Get SAVE_PC.
|.if X64
| jmp >1
|.endif
|.endif
|->vm_exit_interp:
| // RD = MULTRES or negated error code, BASE, PC and DISPATCH set.
|.if JIT
|.if X64
| // Restore additional callee-save registers only used in compiled code.
|.if X64WIN
| lea RAa, [rsp+9*16+4*8]
|1:
| movdqa xmm15, [RAa-9*16]
| movdqa xmm14, [RAa-8*16]
| movdqa xmm13, [RAa-7*16]
| movdqa xmm12, [RAa-6*16]
| movdqa xmm11, [RAa-5*16]
| movdqa xmm10, [RAa-4*16]
| movdqa xmm9, [RAa-3*16]
| movdqa xmm8, [RAa-2*16]
| movdqa xmm7, [RAa-1*16]
| mov rsp, RAa // Reposition stack to C frame.
| movdqa xmm6, [RAa]
| mov r15, CSAVE_3
| mov r14, CSAVE_4
|.else
| add rsp, 16 // Reposition stack to C frame.
|1:
|.endif
| mov r13, TMPa
| mov r12, TMPQ
|.endif
| test RD, RD; js >9 // Check for error from exit.
| mov L:RB, SAVE_L
| mov MULTRES, RD
| mov LFUNC:KBASE, [BASE-8]
| mov KBASE, LFUNC:KBASE->pc
| mov KBASE, [KBASE+PC2PROTO(k)]
| mov L:RB->base, BASE
| mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0
| set_vmstate INTERP
| // Modified copy of ins_next which handles function header dispatch, too.
| mov RC, [PC]
| movzx RA, RCH
| movzx OP, RCL
| add PC, 4
| shr RC, 16
| cmp OP, BC_FUNCF // Function header?
| jb >3
| cmp OP, BC_FUNCC+2 // Fast function?
| jae >4
|2:
| mov RC, MULTRES // RC/RD holds nres+1.
|3:
|.if X64
| jmp aword [DISPATCH+OP*8]
|.else
| jmp aword [DISPATCH+OP*4]
|.endif
|
|4: // Check frame below fast function.
| mov RC, [BASE-4]
| test RC, FRAME_TYPE
| jnz <2 // Trace stitching continuation?
| // Otherwise set KBASE for Lua function below fast function.
| movzx RC, byte [RC-3]
| not RCa
| mov LFUNC:KBASE, [BASE+RC*8-8]
| mov KBASE, LFUNC:KBASE->pc
| mov KBASE, [KBASE+PC2PROTO(k)]
| jmp <2
|
|9: // Rethrow error from the right C frame.
| mov FCARG2, RD
| mov FCARG1, L:RB
| neg FCARG2
| call extern lj_err_trace@8 // (lua_State *L, int errcode)
|.endif
|
|//-----------------------------------------------------------------------
|//-- Math helper functions ----------------------------------------------
|//-----------------------------------------------------------------------
|
|// FP value rounding. Called by math.floor/math.ceil fast functions
|// and from JIT code. arg/ret is xmm0. xmm0-xmm3 and RD (eax) modified.
|.macro vm_round, name, mode, cond
|->name:
|.if not X64 and cond
| movsd xmm0, qword [esp+4]
| call ->name .. _sse
| movsd qword [esp+4], xmm0 // Overwrite callee-owned arg.
| fld qword [esp+4]
| ret
|.endif
|
|->name .. _sse:
| sseconst_abs xmm2, RDa
| sseconst_2p52 xmm3, RDa
| movaps xmm1, xmm0
| andpd xmm1, xmm2 // |x|
| ucomisd xmm3, xmm1 // No truncation if 2^52 <= |x|.
| jbe >1
| andnpd xmm2, xmm0 // Isolate sign bit.
|.if mode == 2 // trunc(x)?
| movaps xmm0, xmm1
| addsd xmm1, xmm3 // (|x| + 2^52) - 2^52
| subsd xmm1, xmm3
| sseconst_1 xmm3, RDa
| cmpsd xmm0, xmm1, 1 // |x| < result?
| andpd xmm0, xmm3
| subsd xmm1, xmm0 // If yes, subtract -1.
| orpd xmm1, xmm2 // Merge sign bit back in.
|.else
| addsd xmm1, xmm3 // (|x| + 2^52) - 2^52
| subsd xmm1, xmm3
| orpd xmm1, xmm2 // Merge sign bit back in.
| .if mode == 1 // ceil(x)?
| sseconst_m1 xmm2, RDa // Must subtract -1 to preserve -0.
| cmpsd xmm0, xmm1, 6 // x > result?
| .else // floor(x)?
| sseconst_1 xmm2, RDa
| cmpsd xmm0, xmm1, 1 // x < result?
| .endif
| andpd xmm0, xmm2
| subsd xmm1, xmm0 // If yes, subtract +-1.
|.endif
| movaps xmm0, xmm1
|1:
| ret
|.endmacro
|
| vm_round vm_floor, 0, 1
| vm_round vm_ceil, 1, JIT
| vm_round vm_trunc, 2, JIT
|
|// FP modulo x%y. Called by BC_MOD* and vm_arith.
|->vm_mod:
|// Args in xmm0/xmm1, return value in xmm0.
|// Caveat: xmm0-xmm5 and RC (eax) modified!
| movaps xmm5, xmm0
| divsd xmm0, xmm1
| sseconst_abs xmm2, RDa
| sseconst_2p52 xmm3, RDa
| movaps xmm4, xmm0
| andpd xmm4, xmm2 // |x/y|
| ucomisd xmm3, xmm4 // No truncation if 2^52 <= |x/y|.
| jbe >1
| andnpd xmm2, xmm0 // Isolate sign bit.
| addsd xmm4, xmm3 // (|x/y| + 2^52) - 2^52
| subsd xmm4, xmm3
| orpd xmm4, xmm2 // Merge sign bit back in.
| sseconst_1 xmm2, RDa
| cmpsd xmm0, xmm4, 1 // x/y < result?
| andpd xmm0, xmm2
| subsd xmm4, xmm0 // If yes, subtract 1.0.
| movaps xmm0, xmm5
| mulsd xmm1, xmm4
| subsd xmm0, xmm1
| ret
|1:
| mulsd xmm1, xmm0
| movaps xmm0, xmm5
| subsd xmm0, xmm1
| ret
|
|// Args in xmm0/eax. Ret in xmm0. xmm0-xmm1 and eax modified.
|->vm_powi_sse:
| cmp eax, 1; jle >6 // i<=1?
| // Now 1 < (unsigned)i <= 0x80000000.
|1: // Handle leading zeros.
| test eax, 1; jnz >2
| mulsd xmm0, xmm0
| shr eax, 1
| jmp <1
|2:
| shr eax, 1; jz >5
| movaps xmm1, xmm0
|3: // Handle trailing bits.
| mulsd xmm0, xmm0
| shr eax, 1; jz >4
| jnc <3
| mulsd xmm1, xmm0
| jmp <3
|4:
| mulsd xmm0, xmm1
|5:
| ret
|6:
| je <5 // x^1 ==> x
| jb >7 // x^0 ==> 1
| neg eax
| call <1
| sseconst_1 xmm1, RDa
| divsd xmm1, xmm0
| movaps xmm0, xmm1
| ret
|7:
| sseconst_1 xmm0, RDa
| ret
|
|//-----------------------------------------------------------------------
|//-- Miscellaneous functions --------------------------------------------
|//-----------------------------------------------------------------------
|
|// int lj_vm_cpuid(uint32_t f, uint32_t res[4])
|->vm_cpuid:
|.if X64
| mov eax, CARG1d
| .if X64WIN; push rsi; mov rsi, CARG2; .endif
| push rbx
| xor ecx, ecx
| cpuid
| mov [rsi], eax
| mov [rsi+4], ebx
| mov [rsi+8], ecx
| mov [rsi+12], edx
| pop rbx
| .if X64WIN; pop rsi; .endif
| ret
|.else
| pushfd
| pop edx
| mov ecx, edx
| xor edx, 0x00200000 // Toggle ID bit in flags.
| push edx
| popfd
| pushfd
| pop edx
| xor eax, eax // Zero means no features supported.
| cmp ecx, edx
| jz >1 // No ID toggle means no CPUID support.
| mov eax, [esp+4] // Argument 1 is function number.
| push edi
| push ebx
| xor ecx, ecx
| cpuid
| mov edi, [esp+16] // Argument 2 is result area.
| mov [edi], eax
| mov [edi+4], ebx
| mov [edi+8], ecx
| mov [edi+12], edx
| pop ebx
| pop edi
|1:
| ret
|.endif
|
|.define NEXT_TAB, TAB:FCARG1
|.define NEXT_IDX, FCARG2
|.define NEXT_PTR, RCa
|.define NEXT_PTRd, RC
|.macro NEXT_RES_IDXL, op2; lea edx, [NEXT_IDX+op2]; .endmacro
|.if X64
|.define NEXT_TMP, CARG3d
|.define NEXT_TMPq, CARG3
|.define NEXT_ASIZE, CARG4d
|.macro NEXT_ENTER; .endmacro
|.macro NEXT_LEAVE; ret; .endmacro
|.if X64WIN
|.define NEXT_RES_PTR, [rsp+aword*5]
|.macro NEXT_RES_IDX, op2; add NEXT_IDX, op2; .endmacro
|.else
|.define NEXT_RES_PTR, [rsp+aword*1]
|.macro NEXT_RES_IDX, op2; lea edx, [NEXT_IDX+op2]; .endmacro
|.endif
|.else
|.define NEXT_ASIZE, esi
|.define NEXT_TMP, edi
|.macro NEXT_ENTER; push esi; push edi; .endmacro
|.macro NEXT_LEAVE; pop edi; pop esi; ret; .endmacro
|.define NEXT_RES_PTR, [esp+dword*3]
|.macro NEXT_RES_IDX, op2; add NEXT_IDX, op2; .endmacro
|.endif
|
|// TValue *lj_vm_next(GCtab *t, uint32_t idx)
|// Next idx returned in edx.
|->vm_next:
|.if JIT
| NEXT_ENTER
| mov NEXT_ASIZE, NEXT_TAB->asize
|1: // Traverse array part.
| cmp NEXT_IDX, NEXT_ASIZE; jae >5
| mov NEXT_TMP, NEXT_TAB->array
| cmp dword [NEXT_TMP+NEXT_IDX*8+4], LJ_TNIL; je >2
| lea NEXT_PTR, NEXT_RES_PTR
|.if X64
| mov NEXT_TMPq, qword [NEXT_TMP+NEXT_IDX*8]
| mov qword [NEXT_PTR], NEXT_TMPq
|.else
| mov NEXT_ASIZE, dword [NEXT_TMP+NEXT_IDX*8+4]
| mov NEXT_TMP, dword [NEXT_TMP+NEXT_IDX*8]
| mov dword [NEXT_PTR+4], NEXT_ASIZE
| mov dword [NEXT_PTR], NEXT_TMP
|.endif
|.if DUALNUM
| mov dword [NEXT_PTR+dword*3], LJ_TISNUM
| mov dword [NEXT_PTR+dword*2], NEXT_IDX
|.else
| cvtsi2sd xmm0, NEXT_IDX
| movsd qword [NEXT_PTR+dword*2], xmm0
|.endif
| NEXT_RES_IDX 1
| NEXT_LEAVE
|2: // Skip holes in array part.
| add NEXT_IDX, 1
| jmp <1
|
|5: // Traverse hash part.
| sub NEXT_IDX, NEXT_ASIZE
|6:
| cmp NEXT_IDX, NEXT_TAB->hmask; ja >9
| imul NEXT_PTRd, NEXT_IDX, #NODE
| add NODE:NEXT_PTRd, dword NEXT_TAB->node
| cmp dword NODE:NEXT_PTR->val.it, LJ_TNIL; je >7
| NEXT_RES_IDXL NEXT_ASIZE+1
| NEXT_LEAVE
|7: // Skip holes in hash part.
| add NEXT_IDX, 1
| jmp <6
|
|9: // End of iteration. Set the key to nil (not the value).
| NEXT_RES_IDX NEXT_ASIZE
| lea NEXT_PTR, NEXT_RES_PTR
| mov dword [NEXT_PTR+dword*3], LJ_TNIL
| NEXT_LEAVE
|.endif
|
|//-----------------------------------------------------------------------
|//-- Assertions ---------------------------------------------------------
|//-----------------------------------------------------------------------
|
|->assert_bad_for_arg_type:
#ifdef LUA_USE_ASSERT
| int3
#endif
| int3
|
|//-----------------------------------------------------------------------
|//-- FFI helper functions -----------------------------------------------
|//-----------------------------------------------------------------------
|
|// Handler for callback functions. Callback slot number in ah/al.
|->vm_ffi_callback:
|.if FFI
|.type CTSTATE, CTState, PC
|.if not X64
| sub esp, 16 // Leave room for SAVE_ERRF etc.
|.endif
| saveregs_ // ebp/rbp already saved. ebp now holds global_State *.
| lea DISPATCH, [ebp+GG_G2DISP]
| mov CTSTATE, GL:ebp->ctype_state
| movzx eax, ax
| mov CTSTATE->cb.slot, eax
|.if X64
| mov CTSTATE->cb.gpr[0], CARG1
| mov CTSTATE->cb.gpr[1], CARG2
| mov CTSTATE->cb.gpr[2], CARG3
| mov CTSTATE->cb.gpr[3], CARG4
| movsd qword CTSTATE->cb.fpr[0], xmm0
| movsd qword CTSTATE->cb.fpr[1], xmm1
| movsd qword CTSTATE->cb.fpr[2], xmm2
| movsd qword CTSTATE->cb.fpr[3], xmm3
|.if X64WIN
| lea rax, [rsp+CFRAME_SIZE+4*8]
|.else
| lea rax, [rsp+CFRAME_SIZE]
| mov CTSTATE->cb.gpr[4], CARG5
| mov CTSTATE->cb.gpr[5], CARG6
| movsd qword CTSTATE->cb.fpr[4], xmm4
| movsd qword CTSTATE->cb.fpr[5], xmm5
| movsd qword CTSTATE->cb.fpr[6], xmm6
| movsd qword CTSTATE->cb.fpr[7], xmm7
|.endif
| mov CTSTATE->cb.stack, rax
| mov CARG2, rsp
|.else
| lea eax, [esp+CFRAME_SIZE+16]
| mov CTSTATE->cb.gpr[0], FCARG1
| mov CTSTATE->cb.gpr[1], FCARG2
| mov CTSTATE->cb.stack, eax
| mov FCARG1, [esp+CFRAME_SIZE+12] // Move around misplaced retaddr/ebp.
| mov FCARG2, [esp+CFRAME_SIZE+8]
| mov SAVE_RET, FCARG1
| mov SAVE_R4, FCARG2
| mov FCARG2, esp
|.endif
| mov SAVE_PC, CTSTATE // Any value outside of bytecode is ok.
| mov FCARG1, CTSTATE
| call extern lj_ccallback_enter@8 // (CTState *cts, void *cf)
| // lua_State * returned in eax (RD).
| set_vmstate INTERP
| mov BASE, L:RD->base
| mov RD, L:RD->top
| sub RD, BASE
| mov LFUNC:RB, [BASE-8]
| shr RD, 3
| add RD, 1
| ins_callt
|.endif
|
|->cont_ffi_callback: // Return from FFI callback.
|.if FFI
| mov L:RA, SAVE_L
| mov CTSTATE, [DISPATCH+DISPATCH_GL(ctype_state)]
| mov aword CTSTATE->L, L:RAa
| mov L:RA->base, BASE
| mov L:RA->top, RB
| mov FCARG1, CTSTATE
| mov FCARG2, RC
| call extern lj_ccallback_leave@8 // (CTState *cts, TValue *o)
|.if X64
| mov rax, CTSTATE->cb.gpr[0]
| movsd xmm0, qword CTSTATE->cb.fpr[0]
| jmp ->vm_leave_unw
|.else
| mov L:RB, SAVE_L
| mov eax, CTSTATE->cb.gpr[0]
| mov edx, CTSTATE->cb.gpr[1]
| cmp dword CTSTATE->cb.gpr[2], 1
| jb >7
| je >6
| fld qword CTSTATE->cb.fpr[0].d
| jmp >7
|6:
| fld dword CTSTATE->cb.fpr[0].f
|7:
| mov ecx, L:RB->top
| movzx ecx, word [ecx+6] // Get stack adjustment and copy up.
| mov SAVE_L, ecx // Must be one slot above SAVE_RET
| restoreregs
| pop ecx // Move return addr from SAVE_RET.
| add esp, [esp] // Adjust stack.
| add esp, 16
| push ecx
| ret
|.endif
|.endif
|
|->vm_ffi_call@4: // Call C function via FFI.
| // Caveat: needs special frame unwinding, see below.
|.if FFI
|.if X64
| .type CCSTATE, CCallState, rbx
| push rbp; mov rbp, rsp; push rbx; mov CCSTATE, CARG1
|.else
| .type CCSTATE, CCallState, ebx
| push ebp; mov ebp, esp; push ebx; mov CCSTATE, FCARG1
|.endif
|
| // Readjust stack.
|.if X64
| mov eax, CCSTATE->spadj
| sub rsp, rax
|.else
| sub esp, CCSTATE->spadj
|.if WIN
| mov CCSTATE->spadj, esp
|.endif
|.endif
|
| // Copy stack slots.
| movzx ecx, byte CCSTATE->nsp
| sub ecx, 1
| js >2
|1:
|.if X64
| mov rax, [CCSTATE+rcx*8+offsetof(CCallState, stack)]
| mov [rsp+rcx*8+CCALL_SPS_EXTRA*8], rax
|.else
| mov eax, [CCSTATE+ecx*4+offsetof(CCallState, stack)]
| mov [esp+ecx*4], eax
|.endif
| sub ecx, 1
| jns <1
|2:
|
|.if X64
| movzx eax, byte CCSTATE->nfpr
| mov CARG1, CCSTATE->gpr[0]
| mov CARG2, CCSTATE->gpr[1]
| mov CARG3, CCSTATE->gpr[2]
| mov CARG4, CCSTATE->gpr[3]
|.if not X64WIN
| mov CARG5, CCSTATE->gpr[4]
| mov CARG6, CCSTATE->gpr[5]
|.endif
| test eax, eax; jz >5
| movaps xmm0, CCSTATE->fpr[0]
| movaps xmm1, CCSTATE->fpr[1]
| movaps xmm2, CCSTATE->fpr[2]
| movaps xmm3, CCSTATE->fpr[3]
|.if not X64WIN
| cmp eax, 4; jbe >5
| movaps xmm4, CCSTATE->fpr[4]
| movaps xmm5, CCSTATE->fpr[5]
| movaps xmm6, CCSTATE->fpr[6]
| movaps xmm7, CCSTATE->fpr[7]
|.endif
|5:
|.else
| mov FCARG1, CCSTATE->gpr[0]
| mov FCARG2, CCSTATE->gpr[1]
|.endif
|
| call aword CCSTATE->func
|
|.if X64
| mov CCSTATE->gpr[0], rax
| movaps CCSTATE->fpr[0], xmm0
|.if not X64WIN
| mov CCSTATE->gpr[1], rdx
| movaps CCSTATE->fpr[1], xmm1
|.endif
|.else
| mov CCSTATE->gpr[0], eax
| mov CCSTATE->gpr[1], edx
| cmp byte CCSTATE->resx87, 1
| jb >7
| je >6
| fstp qword CCSTATE->fpr[0].d[0]
| jmp >7
|6:
| fstp dword CCSTATE->fpr[0].f[0]
|7:
|.if WIN
| sub CCSTATE->spadj, esp
|.endif
|.endif
|
|.if X64
| mov rbx, [rbp-8]; leave; ret
|.else
| mov ebx, [ebp-4]; leave; ret
|.endif
|.endif
|// Note: vm_ffi_call must be the last function in this object file!
|
|//-----------------------------------------------------------------------
}
/* Generate the code for a single instruction. */
static void build_ins(BuildCtx *ctx, BCOp op, int defop)
{
int vk = 0;
|// Note: aligning all instructions does not pay off.
|=>defop:
switch (op) {
/* -- Comparison ops ---------------------------------------------------- */
/* Remember: all ops branch for a true comparison, fall through otherwise. */
|.macro jmp_comp, lt, ge, le, gt, target
||switch (op) {
||case BC_ISLT:
| lt target
||break;
||case BC_ISGE:
| ge target
||break;
||case BC_ISLE:
| le target
||break;
||case BC_ISGT:
| gt target
||break;
||default: break; /* Shut up GCC. */
||}
|.endmacro
case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
| // RA = src1, RD = src2, JMP with RD = target
| ins_AD
|.if DUALNUM
| checkint RA, >7
| checkint RD, >8
| mov RB, dword [BASE+RA*8]
| add PC, 4
| cmp RB, dword [BASE+RD*8]
| jmp_comp jge, jl, jg, jle, >9
|6:
| movzx RD, PC_RD
| branchPC RD
|9:
| ins_next
|
|7: // RA is not an integer.
| ja ->vmeta_comp
| // RA is a number.
| cmp dword [BASE+RD*8+4], LJ_TISNUM; jb >1; jne ->vmeta_comp
| // RA is a number, RD is an integer.
| cvtsi2sd xmm0, dword [BASE+RD*8]
| jmp >2
|
|8: // RA is an integer, RD is not an integer.
| ja ->vmeta_comp
| // RA is an integer, RD is a number.
| cvtsi2sd xmm1, dword [BASE+RA*8]
| movsd xmm0, qword [BASE+RD*8]
| add PC, 4
| ucomisd xmm0, xmm1
| jmp_comp jbe, ja, jb, jae, <9
| jmp <6
|.else
| checknum RA, ->vmeta_comp
| checknum RD, ->vmeta_comp
|.endif
|1:
| movsd xmm0, qword [BASE+RD*8]
|2:
| add PC, 4
| ucomisd xmm0, qword [BASE+RA*8]
|3:
| // Unordered: all of ZF CF PF set, ordered: PF clear.
| // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't.
|.if DUALNUM
| jmp_comp jbe, ja, jb, jae, <9
| jmp <6
|.else
| jmp_comp jbe, ja, jb, jae, >1
| movzx RD, PC_RD
| branchPC RD
|1:
| ins_next
|.endif
break;
case BC_ISEQV: case BC_ISNEV:
vk = op == BC_ISEQV;
| ins_AD // RA = src1, RD = src2, JMP with RD = target
| mov RB, [BASE+RD*8+4]
| add PC, 4
|.if DUALNUM
| cmp RB, LJ_TISNUM; jne >7
| checkint RA, >8
| mov RB, dword [BASE+RD*8]
| cmp RB, dword [BASE+RA*8]
if (vk) {
| jne >9
} else {
| je >9
}
| movzx RD, PC_RD
| branchPC RD
|9:
| ins_next
|
|7: // RD is not an integer.
| ja >5
| // RD is a number.
| cmp dword [BASE+RA*8+4], LJ_TISNUM; jb >1; jne >5
| // RD is a number, RA is an integer.
| cvtsi2sd xmm0, dword [BASE+RA*8]
| jmp >2
|
|8: // RD is an integer, RA is not an integer.
| ja >5
| // RD is an integer, RA is a number.
| cvtsi2sd xmm0, dword [BASE+RD*8]
| ucomisd xmm0, qword [BASE+RA*8]
| jmp >4
|
|.else
| cmp RB, LJ_TISNUM; jae >5
| checknum RA, >5
|.endif
|1:
| movsd xmm0, qword [BASE+RA*8]
|2:
| ucomisd xmm0, qword [BASE+RD*8]
|4:
iseqne_fp:
if (vk) {
| jp >2 // Unordered means not equal.
| jne >2
} else {
| jp >2 // Unordered means not equal.
| je >1
}
iseqne_end:
if (vk) {
|1: // EQ: Branch to the target.
| movzx RD, PC_RD
| branchPC RD
|2: // NE: Fallthrough to next instruction.
|.if not FFI
|3:
|.endif
} else {
|.if not FFI
|3:
|.endif
|2: // NE: Branch to the target.
| movzx RD, PC_RD
| branchPC RD
|1: // EQ: Fallthrough to next instruction.
}
if (LJ_DUALNUM && (op == BC_ISEQV || op == BC_ISNEV ||
op == BC_ISEQN || op == BC_ISNEN)) {
| jmp <9
} else {
| ins_next
}
|
if (op == BC_ISEQV || op == BC_ISNEV) {
|5: // Either or both types are not numbers.
|.if FFI
| cmp RB, LJ_TCDATA; je ->vmeta_equal_cd
| checktp RA, LJ_TCDATA; je ->vmeta_equal_cd
|.endif
| checktp RA, RB // Compare types.
| jne <2 // Not the same type?
| cmp RB, LJ_TISPRI
| jae <1 // Same type and primitive type?
|
| // Same types and not a primitive type. Compare GCobj or pvalue.
| mov RA, [BASE+RA*8]
| mov RD, [BASE+RD*8]
| cmp RA, RD
| je <1 // Same GCobjs or pvalues?
| cmp RB, LJ_TISTABUD
| ja <2 // Different objects and not table/ud?
|.if X64
| cmp RB, LJ_TUDATA // And not 64 bit lightuserdata.
| jb <2
|.endif
|
| // Different tables or userdatas. Need to check __eq metamethod.
| // Field metatable must be at same offset for GCtab and GCudata!
| mov TAB:RB, TAB:RA->metatable
| test TAB:RB, TAB:RB
| jz <2 // No metatable?
| test byte TAB:RB->nomm, 1<<MM_eq
| jnz <2 // Or 'no __eq' flag set?
if (vk) {
| xor RB, RB // ne = 0
} else {
| mov RB, 1 // ne = 1
}
| jmp ->vmeta_equal // Handle __eq metamethod.
} else {
|.if FFI
|3:
| cmp RB, LJ_TCDATA
if (LJ_DUALNUM && vk) {
| jne <9
} else {
| jne <2
}
| jmp ->vmeta_equal_cd
|.endif
}
break;
case BC_ISEQS: case BC_ISNES:
vk = op == BC_ISEQS;
| ins_AND // RA = src, RD = str const, JMP with RD = target
| mov RB, [BASE+RA*8+4]
| add PC, 4
| cmp RB, LJ_TSTR; jne >3
| mov RA, [BASE+RA*8]
| cmp RA, [KBASE+RD*4]
iseqne_test:
if (vk) {
| jne >2
} else {
| je >1
}
goto iseqne_end;
case BC_ISEQN: case BC_ISNEN:
vk = op == BC_ISEQN;
| ins_AD // RA = src, RD = num const, JMP with RD = target
| mov RB, [BASE+RA*8+4]
| add PC, 4
|.if DUALNUM
| cmp RB, LJ_TISNUM; jne >7
| cmp dword [KBASE+RD*8+4], LJ_TISNUM; jne >8
| mov RB, dword [KBASE+RD*8]
| cmp RB, dword [BASE+RA*8]
if (vk) {
| jne >9
} else {
| je >9
}
| movzx RD, PC_RD
| branchPC RD
|9:
| ins_next
|
|7: // RA is not an integer.
| ja >3
| // RA is a number.
| cmp dword [KBASE+RD*8+4], LJ_TISNUM; jb >1
| // RA is a number, RD is an integer.
| cvtsi2sd xmm0, dword [KBASE+RD*8]
| jmp >2
|
|8: // RA is an integer, RD is a number.
| cvtsi2sd xmm0, dword [BASE+RA*8]
| ucomisd xmm0, qword [KBASE+RD*8]
| jmp >4
|.else
| cmp RB, LJ_TISNUM; jae >3
|.endif
|1:
| movsd xmm0, qword [KBASE+RD*8]
|2:
| ucomisd xmm0, qword [BASE+RA*8]
|4:
goto iseqne_fp;
case BC_ISEQP: case BC_ISNEP:
vk = op == BC_ISEQP;
| ins_AND // RA = src, RD = primitive type (~), JMP with RD = target
| mov RB, [BASE+RA*8+4]
| add PC, 4
| cmp RB, RD
if (!LJ_HASFFI) goto iseqne_test;
if (vk) {
| jne >3
| movzx RD, PC_RD
| branchPC RD
|2:
| ins_next
|3:
| cmp RB, LJ_TCDATA; jne <2
| jmp ->vmeta_equal_cd
} else {
| je >2
| cmp RB, LJ_TCDATA; je ->vmeta_equal_cd
| movzx RD, PC_RD
| branchPC RD
|2:
| ins_next
}
break;
/* -- Unary test and copy ops ------------------------------------------- */
case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
| ins_AD // RA = dst or unused, RD = src, JMP with RD = target
| mov RB, [BASE+RD*8+4]
| add PC, 4
| cmp RB, LJ_TISTRUECOND
if (op == BC_IST || op == BC_ISTC) {
| jae >1
} else {
| jb >1
}
if (op == BC_ISTC || op == BC_ISFC) {
| mov [BASE+RA*8+4], RB
| mov RB, [BASE+RD*8]
| mov [BASE+RA*8], RB
}
| movzx RD, PC_RD
| branchPC RD
|1: // Fallthrough to the next instruction.
| ins_next
break;
case BC_ISTYPE:
| ins_AD // RA = src, RD = -type
| add RD, [BASE+RA*8+4]
| jne ->vmeta_istype
| ins_next
break;
case BC_ISNUM:
| ins_AD // RA = src, RD = -(TISNUM-1)
| checknum RA, ->vmeta_istype
| ins_next
break;
/* -- Unary ops --------------------------------------------------------- */
case BC_MOV:
| ins_AD // RA = dst, RD = src
|.if X64
| mov RBa, [BASE+RD*8]
| mov [BASE+RA*8], RBa
|.else
| mov RB, [BASE+RD*8+4]
| mov RD, [BASE+RD*8]
| mov [BASE+RA*8+4], RB
| mov [BASE+RA*8], RD
|.endif
| ins_next_
break;
case BC_NOT:
| ins_AD // RA = dst, RD = src
| xor RB, RB
| checktp RD, LJ_TISTRUECOND
| adc RB, LJ_TTRUE
| mov [BASE+RA*8+4], RB
| ins_next
break;
case BC_UNM:
| ins_AD // RA = dst, RD = src
|.if DUALNUM
| checkint RD, >5
| mov RB, [BASE+RD*8]
| neg RB
| jo >4
| mov dword [BASE+RA*8+4], LJ_TISNUM
| mov dword [BASE+RA*8], RB
|9:
| ins_next
|4:
| mov dword [BASE+RA*8+4], 0x41e00000 // 2^31.
| mov dword [BASE+RA*8], 0
| jmp <9
|5:
| ja ->vmeta_unm
|.else
| checknum RD, ->vmeta_unm
|.endif
| movsd xmm0, qword [BASE+RD*8]
| sseconst_sign xmm1, RDa
| xorps xmm0, xmm1
| movsd qword [BASE+RA*8], xmm0
|.if DUALNUM
| jmp <9
|.else
| ins_next
|.endif
break;
case BC_LEN:
| ins_AD // RA = dst, RD = src
| checkstr RD, >2
| mov STR:RD, [BASE+RD*8]
|.if DUALNUM
| mov RD, dword STR:RD->len
|1:
| mov dword [BASE+RA*8+4], LJ_TISNUM
| mov dword [BASE+RA*8], RD
|.else
| xorps xmm0, xmm0
| cvtsi2sd xmm0, dword STR:RD->len
|1:
| movsd qword [BASE+RA*8], xmm0
|.endif
| ins_next
|2:
| checktab RD, ->vmeta_len
| mov TAB:FCARG1, [BASE+RD*8]
#if LJ_52
| mov TAB:RB, TAB:FCARG1->metatable
| cmp TAB:RB, 0
| jnz >9
|3:
#endif
|->BC_LEN_Z:
| mov RB, BASE // Save BASE.
| call extern lj_tab_len@4 // (GCtab *t)
| // Length of table returned in eax (RD).
|.if DUALNUM
| // Nothing to do.
|.else
| cvtsi2sd xmm0, RD
|.endif
| mov BASE, RB // Restore BASE.
| movzx RA, PC_RA
| jmp <1
#if LJ_52
|9: // Check for __len.
| test byte TAB:RB->nomm, 1<<MM_len
| jnz <3
| jmp ->vmeta_len // 'no __len' flag NOT set: check.
#endif
break;
/* -- Binary ops -------------------------------------------------------- */
|.macro ins_arithpre, sseins, ssereg
| ins_ABC
||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
||switch (vk) {
||case 0:
| checknum RB, ->vmeta_arith_vn
| .if DUALNUM
| cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_vn
| .endif
| movsd xmm0, qword [BASE+RB*8]
| sseins ssereg, qword [KBASE+RC*8]
|| break;
||case 1:
| checknum RB, ->vmeta_arith_nv
| .if DUALNUM
| cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_nv
| .endif
| movsd xmm0, qword [KBASE+RC*8]
| sseins ssereg, qword [BASE+RB*8]
|| break;
||default:
| checknum RB, ->vmeta_arith_vv
| checknum RC, ->vmeta_arith_vv
| movsd xmm0, qword [BASE+RB*8]
| sseins ssereg, qword [BASE+RC*8]
|| break;
||}
|.endmacro
|
|.macro ins_arithdn, intins
| ins_ABC
||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
||switch (vk) {
||case 0:
| checkint RB, ->vmeta_arith_vn
| cmp dword [KBASE+RC*8+4], LJ_TISNUM; jne ->vmeta_arith_vn
| mov RB, [BASE+RB*8]
| intins RB, [KBASE+RC*8]; jo ->vmeta_arith_vno
|| break;
||case 1:
| checkint RB, ->vmeta_arith_nv
| cmp dword [KBASE+RC*8+4], LJ_TISNUM; jne ->vmeta_arith_nv
| mov RC, [KBASE+RC*8]
| intins RC, [BASE+RB*8]; jo ->vmeta_arith_nvo
|| break;
||default:
| checkint RB, ->vmeta_arith_vv
| checkint RC, ->vmeta_arith_vv
| mov RB, [BASE+RB*8]
| intins RB, [BASE+RC*8]; jo ->vmeta_arith_vvo
|| break;
||}
| mov dword [BASE+RA*8+4], LJ_TISNUM
||if (vk == 1) {
| mov dword [BASE+RA*8], RC
||} else {
| mov dword [BASE+RA*8], RB
||}
| ins_next
|.endmacro
|
|.macro ins_arithpost
| movsd qword [BASE+RA*8], xmm0
|.endmacro
|
|.macro ins_arith, sseins
| ins_arithpre sseins, xmm0
| ins_arithpost
| ins_next
|.endmacro
|
|.macro ins_arith, intins, sseins
|.if DUALNUM
| ins_arithdn intins
|.else
| ins_arith, sseins
|.endif
|.endmacro
| // RA = dst, RB = src1 or num const, RC = src2 or num const
case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
| ins_arith add, addsd
break;
case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
| ins_arith sub, subsd
break;
case BC_MULVN: case BC_MULNV: case BC_MULVV:
| ins_arith imul, mulsd
break;
case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
| ins_arith divsd
break;
case BC_MODVN:
| ins_arithpre movsd, xmm1
|->BC_MODVN_Z:
| call ->vm_mod
| ins_arithpost
| ins_next
break;
case BC_MODNV: case BC_MODVV:
| ins_arithpre movsd, xmm1
| jmp ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
break;
case BC_POW:
| ins_arithpre movsd, xmm1
| mov RB, BASE
|.if not X64
| movsd FPARG1, xmm0
| movsd FPARG3, xmm1
|.endif
| call extern pow
| movzx RA, PC_RA
| mov BASE, RB
|.if X64
| ins_arithpost
|.else
| fstp qword [BASE+RA*8]
|.endif
| ins_next
break;
case BC_CAT:
| ins_ABC // RA = dst, RB = src_start, RC = src_end
|.if X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE
| lea CARG2d, [BASE+RC*8]
| mov CARG3d, RC
| sub CARG3d, RB
|->BC_CAT_Z:
| mov L:RB, L:CARG1d
|.else
| lea RA, [BASE+RC*8]
| sub RC, RB
| mov ARG2, RA
| mov ARG3, RC
|->BC_CAT_Z:
| mov L:RB, SAVE_L
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_meta_cat // (lua_State *L, TValue *top, int left)
| // NULL (finished) or TValue * (metamethod) returned in eax (RC).
| mov BASE, L:RB->base
| test RC, RC
| jnz ->vmeta_binop
| movzx RB, PC_RB // Copy result to Stk[RA] from Stk[RB].
| movzx RA, PC_RA
|.if X64
| mov RCa, [BASE+RB*8]
| mov [BASE+RA*8], RCa
|.else
| mov RC, [BASE+RB*8+4]
| mov RB, [BASE+RB*8]
| mov [BASE+RA*8+4], RC
| mov [BASE+RA*8], RB
|.endif
| ins_next
break;
/* -- Constant ops ------------------------------------------------------ */
case BC_KSTR:
| ins_AND // RA = dst, RD = str const (~)
| mov RD, [KBASE+RD*4]
| mov dword [BASE+RA*8+4], LJ_TSTR
| mov [BASE+RA*8], RD
| ins_next
break;
case BC_KCDATA:
|.if FFI
| ins_AND // RA = dst, RD = cdata const (~)
| mov RD, [KBASE+RD*4]
| mov dword [BASE+RA*8+4], LJ_TCDATA
| mov [BASE+RA*8], RD
| ins_next
|.endif
break;
case BC_KSHORT:
| ins_AD // RA = dst, RD = signed int16 literal
|.if DUALNUM
| movsx RD, RDW
| mov dword [BASE+RA*8+4], LJ_TISNUM
| mov dword [BASE+RA*8], RD
|.else
| movsx RD, RDW // Sign-extend literal.
| cvtsi2sd xmm0, RD
| movsd qword [BASE+RA*8], xmm0
|.endif
| ins_next
break;
case BC_KNUM:
| ins_AD // RA = dst, RD = num const
| movsd xmm0, qword [KBASE+RD*8]
| movsd qword [BASE+RA*8], xmm0
| ins_next
break;
case BC_KPRI:
| ins_AND // RA = dst, RD = primitive type (~)
| mov [BASE+RA*8+4], RD
| ins_next
break;
case BC_KNIL:
| ins_AD // RA = dst_start, RD = dst_end
| lea RA, [BASE+RA*8+12]
| lea RD, [BASE+RD*8+4]
| mov RB, LJ_TNIL
| mov [RA-8], RB // Sets minimum 2 slots.
|1:
| mov [RA], RB
| add RA, 8
| cmp RA, RD
| jbe <1
| ins_next
break;
/* -- Upvalue and function ops ------------------------------------------ */
case BC_UGET:
| ins_AD // RA = dst, RD = upvalue #
| mov LFUNC:RB, [BASE-8]
| mov UPVAL:RB, [LFUNC:RB+RD*4+offsetof(GCfuncL, uvptr)]
| mov RB, UPVAL:RB->v
|.if X64
| mov RDa, [RB]
| mov [BASE+RA*8], RDa
|.else
| mov RD, [RB+4]
| mov RB, [RB]
| mov [BASE+RA*8+4], RD
| mov [BASE+RA*8], RB
|.endif
| ins_next
break;
case BC_USETV:
#define TV2MARKOFS \
((int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv))
| ins_AD // RA = upvalue #, RD = src
| mov LFUNC:RB, [BASE-8]
| mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)]
| cmp byte UPVAL:RB->closed, 0
| mov RB, UPVAL:RB->v
| mov RA, [BASE+RD*8]
| mov RD, [BASE+RD*8+4]
| mov [RB], RA
| mov [RB+4], RD
| jz >1
| // Check barrier for closed upvalue.
| test byte [RB+TV2MARKOFS], LJ_GC_BLACK // isblack(uv)
| jnz >2
|1:
| ins_next
|
|2: // Upvalue is black. Check if new value is collectable and white.
| sub RD, LJ_TISGCV
| cmp RD, LJ_TNUMX - LJ_TISGCV // tvisgcv(v)
| jbe <1
| test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(v)
| jz <1
| // Crossed a write barrier. Move the barrier forward.
|.if X64 and not X64WIN
| mov FCARG2, RB
| mov RB, BASE // Save BASE.
|.else
| xchg FCARG2, RB // Save BASE (FCARG2 == BASE).
|.endif
| lea GL:FCARG1, [DISPATCH+GG_DISP2G]
| call extern lj_gc_barrieruv@8 // (global_State *g, TValue *tv)
| mov BASE, RB // Restore BASE.
| jmp <1
break;
#undef TV2MARKOFS
case BC_USETS:
| ins_AND // RA = upvalue #, RD = str const (~)
| mov LFUNC:RB, [BASE-8]
| mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)]
| mov GCOBJ:RA, [KBASE+RD*4]
| mov RD, UPVAL:RB->v
| mov [RD], GCOBJ:RA
| mov dword [RD+4], LJ_TSTR
| test byte UPVAL:RB->marked, LJ_GC_BLACK // isblack(uv)
| jnz >2
|1:
| ins_next
|
|2: // Check if string is white and ensure upvalue is closed.
| test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(str)
| jz <1
| cmp byte UPVAL:RB->closed, 0
| jz <1
| // Crossed a write barrier. Move the barrier forward.
| mov RB, BASE // Save BASE (FCARG2 == BASE).
| mov FCARG2, RD
| lea GL:FCARG1, [DISPATCH+GG_DISP2G]
| call extern lj_gc_barrieruv@8 // (global_State *g, TValue *tv)
| mov BASE, RB // Restore BASE.
| jmp <1
break;
case BC_USETN:
| ins_AD // RA = upvalue #, RD = num const
| mov LFUNC:RB, [BASE-8]
| movsd xmm0, qword [KBASE+RD*8]
| mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)]
| mov RA, UPVAL:RB->v
| movsd qword [RA], xmm0
| ins_next
break;
case BC_USETP:
| ins_AND // RA = upvalue #, RD = primitive type (~)
| mov LFUNC:RB, [BASE-8]
| mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)]
| mov RA, UPVAL:RB->v
| mov [RA+4], RD
| ins_next
break;
case BC_UCLO:
| ins_AD // RA = level, RD = target
| branchPC RD // Do this first to free RD.
| mov L:RB, SAVE_L
| cmp dword L:RB->openupval, 0
| je >1
| mov L:RB->base, BASE
| lea FCARG2, [BASE+RA*8] // Caveat: FCARG2 == BASE
| mov L:FCARG1, L:RB // Caveat: FCARG1 == RA
| call extern lj_func_closeuv@8 // (lua_State *L, TValue *level)
| mov BASE, L:RB->base
|1:
| ins_next
break;
case BC_FNEW:
| ins_AND // RA = dst, RD = proto const (~) (holding function prototype)
|.if X64
| mov L:RB, SAVE_L
| mov L:RB->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG3d, [BASE-8]
| mov CARG2d, [KBASE+RD*4] // Fetch GCproto *.
| mov CARG1d, L:RB
|.else
| mov LFUNC:RA, [BASE-8]
| mov PROTO:RD, [KBASE+RD*4] // Fetch GCproto *.
| mov L:RB, SAVE_L
| mov ARG3, LFUNC:RA
| mov ARG2, PROTO:RD
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| // (lua_State *L, GCproto *pt, GCfuncL *parent)
| call extern lj_func_newL_gc
| // GCfuncL * returned in eax (RC).
| mov BASE, L:RB->base
| movzx RA, PC_RA
| mov [BASE+RA*8], LFUNC:RC
| mov dword [BASE+RA*8+4], LJ_TFUNC
| ins_next
break;
/* -- Table ops --------------------------------------------------------- */
case BC_TNEW:
| ins_AD // RA = dst, RD = hbits|asize
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov RA, [DISPATCH+DISPATCH_GL(gc.total)]
| cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)]
| mov SAVE_PC, PC
| jae >5
|1:
|.if X64
| mov CARG3d, RD
| and RD, 0x7ff
| shr CARG3d, 11
|.else
| mov RA, RD
| and RD, 0x7ff
| shr RA, 11
| mov ARG3, RA
|.endif
| cmp RD, 0x7ff
| je >3
|2:
|.if X64
| mov L:CARG1d, L:RB
| mov CARG2d, RD
|.else
| mov ARG1, L:RB
| mov ARG2, RD
|.endif
| call extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits)
| // Table * returned in eax (RC).
| mov BASE, L:RB->base
| movzx RA, PC_RA
| mov [BASE+RA*8], TAB:RC
| mov dword [BASE+RA*8+4], LJ_TTAB
| ins_next
|3: // Turn 0x7ff into 0x801.
| mov RD, 0x801
| jmp <2
|5:
| mov L:FCARG1, L:RB
| call extern lj_gc_step_fixtop@4 // (lua_State *L)
| movzx RD, PC_RD
| jmp <1
break;
case BC_TDUP:
| ins_AND // RA = dst, RD = table const (~) (holding template table)
| mov L:RB, SAVE_L
| mov RA, [DISPATCH+DISPATCH_GL(gc.total)]
| mov SAVE_PC, PC
| cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)]
| mov L:RB->base, BASE
| jae >3
|2:
| mov TAB:FCARG2, [KBASE+RD*4] // Caveat: FCARG2 == BASE
| mov L:FCARG1, L:RB // Caveat: FCARG1 == RA
| call extern lj_tab_dup@8 // (lua_State *L, Table *kt)
| // Table * returned in eax (RC).
| mov BASE, L:RB->base
| movzx RA, PC_RA
| mov [BASE+RA*8], TAB:RC
| mov dword [BASE+RA*8+4], LJ_TTAB
| ins_next
|3:
| mov L:FCARG1, L:RB
| call extern lj_gc_step_fixtop@4 // (lua_State *L)
| movzx RD, PC_RD // Need to reload RD.
| not RDa
| jmp <2
break;
case BC_GGET:
| ins_AND // RA = dst, RD = str const (~)
| mov LFUNC:RB, [BASE-8]
| mov TAB:RB, LFUNC:RB->env
| mov STR:RC, [KBASE+RD*4]
| jmp ->BC_TGETS_Z
break;
case BC_GSET:
| ins_AND // RA = src, RD = str const (~)
| mov LFUNC:RB, [BASE-8]
| mov TAB:RB, LFUNC:RB->env
| mov STR:RC, [KBASE+RD*4]
| jmp ->BC_TSETS_Z
break;
case BC_TGETV:
| ins_ABC // RA = dst, RB = table, RC = key
| checktab RB, ->vmeta_tgetv
| mov TAB:RB, [BASE+RB*8]
|
| // Integer key?
|.if DUALNUM
| checkint RC, >5
| mov RC, dword [BASE+RC*8]
|.else
| // Convert number to int and back and compare.
| checknum RC, >5
| movsd xmm0, qword [BASE+RC*8]
| cvttsd2si RC, xmm0
| cvtsi2sd xmm1, RC
| ucomisd xmm0, xmm1
| jne ->vmeta_tgetv // Generic numeric key? Use fallback.
|.endif
| cmp RC, TAB:RB->asize // Takes care of unordered, too.
| jae ->vmeta_tgetv // Not in array part? Use fallback.
| shl RC, 3
| add RC, TAB:RB->array
| cmp dword [RC+4], LJ_TNIL // Avoid overwriting RB in fastpath.
| je >2
| // Get array slot.
|.if X64
| mov RBa, [RC]
| mov [BASE+RA*8], RBa
|.else
| mov RB, [RC]
| mov RC, [RC+4]
| mov [BASE+RA*8], RB
| mov [BASE+RA*8+4], RC
|.endif
|1:
| ins_next
|
|2: // Check for __index if table value is nil.
| cmp dword TAB:RB->metatable, 0 // Shouldn't overwrite RA for fastpath.
| jz >3
| mov TAB:RA, TAB:RB->metatable
| test byte TAB:RA->nomm, 1<<MM_index
| jz ->vmeta_tgetv // 'no __index' flag NOT set: check.
| movzx RA, PC_RA // Restore RA.
|3:
| mov dword [BASE+RA*8+4], LJ_TNIL
| jmp <1
|
|5: // String key?
| checkstr RC, ->vmeta_tgetv
| mov STR:RC, [BASE+RC*8]
| jmp ->BC_TGETS_Z
break;
case BC_TGETS:
| ins_ABC // RA = dst, RB = table, RC = str const (~)
| not RCa
| mov STR:RC, [KBASE+RC*4]
| checktab RB, ->vmeta_tgets
| mov TAB:RB, [BASE+RB*8]
|->BC_TGETS_Z: // RB = GCtab *, RC = GCstr *, refetches PC_RA.
| mov RA, TAB:RB->hmask
| and RA, STR:RC->sid
| imul RA, #NODE
| add NODE:RA, TAB:RB->node
|1:
| cmp dword NODE:RA->key.it, LJ_TSTR
| jne >4
| cmp dword NODE:RA->key.gcr, STR:RC
| jne >4
| // Ok, key found. Assumes: offsetof(Node, val) == 0
| cmp dword [RA+4], LJ_TNIL // Avoid overwriting RB in fastpath.
| je >5 // Key found, but nil value?
| movzx RC, PC_RA
| // Get node value.
|.if X64
| mov RBa, [RA]
| mov [BASE+RC*8], RBa
|.else
| mov RB, [RA]
| mov RA, [RA+4]
| mov [BASE+RC*8], RB
| mov [BASE+RC*8+4], RA
|.endif
|2:
| ins_next
|
|3:
| movzx RC, PC_RA
| mov dword [BASE+RC*8+4], LJ_TNIL
| jmp <2
|
|4: // Follow hash chain.
| mov NODE:RA, NODE:RA->next
| test NODE:RA, NODE:RA
| jnz <1
| // End of hash chain: key not found, nil result.
|
|5: // Check for __index if table value is nil.
| mov TAB:RA, TAB:RB->metatable
| test TAB:RA, TAB:RA
| jz <3 // No metatable: done.
| test byte TAB:RA->nomm, 1<<MM_index
| jnz <3 // 'no __index' flag set: done.
| jmp ->vmeta_tgets // Caveat: preserve STR:RC.
break;
case BC_TGETB:
| ins_ABC // RA = dst, RB = table, RC = byte literal
| checktab RB, ->vmeta_tgetb
| mov TAB:RB, [BASE+RB*8]
| cmp RC, TAB:RB->asize
| jae ->vmeta_tgetb
| shl RC, 3
| add RC, TAB:RB->array
| cmp dword [RC+4], LJ_TNIL // Avoid overwriting RB in fastpath.
| je >2
| // Get array slot.
|.if X64
| mov RBa, [RC]
| mov [BASE+RA*8], RBa
|.else
| mov RB, [RC]
| mov RC, [RC+4]
| mov [BASE+RA*8], RB
| mov [BASE+RA*8+4], RC
|.endif
|1:
| ins_next
|
|2: // Check for __index if table value is nil.
| cmp dword TAB:RB->metatable, 0 // Shouldn't overwrite RA for fastpath.
| jz >3
| mov TAB:RA, TAB:RB->metatable
| test byte TAB:RA->nomm, 1<<MM_index
| jz ->vmeta_tgetb // 'no __index' flag NOT set: check.
| movzx RA, PC_RA // Restore RA.
|3:
| mov dword [BASE+RA*8+4], LJ_TNIL
| jmp <1
break;
case BC_TGETR:
| ins_ABC // RA = dst, RB = table, RC = key
| mov TAB:RB, [BASE+RB*8]
|.if DUALNUM
| mov RC, dword [BASE+RC*8]
|.else
| cvttsd2si RC, qword [BASE+RC*8]
|.endif
| cmp RC, TAB:RB->asize
| jae ->vmeta_tgetr // Not in array part? Use fallback.
| shl RC, 3
| add RC, TAB:RB->array
| // Get array slot.
|->BC_TGETR_Z:
|.if X64
| mov RBa, [RC]
| mov [BASE+RA*8], RBa
|.else
| mov RB, [RC]
| mov RC, [RC+4]
| mov [BASE+RA*8], RB
| mov [BASE+RA*8+4], RC
|.endif
|->BC_TGETR2_Z:
| ins_next
break;
case BC_TSETV:
| ins_ABC // RA = src, RB = table, RC = key
| checktab RB, ->vmeta_tsetv
| mov TAB:RB, [BASE+RB*8]
|
| // Integer key?
|.if DUALNUM
| checkint RC, >5
| mov RC, dword [BASE+RC*8]
|.else
| // Convert number to int and back and compare.
| checknum RC, >5
| movsd xmm0, qword [BASE+RC*8]
| cvttsd2si RC, xmm0
| cvtsi2sd xmm1, RC
| ucomisd xmm0, xmm1
| jne ->vmeta_tsetv // Generic numeric key? Use fallback.
|.endif
| cmp RC, TAB:RB->asize // Takes care of unordered, too.
| jae ->vmeta_tsetv
| shl RC, 3
| add RC, TAB:RB->array
| cmp dword [RC+4], LJ_TNIL
| je >3 // Previous value is nil?
|1:
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jnz >7
|2: // Set array slot.
|.if X64
| mov RBa, [BASE+RA*8]
| mov [RC], RBa
|.else
| mov RB, [BASE+RA*8+4]
| mov RA, [BASE+RA*8]
| mov [RC+4], RB
| mov [RC], RA
|.endif
| ins_next
|
|3: // Check for __newindex if previous value is nil.
| cmp dword TAB:RB->metatable, 0 // Shouldn't overwrite RA for fastpath.
| jz <1
| mov TAB:RA, TAB:RB->metatable
| test byte TAB:RA->nomm, 1<<MM_newindex
| jz ->vmeta_tsetv // 'no __newindex' flag NOT set: check.
| movzx RA, PC_RA // Restore RA.
| jmp <1
|
|5: // String key?
| checkstr RC, ->vmeta_tsetv
| mov STR:RC, [BASE+RC*8]
| jmp ->BC_TSETS_Z
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, RA
| movzx RA, PC_RA // Restore RA.
| jmp <2
break;
case BC_TSETS:
| ins_ABC // RA = src, RB = table, RC = str const (~)
| not RCa
| mov STR:RC, [KBASE+RC*4]
| checktab RB, ->vmeta_tsets
| mov TAB:RB, [BASE+RB*8]
|->BC_TSETS_Z: // RB = GCtab *, RC = GCstr *, refetches PC_RA.
| mov RA, TAB:RB->hmask
| and RA, STR:RC->sid
| imul RA, #NODE
| mov byte TAB:RB->nomm, 0 // Clear metamethod cache.
| add NODE:RA, TAB:RB->node
|1:
| cmp dword NODE:RA->key.it, LJ_TSTR
| jne >5
| cmp dword NODE:RA->key.gcr, STR:RC
| jne >5
| // Ok, key found. Assumes: offsetof(Node, val) == 0
| cmp dword [RA+4], LJ_TNIL
| je >4 // Previous value is nil?
|2:
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jnz >7
|3: // Set node value.
| movzx RC, PC_RA
|.if X64
| mov RBa, [BASE+RC*8]
| mov [RA], RBa
|.else
| mov RB, [BASE+RC*8+4]
| mov RC, [BASE+RC*8]
| mov [RA+4], RB
| mov [RA], RC
|.endif
| ins_next
|
|4: // Check for __newindex if previous value is nil.
| cmp dword TAB:RB->metatable, 0 // Shouldn't overwrite RA for fastpath.
| jz <2
| mov TMP1, RA // Save RA.
| mov TAB:RA, TAB:RB->metatable
| test byte TAB:RA->nomm, 1<<MM_newindex
| jz ->vmeta_tsets // 'no __newindex' flag NOT set: check.
| mov RA, TMP1 // Restore RA.
| jmp <2
|
|5: // Follow hash chain.
| mov NODE:RA, NODE:RA->next
| test NODE:RA, NODE:RA
| jnz <1
| // End of hash chain: key not found, add a new one.
|
| // But check for __newindex first.
| mov TAB:RA, TAB:RB->metatable
| test TAB:RA, TAB:RA
| jz >6 // No metatable: continue.
| test byte TAB:RA->nomm, 1<<MM_newindex
| jz ->vmeta_tsets // 'no __newindex' flag NOT set: check.
|6:
| mov TMP1, STR:RC
| mov TMP2, LJ_TSTR
| mov TMP3, TAB:RB // Save TAB:RB for us.
|.if X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE
| lea CARG3, TMP1
| mov CARG2d, TAB:RB
| mov L:RB, L:CARG1d
|.else
| lea RC, TMP1 // Store temp. TValue in TMP1/TMP2.
| mov ARG2, TAB:RB
| mov L:RB, SAVE_L
| mov ARG3, RC
| mov ARG1, L:RB
| mov L:RB->base, BASE
|.endif
| mov SAVE_PC, PC
| call extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k)
| // Handles write barrier for the new key. TValue * returned in eax (RC).
| mov BASE, L:RB->base
| mov TAB:RB, TMP3 // Need TAB:RB for barrier.
| mov RA, eax
| jmp <2 // Must check write barrier for value.
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, RC // Destroys STR:RC.
| jmp <3
break;
case BC_TSETB:
| ins_ABC // RA = src, RB = table, RC = byte literal
| checktab RB, ->vmeta_tsetb
| mov TAB:RB, [BASE+RB*8]
| cmp RC, TAB:RB->asize
| jae ->vmeta_tsetb
| shl RC, 3
| add RC, TAB:RB->array
| cmp dword [RC+4], LJ_TNIL
| je >3 // Previous value is nil?
|1:
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jnz >7
|2: // Set array slot.
|.if X64
| mov RAa, [BASE+RA*8]
| mov [RC], RAa
|.else
| mov RB, [BASE+RA*8+4]
| mov RA, [BASE+RA*8]
| mov [RC+4], RB
| mov [RC], RA
|.endif
| ins_next
|
|3: // Check for __newindex if previous value is nil.
| cmp dword TAB:RB->metatable, 0 // Shouldn't overwrite RA for fastpath.
| jz <1
| mov TAB:RA, TAB:RB->metatable
| test byte TAB:RA->nomm, 1<<MM_newindex
| jz ->vmeta_tsetb // 'no __newindex' flag NOT set: check.
| movzx RA, PC_RA // Restore RA.
| jmp <1
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, RA
| movzx RA, PC_RA // Restore RA.
| jmp <2
break;
case BC_TSETR:
| ins_ABC // RA = src, RB = table, RC = key
| mov TAB:RB, [BASE+RB*8]
|.if DUALNUM
| mov RC, dword [BASE+RC*8]
|.else
| cvttsd2si RC, qword [BASE+RC*8]
|.endif
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jnz >7
|2:
| cmp RC, TAB:RB->asize
| jae ->vmeta_tsetr
| shl RC, 3
| add RC, TAB:RB->array
| // Set array slot.
|->BC_TSETR_Z:
|.if X64
| mov RBa, [BASE+RA*8]
| mov [RC], RBa
|.else
| mov RB, [BASE+RA*8+4]
| mov RA, [BASE+RA*8]
| mov [RC+4], RB
| mov [RC], RA
|.endif
| ins_next
|
|7: // Possible table write barrier for the value. Skip valiswhite check.
| barrierback TAB:RB, RA
| movzx RA, PC_RA // Restore RA.
| jmp <2
break;
case BC_TSETM:
| ins_AD // RA = base (table at base-1), RD = num const (start index)
| mov TMP1, KBASE // Need one more free register.
| mov KBASE, dword [KBASE+RD*8] // Integer constant is in lo-word.
|1:
| lea RA, [BASE+RA*8]
| mov TAB:RB, [RA-8] // Guaranteed to be a table.
| test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
| jnz >7
|2:
| mov RD, MULTRES
| sub RD, 1
| jz >4 // Nothing to copy?
| add RD, KBASE // Compute needed size.
| cmp RD, TAB:RB->asize
| ja >5 // Doesn't fit into array part?
| sub RD, KBASE
| shl KBASE, 3
| add KBASE, TAB:RB->array
|3: // Copy result slots to table.
|.if X64
| mov RBa, [RA]
| add RA, 8
| mov [KBASE], RBa
|.else
| mov RB, [RA]
| mov [KBASE], RB
| mov RB, [RA+4]
| add RA, 8
| mov [KBASE+4], RB
|.endif
| add KBASE, 8
| sub RD, 1
| jnz <3
|4:
| mov KBASE, TMP1
| ins_next
|
|5: // Need to resize array part.
|.if X64
| mov L:CARG1d, SAVE_L
| mov L:CARG1d->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
| mov CARG2d, TAB:RB
| mov CARG3d, RD
| mov L:RB, L:CARG1d
|.else
| mov ARG2, TAB:RB
| mov L:RB, SAVE_L
| mov L:RB->base, BASE
| mov ARG3, RD
| mov ARG1, L:RB
|.endif
| mov SAVE_PC, PC
| call extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
| mov BASE, L:RB->base
| movzx RA, PC_RA // Restore RA.
| jmp <1 // Retry.
|
|7: // Possible table write barrier for any value. Skip valiswhite check.
| barrierback TAB:RB, RD
| jmp <2
break;
/* -- Calls and vararg handling ----------------------------------------- */
case BC_CALL: case BC_CALLM:
| ins_A_C // RA = base, (RB = nresults+1,) RC = nargs+1 | extra_nargs
if (op == BC_CALLM) {
| add NARGS:RD, MULTRES
}
| cmp dword [BASE+RA*8+4], LJ_TFUNC
| mov LFUNC:RB, [BASE+RA*8]
| jne ->vmeta_call_ra
| lea BASE, [BASE+RA*8+8]
| ins_call
break;
case BC_CALLMT:
| ins_AD // RA = base, RD = extra_nargs
| add NARGS:RD, MULTRES
| // Fall through. Assumes BC_CALLT follows and ins_AD is a no-op.
break;
case BC_CALLT:
| ins_AD // RA = base, RD = nargs+1
| lea RA, [BASE+RA*8+8]
| mov KBASE, BASE // Use KBASE for move + vmeta_call hint.
| mov LFUNC:RB, [RA-8]
| cmp dword [RA-4], LJ_TFUNC
| jne ->vmeta_call
|->BC_CALLT_Z:
| mov PC, [BASE-4]
| test PC, FRAME_TYPE
| jnz >7
|1:
| mov [BASE-8], LFUNC:RB // Copy function down, reloaded below.
| mov MULTRES, NARGS:RD
| sub NARGS:RD, 1
| jz >3
|2: // Move args down.
|.if X64
| mov RBa, [RA]
| add RA, 8
| mov [KBASE], RBa
|.else
| mov RB, [RA]
| mov [KBASE], RB
| mov RB, [RA+4]
| add RA, 8
| mov [KBASE+4], RB
|.endif
| add KBASE, 8
| sub NARGS:RD, 1
| jnz <2
|
| mov LFUNC:RB, [BASE-8]
|3:
| mov NARGS:RD, MULTRES
| cmp byte LFUNC:RB->ffid, 1 // (> FF_C) Calling a fast function?
| ja >5
|4:
| ins_callt
|
|5: // Tailcall to a fast function.
| test PC, FRAME_TYPE // Lua frame below?
| jnz <4
| movzx RA, PC_RA
| not RAa
| mov LFUNC:KBASE, [BASE+RA*8-8] // Need to prepare KBASE.
| mov KBASE, LFUNC:KBASE->pc
| mov KBASE, [KBASE+PC2PROTO(k)]
| jmp <4
|
|7: // Tailcall from a vararg function.
| sub PC, FRAME_VARG
| test PC, FRAME_TYPEP
| jnz >8 // Vararg frame below?
| sub BASE, PC // Need to relocate BASE/KBASE down.
| mov KBASE, BASE
| mov PC, [BASE-4]
| jmp <1
|8:
| add PC, FRAME_VARG
| jmp <1
break;
case BC_ITERC:
| ins_A // RA = base, (RB = nresults+1,) RC = nargs+1 (2+1)
| lea RA, [BASE+RA*8+8] // fb = base+1
|.if X64
| mov RBa, [RA-24] // Copy state. fb[0] = fb[-3].
| mov RCa, [RA-16] // Copy control var. fb[1] = fb[-2].
| mov [RA], RBa
| mov [RA+8], RCa
|.else
| mov RB, [RA-24] // Copy state. fb[0] = fb[-3].
| mov RC, [RA-20]
| mov [RA], RB
| mov [RA+4], RC
| mov RB, [RA-16] // Copy control var. fb[1] = fb[-2].
| mov RC, [RA-12]
| mov [RA+8], RB
| mov [RA+12], RC
|.endif
| mov LFUNC:RB, [RA-32] // Copy callable. fb[-1] = fb[-4]
| mov RC, [RA-28]
| mov [RA-8], LFUNC:RB
| mov [RA-4], RC
| cmp RC, LJ_TFUNC // Handle like a regular 2-arg call.
| mov NARGS:RD, 2+1
| jne ->vmeta_call
| mov BASE, RA
| ins_call
break;
case BC_ITERN:
|.if JIT
| hotloop RB
|.endif
|->vm_IITERN:
| ins_A // RA = base, (RB = nresults+1, RC = nargs+1 (2+1))
| mov TMP1, KBASE // Need two more free registers.
| mov TMP2, DISPATCH
| mov TAB:RB, [BASE+RA*8-16]
| mov RC, [BASE+RA*8-8] // Get index from control var.
| mov DISPATCH, TAB:RB->asize
| add PC, 4
| mov KBASE, TAB:RB->array
|1: // Traverse array part.
| cmp RC, DISPATCH; jae >5 // Index points after array part?
| cmp dword [KBASE+RC*8+4], LJ_TNIL; je >4
|.if DUALNUM
| mov dword [BASE+RA*8+4], LJ_TISNUM
| mov dword [BASE+RA*8], RC
|.else
| cvtsi2sd xmm0, RC
|.endif
| // Copy array slot to returned value.
|.if X64
| mov RBa, [KBASE+RC*8]
| mov [BASE+RA*8+8], RBa
|.else
| mov RB, [KBASE+RC*8+4]
| mov [BASE+RA*8+12], RB
| mov RB, [KBASE+RC*8]
| mov [BASE+RA*8+8], RB
|.endif
| add RC, 1
| // Return array index as a numeric key.
|.if DUALNUM
| // See above.
|.else
| movsd qword [BASE+RA*8], xmm0
|.endif
| mov [BASE+RA*8-8], RC // Update control var.
|2:
| movzx RD, PC_RD // Get target from ITERL.
| branchPC RD
|3:
| mov DISPATCH, TMP2
| mov KBASE, TMP1
| ins_next
|
|4: // Skip holes in array part.
| add RC, 1
| jmp <1
|
|5: // Traverse hash part.
| sub RC, DISPATCH
|6:
| cmp RC, TAB:RB->hmask; ja <3 // End of iteration? Branch to ITERL+1.
| imul KBASE, RC, #NODE
| add NODE:KBASE, TAB:RB->node
| cmp dword NODE:KBASE->val.it, LJ_TNIL; je >7
| lea DISPATCH, [RC+DISPATCH+1]
| // Copy key and value from hash slot.
|.if X64
| mov RBa, NODE:KBASE->key
| mov RCa, NODE:KBASE->val
| mov [BASE+RA*8], RBa
| mov [BASE+RA*8+8], RCa
|.else
| mov RB, NODE:KBASE->key.gcr
| mov RC, NODE:KBASE->key.it
| mov [BASE+RA*8], RB
| mov [BASE+RA*8+4], RC
| mov RB, NODE:KBASE->val.gcr
| mov RC, NODE:KBASE->val.it
| mov [BASE+RA*8+8], RB
| mov [BASE+RA*8+12], RC
|.endif
| mov [BASE+RA*8-8], DISPATCH
| jmp <2
|
|7: // Skip holes in hash part.
| add RC, 1
| jmp <6
break;
case BC_ISNEXT:
| ins_AD // RA = base, RD = target (points to ITERN)
| cmp dword [BASE+RA*8-20], LJ_TFUNC; jne >5
| mov CFUNC:RB, [BASE+RA*8-24]
| cmp dword [BASE+RA*8-12], LJ_TTAB; jne >5
| cmp dword [BASE+RA*8-4], LJ_TNIL; jne >5
| cmp byte CFUNC:RB->ffid, FF_next_N; jne >5
| branchPC RD
| mov dword [BASE+RA*8-8], 0 // Initialize control var.
| mov dword [BASE+RA*8-4], LJ_KEYINDEX
|1:
| ins_next
|5: // Despecialize bytecode if any of the checks fail.
| mov PC_OP, BC_JMP
| branchPC RD
|.if JIT
| cmp byte [PC], BC_ITERN
| jne >6
|.endif
| mov byte [PC], BC_ITERC
| jmp <1
|.if JIT
|6: // Unpatch JLOOP.
| mov RA, [DISPATCH+DISPATCH_J(trace)]
| movzx RC, word [PC+2]
| mov TRACE:RA, [RA+RC*4]
| mov eax, TRACE:RA->startins
| mov al, BC_ITERC
| mov dword [PC], eax
| jmp <1
|.endif
break;
case BC_VARG:
| ins_ABC // RA = base, RB = nresults+1, RC = numparams
| mov TMP1, KBASE // Need one more free register.
| lea KBASE, [BASE+RC*8+(8+FRAME_VARG)]
| lea RA, [BASE+RA*8]
| sub KBASE, [BASE-4]
| // Note: KBASE may now be even _above_ BASE if nargs was < numparams.
| test RB, RB
| jz >5 // Copy all varargs?
| lea RB, [RA+RB*8-8]
| cmp KBASE, BASE // No vararg slots?
| jnb >2
|1: // Copy vararg slots to destination slots.
|.if X64
| mov RCa, [KBASE-8]
| add KBASE, 8
| mov [RA], RCa
|.else
| mov RC, [KBASE-8]
| mov [RA], RC
| mov RC, [KBASE-4]
| add KBASE, 8
| mov [RA+4], RC
|.endif
| add RA, 8
| cmp RA, RB // All destination slots filled?
| jnb >3
| cmp KBASE, BASE // No more vararg slots?
| jb <1
|2: // Fill up remainder with nil.
| mov dword [RA+4], LJ_TNIL
| add RA, 8
| cmp RA, RB
| jb <2
|3:
| mov KBASE, TMP1
| ins_next
|
|5: // Copy all varargs.
| mov MULTRES, 1 // MULTRES = 0+1
| mov RC, BASE
| sub RC, KBASE
| jbe <3 // No vararg slots?
| mov RB, RC
| shr RB, 3
| add RB, 1
| mov MULTRES, RB // MULTRES = #varargs+1
| mov L:RB, SAVE_L
| add RC, RA
| cmp RC, L:RB->maxstack
| ja >7 // Need to grow stack?
|6: // Copy all vararg slots.
|.if X64
| mov RCa, [KBASE-8]
| add KBASE, 8
| mov [RA], RCa
|.else
| mov RC, [KBASE-8]
| mov [RA], RC
| mov RC, [KBASE-4]
| add KBASE, 8
| mov [RA+4], RC
|.endif
| add RA, 8
| cmp KBASE, BASE // No more vararg slots?
| jb <6
| jmp <3
|
|7: // Grow stack for varargs.
| mov L:RB->base, BASE
| mov L:RB->top, RA
| mov SAVE_PC, PC
| sub KBASE, BASE // Need delta, because BASE may change.
| mov FCARG2, MULTRES
| sub FCARG2, 1
| mov FCARG1, L:RB
| call extern lj_state_growstack@8 // (lua_State *L, int n)
| mov BASE, L:RB->base
| mov RA, L:RB->top
| add KBASE, BASE
| jmp <6
break;
/* -- Returns ----------------------------------------------------------- */
case BC_RETM:
| ins_AD // RA = results, RD = extra_nresults
| add RD, MULTRES // MULTRES >=1, so RD >=1.
| // Fall through. Assumes BC_RET follows and ins_AD is a no-op.
break;
case BC_RET: case BC_RET0: case BC_RET1:
| ins_AD // RA = results, RD = nresults+1
if (op != BC_RET0) {
| shl RA, 3
}
|1:
| mov PC, [BASE-4]
| mov MULTRES, RD // Save nresults+1.
| test PC, FRAME_TYPE // Check frame type marker.
| jnz >7 // Not returning to a fixarg Lua func?
switch (op) {
case BC_RET:
|->BC_RET_Z:
| mov KBASE, BASE // Use KBASE for result move.
| sub RD, 1
| jz >3
|2: // Move results down.
|.if X64
| mov RBa, [KBASE+RA]
| mov [KBASE-8], RBa
|.else
| mov RB, [KBASE+RA]
| mov [KBASE-8], RB
| mov RB, [KBASE+RA+4]
| mov [KBASE-4], RB
|.endif
| add KBASE, 8
| sub RD, 1
| jnz <2
|3:
| mov RD, MULTRES // Note: MULTRES may be >255.
| movzx RB, PC_RB // So cannot compare with RDL!
|5:
| cmp RB, RD // More results expected?
| ja >6
break;
case BC_RET1:
|.if X64
| mov RBa, [BASE+RA]
| mov [BASE-8], RBa
|.else
| mov RB, [BASE+RA+4]
| mov [BASE-4], RB
| mov RB, [BASE+RA]
| mov [BASE-8], RB
|.endif
/* fallthrough */
case BC_RET0:
|5:
| cmp PC_RB, RDL // More results expected?
| ja >6
default:
break;
}
| movzx RA, PC_RA
| not RAa // Note: ~RA = -(RA+1)
| lea BASE, [BASE+RA*8] // base = base - (RA+1)*8
| mov LFUNC:KBASE, [BASE-8]
| mov KBASE, LFUNC:KBASE->pc
| mov KBASE, [KBASE+PC2PROTO(k)]
| ins_next
|
|6: // Fill up results with nil.
if (op == BC_RET) {
| mov dword [KBASE-4], LJ_TNIL // Note: relies on shifted base.
| add KBASE, 8
} else {
| mov dword [BASE+RD*8-12], LJ_TNIL
}
| add RD, 1
| jmp <5
|
|7: // Non-standard return case.
| lea RB, [PC-FRAME_VARG]
| test RB, FRAME_TYPEP
| jnz ->vm_return
| // Return from vararg function: relocate BASE down and RA up.
| sub BASE, RB
if (op != BC_RET0) {
| add RA, RB
}
| jmp <1
break;
/* -- Loops and branches ------------------------------------------------ */
|.define FOR_IDX, [RA]; .define FOR_TIDX, dword [RA+4]
|.define FOR_STOP, [RA+8]; .define FOR_TSTOP, dword [RA+12]
|.define FOR_STEP, [RA+16]; .define FOR_TSTEP, dword [RA+20]
|.define FOR_EXT, [RA+24]; .define FOR_TEXT, dword [RA+28]
case BC_FORL:
|.if JIT
| hotloop RB
|.endif
| // Fall through. Assumes BC_IFORL follows and ins_AJ is a no-op.
break;
case BC_JFORI:
case BC_JFORL:
#if !LJ_HASJIT
break;
#endif
case BC_FORI:
case BC_IFORL:
vk = (op == BC_IFORL || op == BC_JFORL);
| ins_AJ // RA = base, RD = target (after end of loop or start of loop)
| lea RA, [BASE+RA*8]
if (LJ_DUALNUM) {
| cmp FOR_TIDX, LJ_TISNUM; jne >9
if (!vk) {
| cmp FOR_TSTOP, LJ_TISNUM; jne ->vmeta_for
| cmp FOR_TSTEP, LJ_TISNUM; jne ->vmeta_for
| mov RB, dword FOR_IDX
| cmp dword FOR_STEP, 0; jl >5
} else {
#ifdef LUA_USE_ASSERT
| cmp FOR_TSTOP, LJ_TISNUM; jne ->assert_bad_for_arg_type
| cmp FOR_TSTEP, LJ_TISNUM; jne ->assert_bad_for_arg_type
#endif
| mov RB, dword FOR_STEP
| test RB, RB; js >5
| add RB, dword FOR_IDX; jo >1
| mov dword FOR_IDX, RB
}
| cmp RB, dword FOR_STOP
| mov FOR_TEXT, LJ_TISNUM
| mov dword FOR_EXT, RB
if (op == BC_FORI) {
| jle >7
|1:
|6:
| branchPC RD
} else if (op == BC_JFORI) {
| branchPC RD
| movzx RD, PC_RD
| jle =>BC_JLOOP
|1:
|6:
} else if (op == BC_IFORL) {
| jg >7
|6:
| branchPC RD
|1:
} else {
| jle =>BC_JLOOP
|1:
|6:
}
|7:
| ins_next
|
|5: // Invert check for negative step.
if (vk) {
| add RB, dword FOR_IDX; jo <1
| mov dword FOR_IDX, RB
}
| cmp RB, dword FOR_STOP
| mov FOR_TEXT, LJ_TISNUM
| mov dword FOR_EXT, RB
if (op == BC_FORI) {
| jge <7
} else if (op == BC_JFORI) {
| branchPC RD
| movzx RD, PC_RD
| jge =>BC_JLOOP
} else if (op == BC_IFORL) {
| jl <7
} else {
| jge =>BC_JLOOP
}
| jmp <6
|9: // Fallback to FP variant.
} else if (!vk) {
| cmp FOR_TIDX, LJ_TISNUM
}
if (!vk) {
| jae ->vmeta_for
| cmp FOR_TSTOP, LJ_TISNUM; jae ->vmeta_for
} else {
#ifdef LUA_USE_ASSERT
| cmp FOR_TSTOP, LJ_TISNUM; jae ->assert_bad_for_arg_type
| cmp FOR_TSTEP, LJ_TISNUM; jae ->assert_bad_for_arg_type
#endif
}
| mov RB, FOR_TSTEP // Load type/hiword of for step.
if (!vk) {
| cmp RB, LJ_TISNUM; jae ->vmeta_for
}
| movsd xmm0, qword FOR_IDX
| movsd xmm1, qword FOR_STOP
if (vk) {
| addsd xmm0, qword FOR_STEP
| movsd qword FOR_IDX, xmm0
| test RB, RB; js >3
} else {
| jl >3
}
| ucomisd xmm1, xmm0
|1:
| movsd qword FOR_EXT, xmm0
if (op == BC_FORI) {
|.if DUALNUM
| jnb <7
|.else
| jnb >2
| branchPC RD
|.endif
} else if (op == BC_JFORI) {
| branchPC RD
| movzx RD, PC_RD
| jnb =>BC_JLOOP
} else if (op == BC_IFORL) {
|.if DUALNUM
| jb <7
|.else
| jb >2
| branchPC RD
|.endif
} else {
| jnb =>BC_JLOOP
}
|.if DUALNUM
| jmp <6
|.else
|2:
| ins_next
|.endif
|
|3: // Invert comparison if step is negative.
| ucomisd xmm0, xmm1
| jmp <1
break;
case BC_ITERL:
|.if JIT
| hotloop RB
|.endif
| // Fall through. Assumes BC_IITERL follows and ins_AJ is a no-op.
break;
case BC_JITERL:
#if !LJ_HASJIT
break;
#endif
case BC_IITERL:
| ins_AJ // RA = base, RD = target
| lea RA, [BASE+RA*8]
| mov RB, [RA+4]
| cmp RB, LJ_TNIL; je >1 // Stop if iterator returned nil.
if (op == BC_JITERL) {
| mov [RA-4], RB
| mov RB, [RA]
| mov [RA-8], RB
| jmp =>BC_JLOOP
} else {
| branchPC RD // Otherwise save control var + branch.
| mov RD, [RA]
| mov [RA-4], RB
| mov [RA-8], RD
}
|1:
| ins_next
break;
case BC_LOOP:
| ins_A // RA = base, RD = target (loop extent)
| // Note: RA/RD is only used by trace recorder to determine scope/extent
| // This opcode does NOT jump, it's only purpose is to detect a hot loop.
|.if JIT
| hotloop RB
|.endif
| // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op.
break;
case BC_ILOOP:
| ins_A // RA = base, RD = target (loop extent)
| ins_next
break;
case BC_JLOOP:
|.if JIT
| ins_AD // RA = base (ignored), RD = traceno
| mov RA, [DISPATCH+DISPATCH_J(trace)]
| mov TRACE:RD, [RA+RD*4]
| mov RDa, TRACE:RD->mcode
| mov L:RB, SAVE_L
| mov [DISPATCH+DISPATCH_GL(jit_base)], BASE
| mov [DISPATCH+DISPATCH_GL(tmpbuf.L)], L:RB
| // Save additional callee-save registers only used in compiled code.
|.if X64WIN
| mov TMPQ, r12
| mov TMPa, r13
| mov CSAVE_4, r14
| mov CSAVE_3, r15
| mov RAa, rsp
| sub rsp, 9*16+4*8
| movdqa [RAa], xmm6
| movdqa [RAa-1*16], xmm7
| movdqa [RAa-2*16], xmm8
| movdqa [RAa-3*16], xmm9
| movdqa [RAa-4*16], xmm10
| movdqa [RAa-5*16], xmm11
| movdqa [RAa-6*16], xmm12
| movdqa [RAa-7*16], xmm13
| movdqa [RAa-8*16], xmm14
| movdqa [RAa-9*16], xmm15
|.elif X64
| mov TMPQ, r12
| mov TMPa, r13
| sub rsp, 16
|.endif
| jmp RDa
|.endif
break;
case BC_JMP:
| ins_AJ // RA = unused, RD = target
| branchPC RD
| ins_next
break;
/* -- Function headers -------------------------------------------------- */
/*
** Reminder: A function may be called with func/args above L->maxstack,
** i.e. occupying EXTRA_STACK slots. And vmeta_call may add one extra slot,
** too. This means all FUNC* ops (including fast functions) must check
** for stack overflow _before_ adding more slots!
*/
case BC_FUNCF:
|.if JIT
| hotcall RB
|.endif
case BC_FUNCV: /* NYI: compiled vararg functions. */
| // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow and ins_AD is a no-op.
break;
case BC_JFUNCF:
#if !LJ_HASJIT
break;
#endif
case BC_IFUNCF:
| ins_AD // BASE = new base, RA = framesize, RD = nargs+1
| mov KBASE, [PC-4+PC2PROTO(k)]
| mov L:RB, SAVE_L
| lea RA, [BASE+RA*8] // Top of frame.
| cmp RA, L:RB->maxstack
| ja ->vm_growstack_f
| movzx RA, byte [PC-4+PC2PROTO(numparams)]
| cmp NARGS:RD, RA // Check for missing parameters.
| jbe >3
|2:
if (op == BC_JFUNCF) {
| movzx RD, PC_RD
| jmp =>BC_JLOOP
} else {
| ins_next
}
|
|3: // Clear missing parameters.
| mov dword [BASE+NARGS:RD*8-4], LJ_TNIL
| add NARGS:RD, 1
| cmp NARGS:RD, RA
| jbe <3
| jmp <2
break;
case BC_JFUNCV:
#if !LJ_HASJIT
break;
#endif
| int3 // NYI: compiled vararg functions
break; /* NYI: compiled vararg functions. */
case BC_IFUNCV:
| ins_AD // BASE = new base, RA = framesize, RD = nargs+1
| lea RB, [NARGS:RD*8+FRAME_VARG]
| lea RD, [BASE+NARGS:RD*8]
| mov LFUNC:KBASE, [BASE-8]
| mov [RD-4], RB // Store delta + FRAME_VARG.
| mov [RD-8], LFUNC:KBASE // Store copy of LFUNC.
| mov L:RB, SAVE_L
| lea RA, [RD+RA*8]
| cmp RA, L:RB->maxstack
| ja ->vm_growstack_v // Need to grow stack.
| mov RA, BASE
| mov BASE, RD
| movzx RB, byte [PC-4+PC2PROTO(numparams)]
| test RB, RB
| jz >2
|1: // Copy fixarg slots up to new frame.
| add RA, 8
| cmp RA, BASE
| jnb >3 // Less args than parameters?
| mov KBASE, [RA-8]
| mov [RD], KBASE
| mov KBASE, [RA-4]
| mov [RD+4], KBASE
| add RD, 8
| mov dword [RA-4], LJ_TNIL // Clear old fixarg slot (help the GC).
| sub RB, 1
| jnz <1
|2:
if (op == BC_JFUNCV) {
| movzx RD, PC_RD
| jmp =>BC_JLOOP
} else {
| mov KBASE, [PC-4+PC2PROTO(k)]
| ins_next
}
|
|3: // Clear missing parameters.
| mov dword [RD+4], LJ_TNIL
| add RD, 8
| sub RB, 1
| jnz <3
| jmp <2
break;
case BC_FUNCC:
case BC_FUNCCW:
| ins_AD // BASE = new base, RA = ins RA|RD (unused), RD = nargs+1
| mov CFUNC:RB, [BASE-8]
| mov KBASEa, CFUNC:RB->f
| mov L:RB, SAVE_L
| lea RD, [BASE+NARGS:RD*8-8]
| mov L:RB->base, BASE
| lea RA, [RD+8*LUA_MINSTACK]
| cmp RA, L:RB->maxstack
| mov L:RB->top, RD
if (op == BC_FUNCC) {
|.if X64
| mov CARG1d, L:RB // Caveat: CARG1d may be RA.
|.else
| mov ARG1, L:RB
|.endif
} else {
|.if X64
| mov CARG2, KBASEa
| mov CARG1d, L:RB // Caveat: CARG1d may be RA.
|.else
| mov ARG2, KBASEa
| mov ARG1, L:RB
|.endif
}
| ja ->vm_growstack_c // Need to grow stack.
| set_vmstate C
if (op == BC_FUNCC) {
| call KBASEa // (lua_State *L)
} else {
| // (lua_State *L, lua_CFunction f)
| call aword [DISPATCH+DISPATCH_GL(wrapf)]
}
| // nresults returned in eax (RD).
| mov BASE, L:RB->base
| mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
| set_vmstate INTERP
| lea RA, [BASE+RD*8]
| neg RA
| add RA, L:RB->top // RA = (L->top-(L->base+nresults))*8
| mov PC, [BASE-4] // Fetch PC of caller.
| jmp ->vm_returnc
break;
/* ---------------------------------------------------------------------- */
default:
fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
exit(2);
break;
}
}
static int build_backend(BuildCtx *ctx)
{
int op;
dasm_growpc(Dst, BC__MAX);
build_subroutines(ctx);
|.code_op
for (op = 0; op < BC__MAX; op++)
build_ins(ctx, (BCOp)op, op);
return BC__MAX;
}
/* Emit pseudo frame-info for all assembler functions. */
static void emit_asm_debug(BuildCtx *ctx)
{
int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code);
#if LJ_64
#define SZPTR "8"
#define BSZPTR "3"
#define REG_SP "0x7"
#define REG_RA "0x10"
#else
#define SZPTR "4"
#define BSZPTR "2"
#define REG_SP "0x4"
#define REG_RA "0x8"
#endif
switch (ctx->mode) {
case BUILD_elfasm:
fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n");
fprintf(ctx->fp,
".Lframe0:\n"
"\t.long .LECIE0-.LSCIE0\n"
".LSCIE0:\n"
"\t.long 0xffffffff\n"
"\t.byte 0x1\n"
"\t.string \"\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -" SZPTR "\n"
"\t.byte " REG_RA "\n"
"\t.byte 0xc\n\t.uleb128 " REG_SP "\n\t.uleb128 " SZPTR "\n"
"\t.byte 0x80+" REG_RA "\n\t.uleb128 0x1\n"
"\t.align " SZPTR "\n"
".LECIE0:\n\n");
fprintf(ctx->fp,
".LSFDE0:\n"
"\t.long .LEFDE0-.LASFDE0\n"
".LASFDE0:\n"
"\t.long .Lframe0\n"
#if LJ_64
"\t.quad .Lbegin\n"
"\t.quad %d\n"
"\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
"\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
"\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */
"\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */
#if LJ_NO_UNWIND
"\t.byte 0x8d\n\t.uleb128 0x6\n" /* offset r13 */
"\t.byte 0x8c\n\t.uleb128 0x7\n" /* offset r12 */
#endif
#else
"\t.long .Lbegin\n"
"\t.long %d\n"
"\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
"\t.byte 0x85\n\t.uleb128 0x2\n" /* offset ebp */
"\t.byte 0x87\n\t.uleb128 0x3\n" /* offset edi */
"\t.byte 0x86\n\t.uleb128 0x4\n" /* offset esi */
"\t.byte 0x83\n\t.uleb128 0x5\n" /* offset ebx */
#endif
"\t.align " SZPTR "\n"
".LEFDE0:\n\n", fcofs, CFRAME_SIZE);
#if LJ_HASFFI
fprintf(ctx->fp,
".LSFDE1:\n"
"\t.long .LEFDE1-.LASFDE1\n"
".LASFDE1:\n"
"\t.long .Lframe0\n"
#if LJ_64
"\t.quad lj_vm_ffi_call\n"
"\t.quad %d\n"
"\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */
"\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
"\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
#else
"\t.long lj_vm_ffi_call\n"
"\t.long %d\n"
"\t.byte 0xe\n\t.uleb128 8\n" /* def_cfa_offset */
"\t.byte 0x85\n\t.uleb128 0x2\n" /* offset ebp */
"\t.byte 0xd\n\t.uleb128 0x5\n" /* def_cfa_register ebp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset ebx */
#endif
"\t.align " SZPTR "\n"
".LEFDE1:\n\n", (int)ctx->codesz - fcofs);
#endif
#if !LJ_NO_UNWIND
#if LJ_TARGET_SOLARIS
#if LJ_64
fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@unwind\n");
#else
fprintf(ctx->fp, "\t.section .eh_frame,\"aw\",@progbits\n");
#endif
#else
fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n");
#endif
fprintf(ctx->fp,
".Lframe1:\n"
"\t.long .LECIE1-.LSCIE1\n"
".LSCIE1:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.string \"zPR\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -" SZPTR "\n"
"\t.byte " REG_RA "\n"
"\t.uleb128 6\n" /* augmentation length */
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.long lj_err_unwind_dwarf-.\n"
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.uleb128 " REG_SP "\n\t.uleb128 " SZPTR "\n"
"\t.byte 0x80+" REG_RA "\n\t.uleb128 0x1\n"
"\t.align " SZPTR "\n"
".LECIE1:\n\n");
fprintf(ctx->fp,
".LSFDE2:\n"
"\t.long .LEFDE2-.LASFDE2\n"
".LASFDE2:\n"
"\t.long .LASFDE2-.Lframe1\n"
"\t.long .Lbegin-.\n"
"\t.long %d\n"
"\t.uleb128 0\n" /* augmentation length */
"\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
#if LJ_64
"\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
"\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */
"\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */
#else
"\t.byte 0x85\n\t.uleb128 0x2\n" /* offset ebp */
"\t.byte 0x87\n\t.uleb128 0x3\n" /* offset edi */
"\t.byte 0x86\n\t.uleb128 0x4\n" /* offset esi */
"\t.byte 0x83\n\t.uleb128 0x5\n" /* offset ebx */
#endif
"\t.align " SZPTR "\n"
".LEFDE2:\n\n", fcofs, CFRAME_SIZE);
#if LJ_HASFFI
fprintf(ctx->fp,
".Lframe2:\n"
"\t.long .LECIE2-.LSCIE2\n"
".LSCIE2:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.string \"zR\"\n"
"\t.uleb128 0x1\n"
"\t.sleb128 -" SZPTR "\n"
"\t.byte " REG_RA "\n"
"\t.uleb128 1\n" /* augmentation length */
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.uleb128 " REG_SP "\n\t.uleb128 " SZPTR "\n"
"\t.byte 0x80+" REG_RA "\n\t.uleb128 0x1\n"
"\t.align " SZPTR "\n"
".LECIE2:\n\n");
fprintf(ctx->fp,
".LSFDE3:\n"
"\t.long .LEFDE3-.LASFDE3\n"
".LASFDE3:\n"
"\t.long .LASFDE3-.Lframe2\n"
"\t.long lj_vm_ffi_call-.\n"
"\t.long %d\n"
"\t.uleb128 0\n" /* augmentation length */
#if LJ_64
"\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */
"\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
"\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
#else
"\t.byte 0xe\n\t.uleb128 8\n" /* def_cfa_offset */
"\t.byte 0x85\n\t.uleb128 0x2\n" /* offset ebp */
"\t.byte 0xd\n\t.uleb128 0x5\n" /* def_cfa_register ebp */
"\t.byte 0x83\n\t.uleb128 0x3\n" /* offset ebx */
#endif
"\t.align " SZPTR "\n"
".LEFDE3:\n\n", (int)ctx->codesz - fcofs);
#endif
#endif
break;
#if !LJ_NO_UNWIND
/* Mental note: never let Apple design an assembler.
** Or a linker. Or a plastic case. But I digress.
*/
case BUILD_machasm: {
#if LJ_HASFFI
int fcsize = 0;
#endif
int i;
fprintf(ctx->fp, "\t.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support\n");
fprintf(ctx->fp,
"EH_frame1:\n"
"\t.set L$set$x,LECIEX-LSCIEX\n"
"\t.long L$set$x\n"
"LSCIEX:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.ascii \"zPR\\0\"\n"
"\t.byte 0x1\n"
"\t.byte 128-" SZPTR "\n"
"\t.byte " REG_RA "\n"
"\t.byte 6\n" /* augmentation length */
"\t.byte 0x9b\n" /* indirect|pcrel|sdata4 */
#if LJ_64
"\t.long _lj_err_unwind_dwarf+4@GOTPCREL\n"
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.byte " REG_SP "\n\t.byte " SZPTR "\n"
#else
"\t.long L_lj_err_unwind_dwarf$non_lazy_ptr-.\n"
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.byte 0x5\n\t.byte 0x4\n" /* esp=5 on 32 bit MACH-O. */
#endif
"\t.byte 0x80+" REG_RA "\n\t.byte 0x1\n"
"\t.align " BSZPTR "\n"
"LECIEX:\n\n");
for (i = 0; i < ctx->nsym; i++) {
const char *name = ctx->sym[i].name;
int32_t size = ctx->sym[i+1].ofs - ctx->sym[i].ofs;
if (size == 0) continue;
#if LJ_HASFFI
if (!strcmp(name, "_lj_vm_ffi_call")) { fcsize = size; continue; }
#endif
fprintf(ctx->fp,
"%s.eh:\n"
"LSFDE%d:\n"
"\t.set L$set$%d,LEFDE%d-LASFDE%d\n"
"\t.long L$set$%d\n"
"LASFDE%d:\n"
"\t.long LASFDE%d-EH_frame1\n"
"\t.long %s-.\n"
"\t.long %d\n"
"\t.byte 0\n" /* augmentation length */
"\t.byte 0xe\n\t.byte %d\n" /* def_cfa_offset */
#if LJ_64
"\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */
"\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */
"\t.byte 0x8f\n\t.byte 0x4\n" /* offset r15 */
"\t.byte 0x8e\n\t.byte 0x5\n" /* offset r14 */
#else
"\t.byte 0x84\n\t.byte 0x2\n" /* offset ebp (4 for MACH-O)*/
"\t.byte 0x87\n\t.byte 0x3\n" /* offset edi */
"\t.byte 0x86\n\t.byte 0x4\n" /* offset esi */
"\t.byte 0x83\n\t.byte 0x5\n" /* offset ebx */
#endif
"\t.align " BSZPTR "\n"
"LEFDE%d:\n\n",
name, i, i, i, i, i, i, i, name, size, CFRAME_SIZE, i);
}
#if LJ_HASFFI
if (fcsize) {
fprintf(ctx->fp,
"EH_frame2:\n"
"\t.set L$set$y,LECIEY-LSCIEY\n"
"\t.long L$set$y\n"
"LSCIEY:\n"
"\t.long 0\n"
"\t.byte 0x1\n"
"\t.ascii \"zR\\0\"\n"
"\t.byte 0x1\n"
"\t.byte 128-" SZPTR "\n"
"\t.byte " REG_RA "\n"
"\t.byte 1\n" /* augmentation length */
#if LJ_64
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.byte " REG_SP "\n\t.byte " SZPTR "\n"
#else
"\t.byte 0x1b\n" /* pcrel|sdata4 */
"\t.byte 0xc\n\t.byte 0x5\n\t.byte 0x4\n" /* esp=5 on 32 bit MACH. */
#endif
"\t.byte 0x80+" REG_RA "\n\t.byte 0x1\n"
"\t.align " BSZPTR "\n"
"LECIEY:\n\n");
fprintf(ctx->fp,
"_lj_vm_ffi_call.eh:\n"
"LSFDEY:\n"
"\t.set L$set$yy,LEFDEY-LASFDEY\n"
"\t.long L$set$yy\n"
"LASFDEY:\n"
"\t.long LASFDEY-EH_frame2\n"
"\t.long _lj_vm_ffi_call-.\n"
"\t.long %d\n"
"\t.byte 0\n" /* augmentation length */
#if LJ_64
"\t.byte 0xe\n\t.byte 16\n" /* def_cfa_offset */
"\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */
"\t.byte 0xd\n\t.byte 0x6\n" /* def_cfa_register rbp */
"\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */
#else
"\t.byte 0xe\n\t.byte 8\n" /* def_cfa_offset */
"\t.byte 0x84\n\t.byte 0x2\n" /* offset ebp (4 for MACH-O)*/
"\t.byte 0xd\n\t.byte 0x4\n" /* def_cfa_register ebp */
"\t.byte 0x83\n\t.byte 0x3\n" /* offset ebx */
#endif
"\t.align " BSZPTR "\n"
"LEFDEY:\n\n", fcsize);
}
#endif
#if !LJ_64
fprintf(ctx->fp,
"\t.non_lazy_symbol_pointer\n"
"L_lj_err_unwind_dwarf$non_lazy_ptr:\n"
".indirect_symbol _lj_err_unwind_dwarf\n"
".long 0\n\n");
fprintf(ctx->fp, "\t.section __IMPORT,__jump_table,symbol_stubs,pure_instructions+self_modifying_code,5\n");
{
const char *const *xn;
for (xn = ctx->extnames; *xn; xn++)
if (strncmp(*xn, LABEL_PREFIX, sizeof(LABEL_PREFIX)-1))
fprintf(ctx->fp, "L_%s$stub:\n\t.indirect_symbol _%s\n\t.ascii \"\\364\\364\\364\\364\\364\"\n", *xn, *xn);
}
#endif
fprintf(ctx->fp, ".subsections_via_symbols\n");
}
break;
#endif
default: /* Difficult for other modes. */
break;
}
}
| xLua/build/luajit-2.1.0b3/src/vm_x86.dasc/0 | {
"file_path": "xLua/build/luajit-2.1.0b3/src/vm_x86.dasc",
"repo_id": "xLua",
"token_count": 79899
} | 2,129 |
/*=========================================================================*\
* Auxiliar routines for class hierarchy manipulation
* LuaSocket toolkit
\*=========================================================================*/
#include <string.h>
#include <stdio.h>
#include "auxiliar.h"
/*=========================================================================*\
* Exported functions
\*=========================================================================*/
/*-------------------------------------------------------------------------*\
* Initializes the module
\*-------------------------------------------------------------------------*/
int auxiliar_open(lua_State *L) {
(void) L;
return 0;
}
/*-------------------------------------------------------------------------*\
* Creates a new class with given methods
* Methods whose names start with __ are passed directly to the metatable.
\*-------------------------------------------------------------------------*/
void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func) {
luaL_newmetatable(L, classname); /* mt */
/* create __index table to place methods */
lua_pushstring(L, "__index"); /* mt,"__index" */
lua_newtable(L); /* mt,"__index",it */
/* put class name into class metatable */
lua_pushstring(L, "class"); /* mt,"__index",it,"class" */
lua_pushstring(L, classname); /* mt,"__index",it,"class",classname */
lua_rawset(L, -3); /* mt,"__index",it */
/* pass all methods that start with _ to the metatable, and all others
* to the index table */
for (; func->name; func++) { /* mt,"__index",it */
lua_pushstring(L, func->name);
lua_pushcfunction(L, func->func);
lua_rawset(L, func->name[0] == '_' ? -5: -3);
}
lua_rawset(L, -3); /* mt */
lua_pop(L, 1);
}
/*-------------------------------------------------------------------------*\
* Prints the value of a class in a nice way
\*-------------------------------------------------------------------------*/
int auxiliar_tostring(lua_State *L) {
char buf[32];
if (!lua_getmetatable(L, 1)) goto error;
lua_pushstring(L, "__index");
lua_gettable(L, -2);
if (!lua_istable(L, -1)) goto error;
lua_pushstring(L, "class");
lua_gettable(L, -2);
if (!lua_isstring(L, -1)) goto error;
sprintf(buf, "%p", lua_touserdata(L, 1));
lua_pushfstring(L, "%s: %s", lua_tostring(L, -1), buf);
return 1;
error:
lua_pushstring(L, "invalid object passed to 'auxiliar.c:__tostring'");
lua_error(L);
return 1;
}
/*-------------------------------------------------------------------------*\
* Insert class into group
\*-------------------------------------------------------------------------*/
void auxiliar_add2group(lua_State *L, const char *classname, const char *groupname) {
luaL_getmetatable(L, classname);
lua_pushstring(L, groupname);
lua_pushboolean(L, 1);
lua_rawset(L, -3);
lua_pop(L, 1);
}
/*-------------------------------------------------------------------------*\
* Make sure argument is a boolean
\*-------------------------------------------------------------------------*/
int auxiliar_checkboolean(lua_State *L, int objidx) {
if (!lua_isboolean(L, objidx))
auxiliar_typeerror(L, objidx, lua_typename(L, LUA_TBOOLEAN));
return lua_toboolean(L, objidx);
}
/*-------------------------------------------------------------------------*\
* Return userdata pointer if object belongs to a given class, abort with
* error otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) {
void *data = auxiliar_getclassudata(L, classname, objidx);
if (!data) {
char msg[45];
sprintf(msg, "%.35s expected", classname);
luaL_argerror(L, objidx, msg);
}
return data;
}
/*-------------------------------------------------------------------------*\
* Return userdata pointer if object belongs to a given group, abort with
* error otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) {
void *data = auxiliar_getgroupudata(L, groupname, objidx);
if (!data) {
char msg[45];
sprintf(msg, "%.35s expected", groupname);
luaL_argerror(L, objidx, msg);
}
return data;
}
/*-------------------------------------------------------------------------*\
* Set object class
\*-------------------------------------------------------------------------*/
void auxiliar_setclass(lua_State *L, const char *classname, int objidx) {
luaL_getmetatable(L, classname);
if (objidx < 0) objidx--;
lua_setmetatable(L, objidx);
}
/*-------------------------------------------------------------------------*\
* Get a userdata pointer if object belongs to a given group. Return NULL
* otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) {
if (!lua_getmetatable(L, objidx))
return NULL;
lua_pushstring(L, groupname);
lua_rawget(L, -2);
if (lua_isnil(L, -1)) {
lua_pop(L, 2);
return NULL;
} else {
lua_pop(L, 2);
return lua_touserdata(L, objidx);
}
}
/*-------------------------------------------------------------------------*\
* Get a userdata pointer if object belongs to a given class. Return NULL
* otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) {
return luaL_checkudata(L, objidx, classname);
}
/*-------------------------------------------------------------------------*\
* Throws error when argument does not have correct type.
* Used to be part of lauxlib in Lua 5.1, was dropped from 5.2.
\*-------------------------------------------------------------------------*/
int auxiliar_typeerror (lua_State *L, int narg, const char *tname) {
const char *msg = lua_pushfstring(L, "%s expected, got %s", tname,
luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
}
| xLua/build/luasocket/auxiliar.c/0 | {
"file_path": "xLua/build/luasocket/auxiliar.c",
"repo_id": "xLua",
"token_count": 1990
} | 2,130 |
/*=========================================================================*\
* Common option interface
* LuaSocket toolkit
\*=========================================================================*/
#include <string.h>
#include "lauxlib.h"
#include "auxiliar.h"
#include "options.h"
#include "inet.h"
/*=========================================================================*\
* Internal functions prototypes
\*=========================================================================*/
static int opt_setmembership(lua_State *L, p_socket ps, int level, int name);
static int opt_ip6_setmembership(lua_State *L, p_socket ps, int level, int name);
static int opt_setboolean(lua_State *L, p_socket ps, int level, int name);
static int opt_getboolean(lua_State *L, p_socket ps, int level, int name);
static int opt_setint(lua_State *L, p_socket ps, int level, int name);
static int opt_getint(lua_State *L, p_socket ps, int level, int name);
static int opt_set(lua_State *L, p_socket ps, int level, int name,
void *val, int len);
static int opt_get(lua_State *L, p_socket ps, int level, int name,
void *val, int* len);
/*=========================================================================*\
* Exported functions
\*=========================================================================*/
/*-------------------------------------------------------------------------*\
* Calls appropriate option handler
\*-------------------------------------------------------------------------*/
int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps)
{
const char *name = luaL_checkstring(L, 2); /* obj, name, ... */
while (opt->name && strcmp(name, opt->name))
opt++;
if (!opt->func) {
char msg[45];
sprintf(msg, "unsupported option `%.35s'", name);
luaL_argerror(L, 2, msg);
}
return opt->func(L, ps);
}
int opt_meth_getoption(lua_State *L, p_opt opt, p_socket ps)
{
const char *name = luaL_checkstring(L, 2); /* obj, name, ... */
while (opt->name && strcmp(name, opt->name))
opt++;
if (!opt->func) {
char msg[45];
sprintf(msg, "unsupported option `%.35s'", name);
luaL_argerror(L, 2, msg);
}
return opt->func(L, ps);
}
/* enables reuse of local address */
int opt_set_reuseaddr(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR);
}
int opt_get_reuseaddr(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, SOL_SOCKET, SO_REUSEADDR);
}
/* enables reuse of local port */
int opt_set_reuseport(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEPORT);
}
int opt_get_reuseport(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, SOL_SOCKET, SO_REUSEPORT);
}
/* disables the Naggle algorithm */
int opt_set_tcp_nodelay(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY);
}
int opt_get_tcp_nodelay(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, IPPROTO_TCP, TCP_NODELAY);
}
int opt_set_keepalive(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE);
}
int opt_get_keepalive(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE);
}
int opt_set_dontroute(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_DONTROUTE);
}
int opt_set_broadcast(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_BROADCAST);
}
int opt_set_ip6_unicast_hops(lua_State *L, p_socket ps)
{
return opt_setint(L, ps, IPPROTO_IPV6, IPV6_UNICAST_HOPS);
}
int opt_get_ip6_unicast_hops(lua_State *L, p_socket ps)
{
return opt_getint(L, ps, IPPROTO_IPV6, IPV6_UNICAST_HOPS);
}
int opt_set_ip6_multicast_hops(lua_State *L, p_socket ps)
{
return opt_setint(L, ps, IPPROTO_IPV6, IPV6_MULTICAST_HOPS);
}
int opt_get_ip6_multicast_hops(lua_State *L, p_socket ps)
{
return opt_getint(L, ps, IPPROTO_IPV6, IPV6_MULTICAST_HOPS);
}
int opt_set_ip_multicast_loop(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP);
}
int opt_get_ip_multicast_loop(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP);
}
int opt_set_ip6_multicast_loop(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, IPPROTO_IPV6, IPV6_MULTICAST_LOOP);
}
int opt_get_ip6_multicast_loop(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, IPPROTO_IPV6, IPV6_MULTICAST_LOOP);
}
int opt_set_linger(lua_State *L, p_socket ps)
{
struct linger li; /* obj, name, table */
if (!lua_istable(L, 3)) auxiliar_typeerror(L,3,lua_typename(L, LUA_TTABLE));
lua_pushstring(L, "on");
lua_gettable(L, 3);
if (!lua_isboolean(L, -1))
luaL_argerror(L, 3, "boolean 'on' field expected");
li.l_onoff = (u_short) lua_toboolean(L, -1);
lua_pushstring(L, "timeout");
lua_gettable(L, 3);
if (!lua_isnumber(L, -1))
luaL_argerror(L, 3, "number 'timeout' field expected");
li.l_linger = (u_short) lua_tonumber(L, -1);
return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li));
}
int opt_get_linger(lua_State *L, p_socket ps)
{
struct linger li; /* obj, name */
int len = sizeof(li);
int err = opt_get(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, &len);
if (err)
return err;
lua_newtable(L);
lua_pushboolean(L, li.l_onoff);
lua_setfield(L, -2, "on");
lua_pushinteger(L, li.l_linger);
lua_setfield(L, -2, "timeout");
return 1;
}
int opt_set_ip_multicast_ttl(lua_State *L, p_socket ps)
{
return opt_setint(L, ps, IPPROTO_IP, IP_MULTICAST_TTL);
}
int opt_set_ip_multicast_if(lua_State *L, p_socket ps)
{
const char *address = luaL_checkstring(L, 3); /* obj, name, ip */
struct in_addr val;
val.s_addr = htonl(INADDR_ANY);
if (strcmp(address, "*") && !inet_aton(address, &val))
luaL_argerror(L, 3, "ip expected");
return opt_set(L, ps, IPPROTO_IP, IP_MULTICAST_IF,
(char *) &val, sizeof(val));
}
int opt_get_ip_multicast_if(lua_State *L, p_socket ps)
{
struct in_addr val;
socklen_t len = sizeof(val);
if (getsockopt(*ps, IPPROTO_IP, IP_MULTICAST_IF, (char *) &val, &len) < 0) {
lua_pushnil(L);
lua_pushstring(L, "getsockopt failed");
return 2;
}
lua_pushstring(L, inet_ntoa(val));
return 1;
}
int opt_set_ip_add_membership(lua_State *L, p_socket ps)
{
return opt_setmembership(L, ps, IPPROTO_IP, IP_ADD_MEMBERSHIP);
}
int opt_set_ip_drop_membersip(lua_State *L, p_socket ps)
{
return opt_setmembership(L, ps, IPPROTO_IP, IP_DROP_MEMBERSHIP);
}
int opt_set_ip6_add_membership(lua_State *L, p_socket ps)
{
return opt_ip6_setmembership(L, ps, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP);
}
int opt_set_ip6_drop_membersip(lua_State *L, p_socket ps)
{
return opt_ip6_setmembership(L, ps, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP);
}
int opt_get_ip6_v6only(lua_State *L, p_socket ps)
{
return opt_getboolean(L, ps, IPPROTO_IPV6, IPV6_V6ONLY);
}
int opt_set_ip6_v6only(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, IPPROTO_IPV6, IPV6_V6ONLY);
}
/*=========================================================================*\
* Auxiliar functions
\*=========================================================================*/
static int opt_setmembership(lua_State *L, p_socket ps, int level, int name)
{
struct ip_mreq val; /* obj, name, table */
if (!lua_istable(L, 3)) auxiliar_typeerror(L,3,lua_typename(L, LUA_TTABLE));
lua_pushstring(L, "multiaddr");
lua_gettable(L, 3);
if (!lua_isstring(L, -1))
luaL_argerror(L, 3, "string 'multiaddr' field expected");
if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr))
luaL_argerror(L, 3, "invalid 'multiaddr' ip address");
lua_pushstring(L, "interface");
lua_gettable(L, 3);
if (!lua_isstring(L, -1))
luaL_argerror(L, 3, "string 'interface' field expected");
val.imr_interface.s_addr = htonl(INADDR_ANY);
if (strcmp(lua_tostring(L, -1), "*") &&
!inet_aton(lua_tostring(L, -1), &val.imr_interface))
luaL_argerror(L, 3, "invalid 'interface' ip address");
return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
}
static int opt_ip6_setmembership(lua_State *L, p_socket ps, int level, int name)
{
struct ipv6_mreq val; /* obj, opt-name, table */
memset(&val, 0, sizeof(val));
if (!lua_istable(L, 3)) auxiliar_typeerror(L,3,lua_typename(L, LUA_TTABLE));
lua_pushstring(L, "multiaddr");
lua_gettable(L, 3);
if (!lua_isstring(L, -1))
luaL_argerror(L, 3, "string 'multiaddr' field expected");
if (!inet_pton_w32(AF_INET6, lua_tostring(L, -1), &val.ipv6mr_multiaddr))
luaL_argerror(L, 3, "invalid 'multiaddr' ip address");
lua_pushstring(L, "interface");
lua_gettable(L, 3);
/* By default we listen to interface on default route
* (sigh). However, interface= can override it. We should
* support either number, or name for it. Waiting for
* windows port of if_nametoindex */
if (!lua_isnil(L, -1)) {
if (lua_isnumber(L, -1)) {
val.ipv6mr_interface = (unsigned int) lua_tonumber(L, -1);
} else
luaL_argerror(L, -1, "number 'interface' field expected");
}
return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
}
static
int opt_get(lua_State *L, p_socket ps, int level, int name, void *val, int* len)
{
socklen_t socklen = *len;
if (getsockopt(*ps, level, name, (char *) val, &socklen) < 0) {
lua_pushnil(L);
lua_pushstring(L, "getsockopt failed");
return 2;
}
*len = socklen;
return 0;
}
static
int opt_set(lua_State *L, p_socket ps, int level, int name, void *val, int len)
{
if (setsockopt(*ps, level, name, (char *) val, len) < 0) {
lua_pushnil(L);
lua_pushstring(L, "setsockopt failed");
return 2;
}
lua_pushnumber(L, 1);
return 1;
}
static int opt_getboolean(lua_State *L, p_socket ps, int level, int name)
{
int val = 0;
int len = sizeof(val);
int err = opt_get(L, ps, level, name, (char *) &val, &len);
if (err)
return err;
lua_pushboolean(L, val);
return 1;
}
int opt_get_error(lua_State *L, p_socket ps)
{
int val = 0;
socklen_t len = sizeof(val);
if (getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *) &val, &len) < 0) {
lua_pushnil(L);
lua_pushstring(L, "getsockopt failed");
return 2;
}
lua_pushstring(L, socket_strerror(val));
return 1;
}
static int opt_setboolean(lua_State *L, p_socket ps, int level, int name)
{
int val = auxiliar_checkboolean(L, 3); /* obj, name, bool */
return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
}
static int opt_getint(lua_State *L, p_socket ps, int level, int name)
{
int val = 0;
int len = sizeof(val);
int err = opt_get(L, ps, level, name, (char *) &val, &len);
if (err)
return err;
lua_pushnumber(L, val);
return 1;
}
static int opt_setint(lua_State *L, p_socket ps, int level, int name)
{
int val = (int) lua_tonumber(L, 3); /* obj, name, int */
return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
}
| xLua/build/luasocket/options.c/0 | {
"file_path": "xLua/build/luasocket/options.c",
"repo_id": "xLua",
"token_count": 5040
} | 2,131 |
#include <string.h>
#include "socket.h"
static const char *wstrerror(int err);
/*-------------------------------------------------------------------------*\
* Initializes module
\*-------------------------------------------------------------------------*/
int socket_open(void) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
int err = WSAStartup(wVersionRequested, &wsaData );
if (err != 0) return 0;
if ((LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) &&
(LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)) {
WSACleanup();
return 0;
}
return 1;
}
/*-------------------------------------------------------------------------*\
* Close module
\*-------------------------------------------------------------------------*/
int socket_close(void) {
WSACleanup();
return 1;
}
/*-------------------------------------------------------------------------*\
* Wait for readable/writable/connected socket with timeout
\*-------------------------------------------------------------------------*/
#define WAITFD_R 1
#define WAITFD_W 2
#define WAITFD_E 4
#define WAITFD_C (WAITFD_E|WAITFD_W)
int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
int ret;
fd_set rfds, wfds, efds, *rp = NULL, *wp = NULL, *ep = NULL;
struct timeval tv, *tp = NULL;
double t;
if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */
if (sw & WAITFD_R) {
FD_ZERO(&rfds);
FD_SET(*ps, &rfds);
rp = &rfds;
}
if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; }
if (sw & WAITFD_C) { FD_ZERO(&efds); FD_SET(*ps, &efds); ep = &efds; }
if ((t = timeout_get(tm)) >= 0.0) {
tv.tv_sec = (int) t;
tv.tv_usec = (int) ((t-tv.tv_sec)*1.0e6);
tp = &tv;
}
ret = select(0, rp, wp, ep, tp);
if (ret == -1) return WSAGetLastError();
if (ret == 0) return IO_TIMEOUT;
if (sw == WAITFD_C && FD_ISSET(*ps, &efds)) return IO_CLOSED;
return IO_DONE;
}
/*-------------------------------------------------------------------------*\
* Select with int timeout in ms
\*-------------------------------------------------------------------------*/
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
p_timeout tm) {
struct timeval tv;
double t = timeout_get(tm);
tv.tv_sec = (int) t;
tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6);
if (n <= 0) {
Sleep((DWORD) (1000*t));
return 0;
} else return select(0, rfds, wfds, efds, t >= 0.0? &tv: NULL);
}
/*-------------------------------------------------------------------------*\
* Close and inutilize socket
\*-------------------------------------------------------------------------*/
void socket_destroy(p_socket ps) {
if (*ps != SOCKET_INVALID) {
socket_setblocking(ps); /* close can take a long time on WIN32 */
closesocket(*ps);
*ps = SOCKET_INVALID;
}
}
/*-------------------------------------------------------------------------*\
*
\*-------------------------------------------------------------------------*/
void socket_shutdown(p_socket ps, int how) {
socket_setblocking(ps);
shutdown(*ps, how);
socket_setnonblocking(ps);
}
/*-------------------------------------------------------------------------*\
* Creates and sets up a socket
\*-------------------------------------------------------------------------*/
int socket_create(p_socket ps, int domain, int type, int protocol) {
*ps = socket(domain, type, protocol);
if (*ps != SOCKET_INVALID) return IO_DONE;
else return WSAGetLastError();
}
/*-------------------------------------------------------------------------*\
* Connects or returns error message
\*-------------------------------------------------------------------------*/
int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
int err;
/* don't call on closed socket */
if (*ps == SOCKET_INVALID) return IO_CLOSED;
/* ask system to connect */
if (connect(*ps, addr, len) == 0) return IO_DONE;
/* make sure the system is trying to connect */
err = WSAGetLastError();
if (err != WSAEWOULDBLOCK && err != WSAEINPROGRESS) return err;
/* zero timeout case optimization */
if (timeout_iszero(tm)) return IO_TIMEOUT;
/* we wait until something happens */
err = socket_waitfd(ps, WAITFD_C, tm);
if (err == IO_CLOSED) {
int len = sizeof(err);
/* give windows time to set the error (yes, disgusting) */
Sleep(10);
/* find out why we failed */
getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
/* we KNOW there was an error. if 'why' is 0, we will return
* "unknown error", but it's not really our fault */
return err > 0? err: IO_UNKNOWN;
} else return err;
}
/*-------------------------------------------------------------------------*\
* Binds or returns error message
\*-------------------------------------------------------------------------*/
int socket_bind(p_socket ps, SA *addr, socklen_t len) {
int err = IO_DONE;
socket_setblocking(ps);
if (bind(*ps, addr, len) < 0) err = WSAGetLastError();
socket_setnonblocking(ps);
return err;
}
/*-------------------------------------------------------------------------*\
*
\*-------------------------------------------------------------------------*/
int socket_listen(p_socket ps, int backlog) {
int err = IO_DONE;
socket_setblocking(ps);
if (listen(*ps, backlog) < 0) err = WSAGetLastError();
socket_setnonblocking(ps);
return err;
}
/*-------------------------------------------------------------------------*\
* Accept with timeout
\*-------------------------------------------------------------------------*/
int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len,
p_timeout tm) {
if (*ps == SOCKET_INVALID) return IO_CLOSED;
for ( ;; ) {
int err;
/* try to get client socket */
if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE;
/* find out why we failed */
err = WSAGetLastError();
/* if we failed because there was no connectoin, keep trying */
if (err != WSAEWOULDBLOCK && err != WSAECONNABORTED) return err;
/* call select to avoid busy wait */
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
}
/*-------------------------------------------------------------------------*\
* Send with timeout
* On windows, if you try to send 10MB, the OS will buffer EVERYTHING
* this can take an awful lot of time and we will end up blocked.
* Therefore, whoever calls this function should not pass a huge buffer.
\*-------------------------------------------------------------------------*/
int socket_send(p_socket ps, const char *data, size_t count,
size_t *sent, p_timeout tm)
{
int err;
*sent = 0;
/* avoid making system calls on closed sockets */
if (*ps == SOCKET_INVALID) return IO_CLOSED;
/* loop until we send something or we give up on error */
for ( ;; ) {
/* try to send something */
int put = send(*ps, data, (int) count, 0);
/* if we sent something, we are done */
if (put > 0) {
*sent = put;
return IO_DONE;
}
/* deal with failure */
err = WSAGetLastError();
/* we can only proceed if there was no serious error */
if (err != WSAEWOULDBLOCK) return err;
/* avoid busy wait */
if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
}
}
/*-------------------------------------------------------------------------*\
* Sendto with timeout
\*-------------------------------------------------------------------------*/
int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
SA *addr, socklen_t len, p_timeout tm)
{
int err;
*sent = 0;
if (*ps == SOCKET_INVALID) return IO_CLOSED;
for ( ;; ) {
int put = sendto(*ps, data, (int) count, 0, addr, len);
if (put > 0) {
*sent = put;
return IO_DONE;
}
err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) return err;
if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
}
}
/*-------------------------------------------------------------------------*\
* Receive with timeout
\*-------------------------------------------------------------------------*/
int socket_recv(p_socket ps, char *data, size_t count, size_t *got,
p_timeout tm)
{
int err, prev = IO_DONE;
*got = 0;
if (*ps == SOCKET_INVALID) return IO_CLOSED;
for ( ;; ) {
int taken = recv(*ps, data, (int) count, 0);
if (taken > 0) {
*got = taken;
return IO_DONE;
}
if (taken == 0) return IO_CLOSED;
err = WSAGetLastError();
/* On UDP, a connreset simply means the previous send failed.
* So we try again.
* On TCP, it means our socket is now useless, so the error passes.
* (We will loop again, exiting because the same error will happen) */
if (err != WSAEWOULDBLOCK) {
if (err != WSAECONNRESET || prev == WSAECONNRESET) return err;
prev = err;
}
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
}
/*-------------------------------------------------------------------------*\
* Recvfrom with timeout
\*-------------------------------------------------------------------------*/
int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
SA *addr, socklen_t *len, p_timeout tm)
{
int err, prev = IO_DONE;
*got = 0;
if (*ps == SOCKET_INVALID) return IO_CLOSED;
for ( ;; ) {
int taken = recvfrom(*ps, data, (int) count, 0, addr, len);
if (taken > 0) {
*got = taken;
return IO_DONE;
}
if (taken == 0) return IO_CLOSED;
err = WSAGetLastError();
/* On UDP, a connreset simply means the previous send failed.
* So we try again.
* On TCP, it means our socket is now useless, so the error passes.
* (We will loop again, exiting because the same error will happen) */
if (err != WSAEWOULDBLOCK) {
if (err != WSAECONNRESET || prev == WSAECONNRESET) return err;
prev = err;
}
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
}
/*-------------------------------------------------------------------------*\
* Put socket into blocking mode
\*-------------------------------------------------------------------------*/
void socket_setblocking(p_socket ps) {
u_long argp = 0;
ioctlsocket(*ps, FIONBIO, &argp);
}
/*-------------------------------------------------------------------------*\
* Put socket into non-blocking mode
\*-------------------------------------------------------------------------*/
void socket_setnonblocking(p_socket ps) {
u_long argp = 1;
ioctlsocket(*ps, FIONBIO, &argp);
}
/*-------------------------------------------------------------------------*\
* DNS helpers
\*-------------------------------------------------------------------------*/
int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) {
*hp = gethostbyaddr(addr, len, AF_INET);
if (*hp) return IO_DONE;
else return WSAGetLastError();
}
int socket_gethostbyname(const char *addr, struct hostent **hp) {
*hp = gethostbyname(addr);
if (*hp) return IO_DONE;
else return WSAGetLastError();
}
/*-------------------------------------------------------------------------*\
* Error translation functions
\*-------------------------------------------------------------------------*/
const char *socket_hoststrerror(int err) {
if (err <= 0) return io_strerror(err);
switch (err) {
case WSAHOST_NOT_FOUND: return "host not found";
default: return wstrerror(err);
}
}
const char *socket_strerror(int err) {
if (err <= 0) return io_strerror(err);
switch (err) {
case WSAEADDRINUSE: return "address already in use";
case WSAECONNREFUSED: return "connection refused";
case WSAEISCONN: return "already connected";
case WSAEACCES: return "permission denied";
case WSAECONNABORTED: return "closed";
case WSAECONNRESET: return "closed";
case WSAETIMEDOUT: return "timeout";
default: return wstrerror(err);
}
}
const char *socket_ioerror(p_socket ps, int err) {
(void) ps;
return socket_strerror(err);
}
static const char *wstrerror(int err) {
switch (err) {
case WSAEINTR: return "Interrupted function call";
case WSAEACCES: return "Permission denied";
case WSAEFAULT: return "Bad address";
case WSAEINVAL: return "Invalid argument";
case WSAEMFILE: return "Too many open files";
case WSAEWOULDBLOCK: return "Resource temporarily unavailable";
case WSAEINPROGRESS: return "Operation now in progress";
case WSAEALREADY: return "Operation already in progress";
case WSAENOTSOCK: return "Socket operation on nonsocket";
case WSAEDESTADDRREQ: return "Destination address required";
case WSAEMSGSIZE: return "Message too long";
case WSAEPROTOTYPE: return "Protocol wrong type for socket";
case WSAENOPROTOOPT: return "Bad protocol option";
case WSAEPROTONOSUPPORT: return "Protocol not supported";
case WSAESOCKTNOSUPPORT: return "Socket type not supported";
case WSAEOPNOTSUPP: return "Operation not supported";
case WSAEPFNOSUPPORT: return "Protocol family not supported";
case WSAEAFNOSUPPORT:
return "Address family not supported by protocol family";
case WSAEADDRINUSE: return "Address already in use";
case WSAEADDRNOTAVAIL: return "Cannot assign requested address";
case WSAENETDOWN: return "Network is down";
case WSAENETUNREACH: return "Network is unreachable";
case WSAENETRESET: return "Network dropped connection on reset";
case WSAECONNABORTED: return "Software caused connection abort";
case WSAECONNRESET: return "Connection reset by peer";
case WSAENOBUFS: return "No buffer space available";
case WSAEISCONN: return "Socket is already connected";
case WSAENOTCONN: return "Socket is not connected";
case WSAESHUTDOWN: return "Cannot send after socket shutdown";
case WSAETIMEDOUT: return "Connection timed out";
case WSAECONNREFUSED: return "Connection refused";
case WSAEHOSTDOWN: return "Host is down";
case WSAEHOSTUNREACH: return "No route to host";
case WSAEPROCLIM: return "Too many processes";
case WSASYSNOTREADY: return "Network subsystem is unavailable";
case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range";
case WSANOTINITIALISED:
return "Successful WSAStartup not yet performed";
case WSAEDISCON: return "Graceful shutdown in progress";
case WSAHOST_NOT_FOUND: return "Host not found";
case WSATRY_AGAIN: return "Nonauthoritative host not found";
case WSANO_RECOVERY: return "Nonrecoverable name lookup error";
case WSANO_DATA: return "Valid name, no data record of requested type";
default: return "Unknown error";
}
}
const char *socket_gaistrerror(int err) {
if (err == 0) return NULL;
switch (err) {
case EAI_AGAIN: return "temporary failure in name resolution";
case EAI_BADFLAGS: return "invalid value for ai_flags";
#ifdef EAI_BADHINTS
case EAI_BADHINTS: return "invalid value for hints";
#endif
case EAI_FAIL: return "non-recoverable failure in name resolution";
case EAI_FAMILY: return "ai_family not supported";
case EAI_MEMORY: return "memory allocation failure";
case EAI_NONAME:
return "host or service not provided, or not known";
#ifdef EAI_OVERFLOW
case EAI_OVERFLOW: return "argument buffer overflow";
#endif
#ifdef EAI_PROTOCOL
case EAI_PROTOCOL: return "resolved protocol is unknown";
#endif
case EAI_SERVICE: return "service not supported for socket type";
case EAI_SOCKTYPE: return "ai_socktype not supported";
#ifdef EAI_SYSTEM
case EAI_SYSTEM: return strerror(errno);
#endif
default: return gai_strerror(err);
}
}
| xLua/build/luasocket/wsocket.c/0 | {
"file_path": "xLua/build/luasocket/wsocket.c",
"repo_id": "xLua",
"token_count": 6131
} | 2,132 |
set CUR_DIR=%~dp0
cd %CUR_DIR%
del /s/q buildnx64
mkdir buildnx64 & pushd buildnx64
rem fix for io_tmpfile & os_tmpname
echo #if !__ASSEMBLER__ > switch_fix.h
echo static inline struct _IO_FILE* tmpfile(){ return 0; } >> switch_fix.h
echo static inline char* tmpnam(char* n){ return 0; } >> switch_fix.h
echo #endif >> switch_fix.h
popd
pushd luajit-2.1.0b3
rem use cygwin64 to compile because msvc treat zero-length array as error
rem define LUAJIT_USE_SYSMALLOC as no mmap for switch
for /F "tokens=* USEBACKQ" %%F IN (`cygpath %NINTENDO_SDK_ROOT%`) DO set NINTENDO_SDK_ROOT_CYG=%%F
set COMPILER="%NINTENDO_SDK_ROOT_CYG%/Compilers/NX/bin/nx-clang.exe"
set "SWITCH_CFLAGS=-m64 -mcpu=cortex-a57+fp+simd+crypto+crc -fno-common -fno-short-enums -ffunction-sections -fdata-sections -fPIC -fms-extensions"
set "LUAJIT_CFLAGS=-DLJ_TARGET_CONSOLE -DLUAJIT_USE_SYSMALLOC -DLUAJIT_DISABLE_JIT -DLUAJIT_ENABLE_GC64 -DLUAJIT_DISABLE_FFI"
set "FIX_FLAGS=-includeswitch_fix.h -I%CUR_DIR%buildnx64"
bash -c "make clean"
bash -c "make -C src TARGET_CC=\"%COMPILER% %SWITCH_CFLAGS% %FIX_FLAGS%\" TARGET_LD=%COMPILER% BUILDMODE=static TARGET_SYS=switch CFLAGS=\"%LUAJIT_CFLAGS%\" libluajit.a"
popd
pushd buildnx64
set "NINTENDO_SDK_ROOT_CMAKE=%NINTENDO_SDK_ROOT:\=/%"
cmake -DCMAKE_C_COMPILER="%NINTENDO_SDK_ROOT_CMAKE%/Compilers/NX/nx/aarch64/bin/clang.exe" ^
-DCMAKE_CXX_COMPILER="%NINTENDO_SDK_ROOT_CMAKE%/Compilers/NX/nx/aarch64/bin/clang++.exe" ^
-G "Unix Makefiles" -DCMAKE_SYSTEM_NAME=Switch ^
-DUSING_LUAJIT=ON ^
..
popd
cmake --build buildnx64 --config Release
mkdir plugin_luajit\Plugins\Switch
copy /Y buildnx64\libxlua.a plugin_luajit\Plugins\Switch\libxlua.a
copy /Y luajit-2.1.0b3\src\libluajit.a plugin_luajit\Plugins\Switch\libluajit.a
rem may need to set package.cpath = "" in lua
rem as any read attempt to undefined location will crash
| xLua/build/make_nx64_luajit_gc64.bat/0 | {
"file_path": "xLua/build/make_nx64_luajit_gc64.bat",
"repo_id": "xLua",
"token_count": 840
} | 2,133 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>15G31</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>xlua</string>
<key>CFBundleIdentifier</key>
<string>com.xlua</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>xlua</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7D1014</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>15E60</string>
<key>DTSDKName</key>
<string>macosx10.11</string>
<key>DTXcode</key>
<string>0731</string>
<key>DTXcodeBuild</key>
<string>7D1014</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright @2017 THL A29 Limited, a Tencent company. All rights reserved.</string>
</dict>
</plist>
| xLua/build/plugin_luajit/Plugins/xlua.bundle/Contents/Info.plist/0 | {
"file_path": "xLua/build/plugin_luajit/Plugins/xlua.bundle/Contents/Info.plist",
"repo_id": "xLua",
"token_count": 567
} | 2,134 |
---
title: 添加删除第三方库
type: guide
order: 101
---
## 添加删除第三方库
> Todo:请在此处输入内容 | xLua/docs/source/src/v1/guide/crtdel-3rd.md/0 | {
"file_path": "xLua/docs/source/src/v1/guide/crtdel-3rd.md",
"repo_id": "xLua",
"token_count": 74
} | 2,135 |
<section class="sidebar clearfix">
<ul>
<% site.pages.find({type: 'guide' , lang: page.lang}).sort('order').each(function (p) { %>
<% var fileName = p.path.replace(/^.+?\/([\w-]+)\.html/, '$1') %>
<% if(fileName == 'index'){%>
<li><h3>基础</h3></li>
<%}%>
<% if(fileName == 'tutorial'){%>
<li><h3>教程</h3></li>
<%}%>
<% if(fileName == 'hotfix'){%>
<li><h3>其他</h3></li>
<%}%>
<li>
<p><a href="<%- url_for(p.path) %>" class="sidebar-link<%- page.title === p.title ? ' current' : '' %><%- p.is_new ? ' new' : '' %>"><%- p.title %></a></p>
</li>
<% }) %>
</ul>
</section> | xLua/docs/source/themes/catlib/layout/partials/sidebar.ejs/0 | {
"file_path": "xLua/docs/source/themes/catlib/layout/partials/sidebar.ejs",
"repo_id": "xLua",
"token_count": 466
} | 2,136 |
/*!
* Vue.js v2.3.0
* (c) 2014-2017 Evan You
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Vue = factory());
}(this, (function () { 'use strict';
/* */
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
function isUndef (v) {
return v === undefined || v === null
}
function isDef (v) {
return v !== undefined && v !== null
}
function isTrue (v) {
return v === true
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
var toString = Object.prototype.toString;
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return toString.call(obj) === '[object Object]'
}
function isRegExp (v) {
return toString.call(v) === '[object RegExp]'
}
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
return JSON.stringify(a) === JSON.stringify(b)
} catch (e) {
// possible circular reference
return a === b
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
var SSR_ATTR = 'data-server-rendered';
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: "development" !== 'production',
/**
* Whether to enable devtools
*/
devtools: "development" !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
var emptyObject = Object.freeze({});
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
}
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
var warn = noop;
var tip = noop;
var formatComponentName;
{
var hasConsole = typeof console !== 'undefined';
var classifyRE = /(?:^|[-_])(\w)/g;
var classify = function (str) { return str
.replace(classifyRE, function (c) { return c.toUpperCase(); })
.replace(/[-_]/g, ''); };
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
tip = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.warn("[Vue tip]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
formatComponentName = function (vm, includeFile) {
if (vm.$root === vm) {
return '<Root>'
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "<Anonymous>") +
(file && includeFile !== false ? (" at " + file) : '')
)
};
var repeat = function (str, n) {
var res = '';
while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}
return res
};
var generateComponentTrace = function (vm) {
if (vm._isVue && vm.$parent) {
var tree = [];
var currentRecursiveSequence = 0;
while (vm) {
if (tree.length > 0) {
var last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++;
vm = vm.$parent;
continue
} else if (currentRecursiveSequence > 0) {
tree[tree.length - 1] = [last, currentRecursiveSequence];
currentRecursiveSequence = 0;
}
}
tree.push(vm);
vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree
.map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)
? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)")
: formatComponentName(vm))); })
.join('\n')
} else {
return ("\n\n(found in " + (formatComponentName(vm)) + ")")
}
};
}
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
{
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
var supportsPassive = false;
if (inBrowser) {
try {
var opts = {};
Object.defineProperty(opts, 'passive', ({
get: function get () {
/* istanbul ignore next */
supportsPassive = true;
}
} )); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
}
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
var hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
timerFunc();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* */
var uid = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stabilize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if ("development" !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
if (Array.isArray(target) && typeof key === 'number') {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (hasOwn(target, key)) {
target[key] = val;
return val
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
"development" !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (target, key) {
if (Array.isArray(target) && typeof key === 'number') {
target.splice(key, 1);
return
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
"development" !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
{
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
"development" !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
LIFECYCLE_HOOKS.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
{
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if ("development" !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
{
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if ("development" !== 'production' && isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
valid = typeof value === expectedType.toLowerCase();
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}
var mark;
var measure;
{
var perf = inBrowser && window.performance;
/* istanbul ignore if */
if (
perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures
) {
mark = function (tag) { return perf.mark(tag); };
measure = function (name, startTag, endTag) {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
perf.clearMeasures(name);
};
}
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
{
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var prototypeAccessors = { child: {} };
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
return this.componentInstance
};
Object.defineProperties( VNode.prototype, prototypeAccessors );
var createEmptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var len = vnodes.length;
var res = new Array(len);
for (var i = 0; i < len; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
var normalizeEvent = cached(function (name) {
var passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
name = once$$1 ? name.slice(1) : name;
var capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name: name,
once: once$$1,
capture: capture,
passive: passive
}
});
function createFnInvoker (fns) {
function invoker () {
var arguments$1 = arguments;
var fns = invoker.fns;
if (Array.isArray(fns)) {
for (var i = 0; i < fns.length; i++) {
fns[i].apply(null, arguments$1);
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
"development" !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur);
}
add(event.name, cur, event.once, event.capture, event.passive);
} else if (cur !== old) {
old.fns = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name], event.capture);
}
}
}
/* */
function mergeVNodeHook (def, hookKey, hook) {
var invoker;
var oldHook = def[hookKey];
function wrappedHook () {
hook.apply(this, arguments);
// important: remove merged hook to ensure it's called only once
// and prevent memory leak
remove(invoker.fns, wrappedHook);
}
if (isUndef(oldHook)) {
// no existing hook
invoker = createFnInvoker([wrappedHook]);
} else {
/* istanbul ignore if */
if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {
// already a merged invoker
invoker = oldHook;
invoker.fns.push(wrappedHook);
} else {
// existing plain hook
invoker = createFnInvoker([oldHook, wrappedHook]);
}
}
invoker.merged = true;
def[hookKey] = invoker;
}
/* */
function extractPropsFromVNodeData (
data,
Ctor,
tag
) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (isUndef(propOptions)) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
if (isDef(attrs) || isDef(props)) {
for (var key in propOptions) {
var altKey = hyphenate(key);
{
var keyInLowerCase = key.toLowerCase();
if (
key !== keyInLowerCase &&
attrs && hasOwn(attrs, keyInLowerCase)
) {
tip(
"Prop \"" + keyInLowerCase + "\" is passed to component " +
(formatComponentName(tag || Ctor)) + ", but the declared prop name is" +
" \"" + key + "\". " +
"Note that HTML attributes are case-insensitive and camelCased " +
"props need to use their kebab-case equivalents when using in-DOM " +
"templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."
);
}
}
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (isDef(hash)) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (isDef(last) && isDef(last.text)) {
(last).text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isDef(c.text) && isDef(last) && isDef(last.text)) {
res[res.length - 1] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) {
c.key = "__vlist" + ((nestedIndex)) + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function ensureCtor (comp, base) {
return isObject(comp)
? base.extend(comp)
: comp
}
function resolveAsyncComponent (
factory,
baseCtor,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
var contexts = factory.contexts = [context];
var sync = true;
var forceRender = function () {
for (var i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
};
var resolve = once(function (res) {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor);
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender();
}
});
var reject = once(function (reason) {
"development" !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender();
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
setTimeout(function () {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender();
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(function () {
reject(
"timeout (" + (res.timeout) + "ms)"
);
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
function getFirstComponentChild (children) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (isDef(c) && isDef(c.componentOptions)) {
return c
}
}
}
}
/* */
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add (event, fn, once$$1) {
if (once$$1) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var this$1 = this;
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
this$1.$on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var this$1 = this;
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// array of events
if (Array.isArray(event)) {
for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
this$1.$off(event[i$1], fn);
}
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
{
var lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
"Event \"" + lowerCaseEvent + "\" is emitted in component " +
(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
"Note that HTML attributes are case-insensitive and you cannot use " +
"v-on to listen to camelCase events when using in-DOM templates. " +
"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
);
}
}
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && child.data.slot != null) {
var name = child.data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore whitespace
if (!defaultSlot.every(isWhitespace)) {
slots.default = defaultSlot;
}
return slots
}
function isWhitespace (node) {
return node.isComment || node.text === ' '
}
function resolveScopedSlots (
fns
) {
var res = {};
for (var i = 0; i < fns.length; i++) {
res[fns[i][0]] = fns[i][1];
}
return res
}
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = null;
vm._directInactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = vm;
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
// fire destroyed hook
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// remove reference to DOM nodes (prevents leak)
vm.$options._parentElm = vm.$options._refElm = null;
};
}
function mountComponent (
vm,
el,
hydrating
) {
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
{
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
var updateComponent;
/* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
updateComponent = function () {
var name = vm._name;
var id = vm._uid;
var startTag = "vue-perf-start:" + id;
var endTag = "vue-perf-end:" + id;
mark(startTag);
var vnode = vm._render();
mark(endTag);
measure((name + " render"), startTag, endTag);
mark(startTag);
vm._update(vnode, hydrating);
mark(endTag);
measure((name + " patch"), startTag, endTag);
};
} else {
updateComponent = function () {
vm._update(vm._render(), hydrating);
};
}
vm._watcher = new Watcher(vm, updateComponent, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
}
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
var hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
{
observerState.isSettingProps = true;
}
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
props[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
{
observerState.isSettingProps = false;
}
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
}
function isInInactiveTree (vm) {
while (vm && (vm = vm.$parent)) {
if (vm._inactive) { return true }
}
return false
}
function activateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = false;
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false;
for (var i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i]);
}
callHook(vm, 'activated');
}
}
function deactivateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = true;
if (isInInactiveTree(vm)) {
return
}
}
if (!vm._inactive) {
vm._inactive = true;
for (var i = 0; i < vm.$children.length; i++) {
deactivateChildComponent(vm.$children[i]);
}
callHook(vm, 'deactivated');
}
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm);
} catch (e) {
handleError(e, vm, (hook + " hook"));
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = activatedChildren.length = 0;
has = {};
{
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
var watcher, id;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if ("development" !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// keep copies of post queues before resetting state
var activatedQueue = activatedChildren.slice();
var updatedQueue = queue.slice();
resetSchedulerState();
// call component updated and activated hooks
callActivatedHooks(activatedQueue);
callUpdateHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdateHooks (queue) {
var i = queue.length;
while (i--) {
var watcher = queue[i];
var vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted) {
callHook(vm, 'updated');
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
*/
function queueActivatedComponent (vm) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
vm._inactive = false;
activatedChildren.push(vm);
}
function callActivatedHooks (queue) {
for (var i = 0; i < queue.length; i++) {
queue[i]._inactive = true;
activateChildComponent(queue[i], true /* true */);
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = expOrFn.toString();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
"development" !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value;
var vm = this.vm;
if (this.user) {
try {
value = this.getter.call(vm, vm);
} catch (e) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
}
} else {
value = this.getter.call(vm, vm);
}
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/* */
var sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function proxy (target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
};
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val;
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch) { initWatch(vm, opts.watch); }
}
var isReservedProp = {
key: 1,
ref: 1,
slot: 1
};
function initProps (vm, propsOptions) {
var propsData = vm.$options.propsData || {};
var props = vm._props = {};
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
var keys = vm.$options._propKeys = [];
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( key ) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
{
if (isReservedProp[key] || config.isReservedAttr(key)) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(props, key, value, function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, "_props", key);
}
};
for (var key in propsOptions) loop( key );
observerState.shouldConvert = true;
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
"development" !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
"development" !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else if (!isReserved(keys[i])) {
proxy(vm, "_data", keys[i]);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
}
}
var computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
var watchers = vm._computedWatchers = Object.create(null);
for (var key in computed) {
var userDef = computed[key];
var getter = typeof userDef === 'function' ? userDef : userDef.get;
{
if (getter === undefined) {
warn(
("No getter function has been defined for computed property \"" + key + "\"."),
vm
);
getter = noop;
}
}
// create internal watcher for the computed property.
watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions);
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef);
} else {
if (key in vm.$data) {
warn(("The computed property \"" + key + "\" is already defined in data."), vm);
} else if (vm.$options.props && key in vm.$options.props) {
warn(("The computed property \"" + key + "\" is already defined as a prop."), vm);
}
}
}
}
function defineComputed (target, key, userDef) {
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = createComputedGetter(key);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop;
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop;
}
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter (key) {
return function computedGetter () {
var watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
}
function initMethods (vm, methods) {
var props = vm.$options.props;
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
{
if (methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
if (props && hasOwn(props, key)) {
warn(
("method \"" + key + "\" has already been defined as a prop."),
vm
);
}
}
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () { return this._data };
var propsDef = {};
propsDef.get = function () { return this._props };
{
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
propsDef.set = function () {
warn("$props is readonly.", this);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Object.defineProperty(Vue.prototype, '$props', propsDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
function initProvide (vm) {
var provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
function initInjections (vm) {
var result = resolveInject(vm.$options.inject, vm);
if (result) {
Object.keys(result).forEach(function (key) {
/* istanbul ignore else */
{
defineReactive$$1(vm, key, result[key], function () {
warn(
"Avoid mutating an injected value directly since the changes will be " +
"overwritten whenever the provided component re-renders. " +
"injection being mutated: \"" + key + "\"",
vm
);
});
}
});
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
// isArray here
var isArray = Array.isArray(inject);
var result = Object.create(null);
var keys = isArray
? inject
: hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var provideKey = isArray ? key : inject[key];
var source = vm;
while (source) {
if (source._provided && provideKey in source._provided) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
}
return result
}
}
/* */
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
data: data,
props: props,
children: children,
parent: context,
listeners: data.on || {},
injections: resolveInject(Ctor.options.inject, context),
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
// hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
}
},
prepatch: function prepatch (oldVnode, vnode) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
},
insert: function insert (vnode) {
var context = vnode.context;
var componentInstance = vnode.componentInstance;
if (!componentInstance._isMounted) {
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
// vue-router#1212
// During updates, a kept-alive component's child components may
// change, so directly walking the tree here may call activated hooks
// on incorrect children. Instead we push them into a queue which will
// be processed after the whole patch process ended.
queueActivatedComponent(componentInstance);
} else {
activateChildComponent(componentInstance, true /* direct */);
}
}
},
destroy: function destroy (vnode) {
var componentInstance = vnode.componentInstance;
if (!componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
var hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
var baseCtor = context.$options._base;
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
{
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (isUndef(Ctor.cid)) {
Ctor = resolveAsyncComponent(Ctor, baseCtor, context);
if (Ctor === undefined) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
// extract props
var propsData = extractPropsFromVNodeData(data, Ctor, tag);
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = componentVNodeHooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
// transform component v-model info (value and callback) into
// prop and event handler respectively.
function transformModel (options, data) {
var prop = (options.model && options.model.prop) || 'value';
var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
if (isDef(on[event])) {
on[event] = [data.model.callback].concat(on[event]);
} else {
on[event] = data.model.callback;
}
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (isDef(data) && isDef((data).__ob__)) {
"development" !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function') {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (vnode !== undefined) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
if (Array.isArray(vnode.children)) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (isDef(child.tag) && isUndef(child.ns)) {
applyNS(child, ns);
}
}
}
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
return ret
}
/* */
/**
* Runtime helper for rendering <slot>
*/
function renderSlot (
name,
fallback,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
extend(props, bindObject);
}
return scopedSlotFn(props) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && "development" !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
/**
* Runtime helper for checking keyCodes from config.
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInAlias
) {
var keyCodes = config.keyCodes[key] || builtInAlias;
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
"development" !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
for (var key in value) {
if (key === 'class' || key === 'style') {
hash = data;
} else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
if (!(key in hash)) {
hash[key] = value[key];
}
}
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] =
this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
}
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* */
function initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject;
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render function");
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
{
vnode = vm.$options.renderError
? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
: vm._vnode;
}
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if ("development" !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// internal render helpers.
// these are exposed on the instance prototype to reduce generated render
// code size.
Vue.prototype._o = markOnce;
Vue.prototype._n = toNumber;
Vue.prototype._s = _toString;
Vue.prototype._l = renderList;
Vue.prototype._t = renderSlot;
Vue.prototype._q = looseEqual;
Vue.prototype._i = looseIndexOf;
Vue.prototype._m = renderStatic;
Vue.prototype._f = resolveFilter;
Vue.prototype._k = checkKeyCodes;
Vue.prototype._b = bindObjectProps;
Vue.prototype._v = createTextVNode;
Vue.prototype._e = createEmptyVNode;
Vue.prototype._u = resolveScopedSlots;
}
/* */
var uid$1 = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid$1++;
var startTag, endTag;
/* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
startTag = "vue-perf-init:" + (vm._uid);
endTag = "vue-perf-end:" + (vm._uid);
mark(startTag);
}
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
{
initProxy(vm);
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created');
/* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(((vm._name) + " init"), startTag, endTag);
}
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = resolveConstructorOptions(Ctor.super);
var cachedSuperOptions = Ctor.superOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
var modifiedOptions = resolveModifiedOptions(Ctor);
// update base extend options
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions);
}
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function resolveModifiedOptions (Ctor) {
var modified;
var latest = Ctor.options;
var extended = Ctor.extendOptions;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = dedupe(latest[key], extended[key], sealed[key]);
}
}
return modified
}
function dedupe (latest, extended, sealed) {
// compare latest and sealed to ensure lifecycle hooks won't be duplicated
// between merges
if (Array.isArray(latest)) {
var res = [];
sealed = Array.isArray(sealed) ? sealed : [sealed];
extended = Array.isArray(extended) ? extended : [extended];
for (var i = 0; i < latest.length; i++) {
// push original options and not sealed options to exclude duplicated options
if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {
res.push(latest[i]);
}
}
return res
} else {
return latest
}
}
function Vue$3 (options) {
if ("development" !== 'production' &&
!(this instanceof Vue$3)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$3);
stateMixin(Vue$3);
eventsMixin(Vue$3);
lifecycleMixin(Vue$3);
renderMixin(Vue$3);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
{
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
);
}
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
function initProps$1 (Comp) {
var props = Comp.options.props;
for (var key in props) {
proxy(Comp.prototype, "_props", key);
}
}
function initComputed$1 (Comp) {
var computed = Comp.options.computed;
for (var key in computed) {
defineComputed(Comp.prototype, key, computed[key]);
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
{
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
);
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
var patternTypes = [String, RegExp];
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
function pruneCache (cache, current, filter) {
for (var key in cache) {
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
if (cachedNode !== current) {
pruneCacheEntry(cachedNode);
}
cache[key] = null;
}
}
}
}
function pruneCacheEntry (vnode) {
if (vnode) {
vnode.componentInstance.$destroy();
}
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes
},
created: function created () {
this.cache = Object.create(null);
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this$1.cache) {
pruneCacheEntry(this$1.cache[key]);
}
},
watch: {
include: function include (val) {
pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); });
},
exclude: function exclude (val) {
pruneCache(this.cache, this._vnode, function (name) { return !matches(val, name); });
}
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
: vnode.key;
if (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
{
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
// exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn: warn,
extend: extend,
mergeOptions: mergeOptions,
defineReactive: defineReactive$$1
};
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
Vue.options = Object.create(null);
ASSET_TYPES.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue$3);
Object.defineProperty(Vue$3.prototype, '$isServer', {
get: isServerRendering
});
Vue$3.version = '2.3.0';
/* */
// these are reserved for web because they are directly compiled away
// during template compilation
var isReservedAttr = makeMap('style,class');
// attributes that should be using props for binding
var acceptValue = makeMap('input,textarea,option,select');
var mustUseProp = function (tag, type, attr) {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (isDef(childNode.componentInstance)) {
childNode = childNode.componentInstance._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while (isDef(parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: isDef(child.class)
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (isDef(staticClass) || isDef(dynamicClass)) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
if (isUndef(value)) {
return ''
}
if (typeof value === 'string') {
return value
}
var res = '';
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (isDef(value[i])) {
if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isPreTag = function (tag) { return tag === 'pre'; };
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selected = document.querySelector(el);
if (!selected) {
"development" !== 'production' && warn(
'Cannot find element: ' + el
);
return document.createElement('div')
}
return selected
} else {
return el
}
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
// false or null will remove the attribute but undefined will not
if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setAttribute (node, key, val) {
node.setAttribute(key, val);
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!key) { return }
var vm = vnode.context;
var ref = vnode.componentInstance || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {
refs[key].push(ref);
} else {
refs[key] = [ref];
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];
function sameVnode (a, b) {
return (
a.key === b.key &&
a.tag === b.tag &&
a.isComment === b.isComment &&
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b)
)
}
// Some browsers do not support dynamically changing type for <input>
// so they need to be treated as different nodes
function sameInputType (a, b) {
if (a.tag !== 'input') { return true }
var i;
var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;
var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
return typeA === typeB
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeNode(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeNode (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
if (isDef(parent)) {
nodeOps.removeChild(parent, el);
}
}
var inPre = 0;
function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
var data = vnode.data;
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
{
if (data && data.pre) {
inPre++;
}
if (
!inPre &&
!vnode.ns &&
!(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if ("development" !== 'production' && data && data.pre) {
inPre--;
}
} else if (isTrue(vnode.isComment)) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */, parentElm, refElm);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue);
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (isDef(vnode.data.pendingInsert)) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
}
vnode.elm = vnode.componentInstance.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var innerNode = vnode;
while (innerNode.componentInstance) {
innerNode = innerNode.componentInstance._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref) {
if (isDef(parent)) {
if (isDef(ref)) {
if (ref.parentNode === parent) {
nodeOps.insertBefore(parent, elm, ref);
}
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));
}
}
function isPatchable (vnode) {
while (vnode.componentInstance) {
vnode = vnode.componentInstance._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (isDef(i.create)) { i.create(emptyNode, vnode); }
if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
var ancestor = vnode;
while (ancestor) {
if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
ancestor = ancestor.parent;
}
// for slot content they should also get the scopeId from the host instance.
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
removeNode(ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
var i;
var listeners = cbs.remove.length + 1;
if (isDef(rm)) {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
} else {
// directly removing
rm = createRmCb(vnode.elm, listeners);
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeNode(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null;
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if ("development" !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (sameVnode(elmToMove, newStartVnode)) {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))) {
vnode.elm = oldVnode.elm;
vnode.componentInstance = oldVnode.componentInstance;
return
}
var i;
var data = vnode.data;
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var elm = vnode.elm = oldVnode.elm;
var oldCh = oldVnode.children;
var ch = vnode.children;
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var bailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue) {
{
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.componentInstance)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
var childrenMatch = true;
var childNode = elm.firstChild;
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
if ("development" !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
for (var key in data) {
if (!isRenderedModule(key)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode) {
if (isDef(vnode.tag)) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }
return
}
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue, parentElm, refElm);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR);
hydrating = true;
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
var oldElm = oldVnode.elm;
var parentElm$1 = nodeOps.parentNode(oldElm);
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm$1,
nodeOps.nextSibling(oldElm)
);
if (isDef(vnode.parent)) {
// component root element replaced.
// update parent placeholder node element, recursively
var ancestor = vnode.parent;
while (ancestor) {
ancestor.elm = vnode.elm;
ancestor = ancestor.parent;
}
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (isDef(parentElm$1)) {
removeVnodes(parentElm$1, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
var isCreate = oldVnode === emptyNode;
var isDestroy = vnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
for (var i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert);
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {
for (var i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
});
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
var fn = dir.def && dir.def[hook];
if (fn) {
try {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
} catch (e) {
handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook"));
}
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(attrs.__ob__)) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
/* istanbul ignore if */
if (isIE9 && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (isUndef(attrs[key])) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, key);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (
isUndef(data.staticClass) &&
isUndef(data.class) && (
isUndef(oldData) || (
isUndef(oldData.staticClass) &&
isUndef(oldData.class)
)
)
) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (isDef(transitionClass)) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
var validDivisionCharRE = /[\w).+\-_$\]]/;
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
var j = i - 1;
var p = (void 0);
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') { break }
}
if (!p || !validDivisionCharRE.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
/* */
function baseWarn (msg) {
console.error(("[Vue compiler]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn
) {
// warn prevent and passive modifier
/* istanbul ignore if */
if (
"development" !== 'production' && warn &&
modifiers && modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.'
);
}
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
/* istanbul ignore if */
if (modifiers && modifiers.passive) {
delete modifiers.passive;
name = '&' + name; // mark the event as passive
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, modifiers: modifiers };
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
function getAndRemoveAttr (el, name) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
return val
}
/* */
/**
* Cross-platform code generation for component v-model
*/
function genComponentModel (
el,
value,
modifiers
) {
var ref = modifiers || {};
var number = ref.number;
var trim = ref.trim;
var baseValueExpression = '$$v';
var valueExpression = baseValueExpression;
if (trim) {
valueExpression =
"(typeof " + baseValueExpression + " === 'string'" +
"? " + baseValueExpression + ".trim()" +
": " + baseValueExpression + ")";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var assignment = genAssignmentCode(value, valueExpression);
el.model = {
value: ("(" + value + ")"),
expression: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index$1;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index$1 = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var warn$1;
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
var RANGE_TOKEN = '__r';
var CHECKBOX_RADIO_TOKEN = '__c';
function model (
el,
dir,
_warn
) {
warn$1 = _warn;
var value = dir.value;
var modifiers = dir.modifiers;
var tag = el.tag;
var type = el.attrsMap.type;
{
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$1(
"<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" +
"File inputs are read only. Use a v-on:change listener instead."
);
}
}
if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers);
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"v-model is not supported on this element type. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?_i(" + value + "," + valueBinding + ")>-1" + (
trueValueBinding === 'true'
? (":(" + value + ")")
: (":_q(" + value + "," + trueValueBinding + ")")
)
);
addHandler(el, CHECKBOX_RADIO_TOKEN,
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," +
'$$i=_i($$a,$$v);' +
"if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" +
"}else{" + (genAssignmentCode(value, '$$c')) + "}",
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding;
addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")"));
addHandler(el, CHECKBOX_RADIO_TOKEN, genAssignmentCode(value, valueBinding), null, true);
}
function genSelect (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var selectedVal = "Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){var val = \"_value\" in o ? o._value : o.value;" +
"return " + (number ? '_n(val)' : 'val') + "})";
var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';
var code = "var $$selectedVal = " + selectedVal + ";";
code = code + " " + (genAssignmentCode(value, assignment));
addHandler(el, 'change', code, null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
var type = el.attrsMap.type;
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var needCompositionGuard = !lazy && type !== 'range';
var event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input';
var valueExpression = '$event.target.value';
if (trim) {
valueExpression = "$event.target.value.trim()";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var code = genAssignmentCode(value, valueExpression);
if (needCompositionGuard) {
code = "if($event.target.composing)return;" + code;
}
addProp(el, 'value', ("(" + value + ")"));
addHandler(el, event, code, null, true);
if (trim || number || type === 'number') {
addHandler(el, 'blur', '$forceUpdate()');
}
}
/* */
// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
var event;
/* istanbul ignore if */
if (isDef(on[RANGE_TOKEN])) {
// IE input[type=range] only supports `change` event
event = isIE ? 'change' : 'input';
on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);
delete on[RANGE_TOKEN];
}
if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
// Chrome fires microtasks in between click/change, leads to #4521
event = isChrome ? 'click' : 'change';
on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []);
delete on[CHECKBOX_RADIO_TOKEN];
}
}
var target$1;
function add$1 (
event,
handler,
once$$1,
capture,
passive
) {
if (once$$1) {
var oldHandler = handler;
var _target = target$1; // save current target element in closure
handler = function (ev) {
var res = arguments.length === 1
? oldHandler(ev)
: oldHandler.apply(null, arguments);
if (res !== null) {
remove$2(event, handler, capture, _target);
}
};
}
target$1.addEventListener(
event,
handler,
supportsPassive
? { capture: capture, passive: passive }
: capture
);
}
function remove$2 (
event,
handler,
capture,
_target
) {
(_target || target$1).removeEventListener(event, handler, capture);
}
function updateDOMListeners (oldVnode, vnode) {
if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
normalizeEvents(on);
updateListeners(on, oldOn, add$1, remove$2, vnode.context);
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
function updateDOMProps (oldVnode, vnode) {
if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(props.__ob__)) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (isUndef(props[key])) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) { vnode.children.length = 0; }
if (cur === oldProps[key]) { continue }
}
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = cur == null ? '' : String(cur);
if (shouldUpdateValue(elm, vnode, strCur)) {
elm.value = strCur;
}
} else {
elm[key] = cur;
}
}
}
// check platforms/web/util/attrs.js acceptValue
function shouldUpdateValue (
elm,
vnode,
checkVal
) {
return (!elm.composing && (
vnode.tag === 'option' ||
isDirty(elm, checkVal) ||
isInputChanged(elm, checkVal)
))
}
function isDirty (elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value
return document.activeElement !== elm && elm.value !== checkVal
}
function isInputChanged (elm, newVal) {
var value = elm.value;
var modifiers = elm._vModifiers; // injected by v-model runtime
if ((isDef(modifiers) && modifiers.number) || elm.type === 'number') {
return toNumber(value) !== toNumber(newVal)
}
if (isDef(modifiers) && modifiers.trim) {
return value.trim() !== newVal.trim()
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
var cssVarRE = /^--/;
var importantRE = /\s*!important$/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(name, val.replace(importantRE, ''), 'important');
} else {
var normalizedName = normalize(name);
if (Array.isArray(val)) {
// Support values array created by autoprefixer, e.g.
// {display: ["-webkit-box", "-ms-flexbox", "flex"]}
// Set them one by one, and the browser will only set those it can recognize
for (var i = 0, len = val.length; i < len; i++) {
el.style[normalizedName] = val[i];
}
} else {
el.style[normalizedName] = val;
}
}
};
var prefixes = ['Webkit', 'Moz', 'ms'];
var testEl;
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div');
prop = camelize(prop);
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper;
if (prefixed in testEl.style) {
return prefixed
}
}
});
function updateStyle (oldVnode, vnode) {
var data = vnode.data;
var oldData = oldVnode.data;
if (isUndef(data.staticStyle) && isUndef(data.style) &&
isUndef(oldData.staticStyle) && isUndef(oldData.style)) {
return
}
var cur, name;
var el = vnode.elm;
var oldStaticStyle = oldData.staticStyle;
var oldStyleBinding = oldData.normalizedStyle || oldData.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
var oldStyle = oldStaticStyle || oldStyleBinding;
var style = normalizeStyleBinding(vnode.data.style) || {};
// store normalized style under a different key for next diff
// make sure to clone it if it's reactive, since the user likley wants
// to mutate it.
vnode.data.normalizedStyle = isDef(style.__ob__)
? extend({}, style)
: style;
var newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (isUndef(newStyle[name])) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
}
/* */
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
enterToClass: (name + "-enter-to"),
enterActiveClass: (name + "-enter-active"),
leaveClass: (name + "-leave"),
leaveToClass: (name + "-leave-to"),
leaveActiveClass: (name + "-leave-active")
}
});
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
// binding to window is necessary to make hot reload work in IE in strict mode
var raf = inBrowser && window.requestAnimationFrame
? window.requestAnimationFrame.bind(window)
: setTimeout;
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls);
addClass(el, cls);
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
var transitionDelays = styles[transitionProp + 'Delay'].split(', ');
var transitionDurations = styles[transitionProp + 'Duration'].split(', ');
var transitionTimeout = getTimeout(transitionDelays, transitionDurations);
var animationDelays = styles[animationProp + 'Delay'].split(', ');
var animationDurations = styles[animationProp + 'Duration'].split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
var el = vnode.elm;
// call leave callback now
if (isDef(el._leaveCb)) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return
}
/* istanbul ignore if */
if (isDef(el._enterCb) || el.nodeType !== 1) {
return
}
var ref = (data);
var css = ref.css;
var type = ref.type;
var enterClass = ref.enterClass;
var enterToClass = ref.enterToClass;
var enterActiveClass = ref.enterActiveClass;
var appearClass = ref.appearClass;
var appearToClass = ref.appearToClass;
var appearActiveClass = ref.appearActiveClass;
var beforeEnter = ref.beforeEnter;
var enter = ref.enter;
var afterEnter = ref.afterEnter;
var enterCancelled = ref.enterCancelled;
var beforeAppear = ref.beforeAppear;
var appear = ref.appear;
var afterAppear = ref.afterAppear;
var appearCancelled = ref.appearCancelled;
var duration = ref.duration;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var context = activeInstance;
var transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
transitionNode = transitionNode.parent;
context = transitionNode.context;
}
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear && appearClass
? appearClass
: enterClass;
var activeClass = isAppear && appearActiveClass
? appearActiveClass
: enterActiveClass;
var toClass = isAppear && appearToClass
? appearToClass
: enterToClass;
var beforeEnterHook = isAppear
? (beforeAppear || beforeEnter)
: beforeEnter;
var enterHook = isAppear
? (typeof appear === 'function' ? appear : enter)
: enter;
var afterEnterHook = isAppear
? (afterAppear || afterEnter)
: afterEnter;
var enterCancelledHook = isAppear
? (appearCancelled || enterCancelled)
: enterCancelled;
var explicitEnterDuration = toNumber(
isObject(duration)
? duration.enter
: duration
);
if ("development" !== 'production' && explicitEnterDuration != null) {
checkDuration(explicitEnterDuration, 'enter', vnode);
}
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(enterHook);
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, toClass);
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
});
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
addTransitionClass(el, toClass);
removeTransitionClass(el, startClass);
if (!cb.cancelled && !userWantsControl) {
if (isValidDuration(explicitEnterDuration)) {
setTimeout(cb, explicitEnterDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (isDef(el._enterCb)) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return rm()
}
/* istanbul ignore if */
if (isDef(el._leaveCb) || el.nodeType !== 1) {
return
}
var ref = (data);
var css = ref.css;
var type = ref.type;
var leaveClass = ref.leaveClass;
var leaveToClass = ref.leaveToClass;
var leaveActiveClass = ref.leaveActiveClass;
var beforeLeave = ref.beforeLeave;
var leave = ref.leave;
var afterLeave = ref.afterLeave;
var leaveCancelled = ref.leaveCancelled;
var delayLeave = ref.delayLeave;
var duration = ref.duration;
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(leave);
var explicitLeaveDuration = toNumber(
isObject(duration)
? duration.leave
: duration
);
if ("development" !== 'production' && explicitLeaveDuration != null) {
checkDuration(explicitLeaveDuration, 'leave', vnode);
}
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
addTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveClass);
if (!cb.cancelled && !userWantsControl) {
if (isValidDuration(explicitLeaveDuration)) {
setTimeout(cb, explicitLeaveDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
// only used in dev mode
function checkDuration (val, name, vnode) {
if (typeof val !== 'number') {
warn(
"<transition> explicit " + name + " duration is not a valid number - " +
"got " + (JSON.stringify(val)) + ".",
vnode.context
);
} else if (isNaN(val)) {
warn(
"<transition> explicit " + name + " duration is NaN - " +
'the duration expression might be incorrect.',
vnode.context
);
}
}
function isValidDuration (val) {
return typeof val === 'number' && !isNaN(val)
}
/**
* Normalize a transition hook's argument length. The hook may be:
* - a merged hook (invoker) with the original in .fns
* - a wrapped component method (check ._length)
* - a plain function (.length)
*/
function getHookArgumentsLength (fn) {
if (isUndef(fn)) {
return false
}
var invokerFns = fn.fns;
if (isDef(invokerFns)) {
// invoker
return getHookArgumentsLength(
Array.isArray(invokerFns)
? invokerFns[0]
: invokerFns
)
} else {
return (fn._length || fn.length) > 1
}
}
function _enter (_, vnode) {
if (vnode.data.show !== true) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove: function remove$$1 (vnode, rm) {
/* istanbul ignore else */
if (vnode.data.show !== true) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var model$1 = {
inserted: function inserted (el, binding, vnode) {
if (vnode.tag === 'select') {
var cb = function () {
setSelected(el, binding, vnode.context);
};
cb();
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0);
}
} else if (vnode.tag === 'textarea' || el.type === 'text' || el.type === 'password') {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd);
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options);
if (needReset) {
trigger(el, 'change');
}
}
}
};
function setSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
"development" !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.componentInstance && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.componentInstance._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
var originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition && !isIE9) {
vnode.data.show = true;
enter(vnode, function () {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (transition && !isIE9) {
vnode.data.show = true;
if (value) {
enter(vnode, function () {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
},
unbind: function unbind (
el,
binding,
vnode,
oldVnode,
isDestroy
) {
if (!isDestroy) {
el.style.display = el.__vOriginalDisplay;
}
}
};
var platformDirectives = {
model: model$1,
show: show
};
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String,
duration: [Number, String, Object]
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1];
}
return data
}
function placeholder (h, rawChild) {
if (/\d-keep-alive$/.test(rawChild.tag)) {
return h('keep-alive', {
props: rawChild.componentOptions.propsData
})
}
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
function isSameChild (child, oldChild) {
return oldChild.key === child.key && oldChild.tag === child.tag
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; });
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if ("development" !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if ("development" !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in') {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
var id = "__transition-" + (this._uid) + "-";
child.key = child.key == null
? id + child.tag
: isPrimitive(child.key)
? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true;
}
if (oldChild && oldChild.data && !isSameChild(child, oldChild)) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild && (oldChild.data.transition = extend({}, data));
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
});
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave);
mergeVNodeHook(data, 'enterCancelled', performLeave);
mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; });
}
}
return rawChild
}
};
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final desired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else {
var opts = c.componentOptions;
var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
var body = document.body;
var f = body.offsetHeight; // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
// Detect whether an element with the move class applied has
// CSS transitions. Since the element may be inside an entering
// transition at this very moment, we make a clone of it and remove
// all other transition classes applied to ensure only the move class
// is applied.
var clone = el.cloneNode();
if (el._transitionClasses) {
el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); });
}
addClass(clone, moveClass);
clone.style.display = 'none';
this.$el.appendChild(clone);
var info = getTransitionInfo(clone);
this.$el.removeChild(clone);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue$3.config.mustUseProp = mustUseProp;
Vue$3.config.isReservedTag = isReservedTag;
Vue$3.config.isReservedAttr = isReservedAttr;
Vue$3.config.getTagNamespace = getTagNamespace;
Vue$3.config.isUnknownElement = isUnknownElement;
// install platform runtime directives & components
extend(Vue$3.options.directives, platformDirectives);
extend(Vue$3.options.components, platformComponents);
// install platform patch function
Vue$3.prototype.__patch__ = inBrowser ? patch : noop;
// public mount method
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return mountComponent(this, el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$3);
} else if ("development" !== 'production' && isChrome) {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
if ("development" !== 'production' &&
config.productionTip !== false &&
inBrowser && typeof console !== 'undefined') {
console[console.info ? 'info' : 'log'](
"You are running Vue in development mode.\n" +
"Make sure to turn on production mode when deploying for production.\n" +
"See more tips at https://vuejs.org/guide/deployment.html"
);
}
}, 0);
/* */
// check whether current browser encodes a char inside attribute values
function shouldDecode (content, encoded) {
var div = document.createElement('div');
div.innerHTML = "<div a=\"" + content + "\">";
return div.innerHTML.indexOf(encoded) > 0
}
// #3663
// IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', ' ') : false;
/* */
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr'
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track'
);
/* */
var decoder;
function decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^<!DOCTYPE [^>]+>/i;
var comment = /^<!--/;
var conditionalComment = /^<!\[/;
var IS_REGEX_CAPTURING_BROKEN = false;
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === '';
});
// Special Elements (can contain anything)
var isPlainTextElement = makeMap('script,style,textarea', true);
var reCache = {};
var decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
};
var encodedAttr = /&(?:lt|gt|quot|amp);/g;
var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g;
function decodeAttr (value, shouldDecodeNewlines) {
var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;
return value.replace(re, function (match) { return decodingMap[match]; })
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd >= 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last) {
options.chars && options.chars(html);
if ("development" !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length);
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag);
}
if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {
parseEndTag(tagName);
}
}
var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
lastTag = tagName;
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tagName, start, end) {
var pos, lowerCasedTagName;
if (start == null) { start = index; }
if (end == null) { end = index; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if ("development" !== 'production' &&
(i > pos || !tagName) &&
options.warn) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
var onRE = /^@|^v-on:/;
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(decode);
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$2 = options.warn || baseWarn;
platformGetTagNamespace = options.getTagNamespace || no;
platformMustUseProp = options.mustUseProp || no;
platformIsPreTag = options.isPreTag || no;
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
transforms = pluckModuleFunction(options.modules, 'transformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn$2(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
"development" !== 'production' && warn$2(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">" + ', as they will not be parsed.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
{
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element);
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else {
warnOnce(
"Component template should contain exactly one root element. " +
"If you are using v-if on multiple elements, " +
"use v-else-if to chain them instead."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
{
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if ("development" !== 'production' && el.tag === 'template') {
warn$2("<template> cannot be keyed. Place the key on real elements instead.");
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) {
"development" !== 'production' && warn$2(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else {
warn$2(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if ("development" !== 'production' && children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
children.pop();
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
var once$$1 = getAndRemoveAttr(el, 'v-once');
if (once$$1 != null) {
el.once = true;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if ("development" !== 'production' && el.key) {
warn$2(
"`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var i, l, name, rawName, value, modifiers, isProp;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn$2);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if ("development" !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
{
var expression = parseText(value, delimiters);
if (expression) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if (
"development" !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
// for script (e.g. type="x/template") or style, do not decode content
function isTextTag (el) {
return el.tag === 'script' || el.tag === 'style'
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$2(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"You are binding v-model directly to a v-for iteration alias. " +
"This will not be able to modify the v-for source array because " +
"writing to the alias is like modifying a function local variable. " +
"Consider using an array of objects and use v-model on an object property instead."
);
}
_el = _el.parent;
}
}
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic$1(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic$1 (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic$1(child);
if (!child.static) {
node.static = false;
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor);
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #4868: modifiers that prevent the execution of the listener
// need to explicitly return null so that we can determine whether to remove
// the listener for .once
var genGuard = function (condition) { return ("if(" + condition + ")return null;"); };
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: genGuard("$event.target !== $event.currentTarget"),
ctrl: genGuard("!$event.ctrlKey"),
shift: genGuard("!$event.shiftKey"),
alt: genGuard("!$event.altKey"),
meta: genGuard("!$event.metaKey"),
left: genGuard("'button' in $event && $event.button !== 0"),
middle: genGuard("'button' in $event && $event.button !== 1"),
right: genGuard("'button' in $event && $event.button !== 2")
};
function genHandlers (
events,
native,
warn
) {
var res = native ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if ("development" !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (handler.value) + "}") // inline statement
} else {
var code = '';
var genModifierCode = '';
var keys = [];
for (var key in handler.modifiers) {
if (modifierCode[key]) {
genModifierCode += modifierCode[key];
// left/right
if (keyCodes[key]) {
keys.push(key);
}
} else {
keys.push(key);
}
}
if (keys.length) {
code += genKeyFilter(keys);
}
// Make sure modifiers like prevent and stop get executed after key filtering
if (genModifierCode) {
code += genModifierCode;
}
var handlerCode = isMethodPath
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function bind$1 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
/* */
var baseDirectives = {
bind: bind$1,
cloak: noop
};
/* */
// configurable state
var warn$3;
var transforms$1;
var dataGenFns;
var platformDirectives$1;
var isPlatformReservedTag$1;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$3 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives$1 = options.directives || {};
isPlatformReservedTag$1 = options.isReservedTag || no;
var code = ast ? genElement(ast) : '_c("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
"development" !== 'production' && warn$3(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
if (
"development" !== 'production' &&
maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key
) {
warn$3(
"<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " +
"v-for should have explicit keys. " +
"See https://vuejs.org/guide/list.html#key for more info.",
true /* tip */
);
}
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:{" + (genProps(el.attrs)) + "},";
}
// DOM props
if (el.props) {
data += "domProps:{" + (genProps(el.props)) + "},";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events, false, warn$3)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, warn$3)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// component v-model
if (el.model) {
data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$3);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if ("development" !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$3('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "])")
}
function genScopedSlot (key, el) {
return "[" + key + ",function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}]"
}
function genChildren (el, checkSkip) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (children.length === 1 &&
el$1.for &&
el$1.tag !== 'template' &&
el$1.tag !== 'slot') {
return genElement(el$1)
}
var normalizationType = checkSkip ? getNormalizationType(children) : 0;
return ("[" + (children.map(genNode).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function getNormalizationType (children) {
var res = 0;
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (el.type !== 1) {
continue
}
if (needsNormalization(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
res = 2;
break
}
if (maybeComponent(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {
res = 1;
}
}
return res
}
function needsNormalization (el) {
return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}
function maybeComponent (el) {
return !isPlatformReservedTag$1(el.tag)
}
function genNode (node) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
}
function genText (text) {
return ("_v(" + (text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))) + ")")
}
function genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
var res = "_t(" + slotName + (children ? ("," + children) : '');
var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
var bind$$1 = el.attrsMap['v-bind'];
if ((attrs || bind$$1) && !children) {
res += ",null";
}
if (attrs) {
res += "," + attrs;
}
if (bind$$1) {
res += (attrs ? '' : ',null') + "," + bind$$1;
}
return res + ')'
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el) {
var children = el.inlineTemplate ? null : genChildren(el, true);
return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
// these keywords should not appear inside expressions, but operators like
// typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// these unary operators should not be used as property/method names
var unaryOperatorsRE = new RegExp('\\b' + (
'delete,typeof,void'
).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
function makeFunction (code, errors) {
try {
return new Function(code)
} catch (err) {
errors.push({ err: err, code: code });
return noop
}
}
function createCompiler (baseOptions) {
var functionCompileCache = Object.create(null);
function compile (
template,
options
) {
var finalOptions = Object.create(baseOptions);
var errors = [];
var tips = [];
finalOptions.warn = function (msg, tip$$1) {
(tip$$1 ? tips : errors).push(msg);
};
if (options) {
// merge custom modules
if (options.modules) {
finalOptions.modules = (baseOptions.modules || []).concat(options.modules);
}
// merge custom directives
if (options.directives) {
finalOptions.directives = extend(
Object.create(baseOptions.directives),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
{
errors.push.apply(errors, detectErrors(compiled.ast));
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
function compileToFunctions (
template,
options,
vm
) {
options = options || {};
/* istanbul ignore if */
{
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
// check cache
var key = options.delimiters
? String(options.delimiters) + template
: template;
if (functionCompileCache[key]) {
return functionCompileCache[key]
}
// compile
var compiled = compile(template, options);
// check compilation errors/tips
{
if (compiled.errors && compiled.errors.length) {
warn(
"Error compiling template:\n\n" + template + "\n\n" +
compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n',
vm
);
}
if (compiled.tips && compiled.tips.length) {
compiled.tips.forEach(function (msg) { return tip(msg, vm); });
}
}
// turn code into functions
var res = {};
var fnGenErrors = [];
res.render = makeFunction(compiled.render, fnGenErrors);
var l = compiled.staticRenderFns.length;
res.staticRenderFns = new Array(l);
for (var i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);
}
// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
{
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn(
"Failed to generate render function:\n\n" +
fnGenErrors.map(function (ref) {
var err = ref.err;
var code = ref.code;
return ((err.toString()) + " in\n\n" + code + "\n");
}).join('\n'),
vm
);
}
}
return (functionCompileCache[key] = res)
}
return {
compile: compile,
compileToFunctions: compileToFunctions
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if ("development" !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.'
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
{
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.'
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:(" + (el.styleBinding) + "),";
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
var modules$1 = [
klass$1,
style$1
];
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives$1 = {
model: model,
text: text,
html: html
};
/* */
var baseOptions = {
expectHTML: true,
modules: modules$1,
directives: directives$1,
isPreTag: isPreTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: genStaticKeys(modules$1)
};
var ref$1 = createCompiler(baseOptions);
var compileToFunctions = ref$1.compileToFunctions;
/* */
var idToTemplate = cached(function (id) {
var el = query(id);
return el && el.innerHTML
});
var mount = Vue$3.prototype.$mount;
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
"development" !== 'production' && warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if ("development" !== 'production' && !template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
{
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
/* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
mark('compile');
}
var ref = compileToFunctions(template, {
shouldDecodeNewlines: shouldDecodeNewlines,
delimiters: options.delimiters
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
/* istanbul ignore if */
if ("development" !== 'production' && config.performance && mark) {
mark('compile end');
measure(((this._name) + " compile"), 'compile', 'compile end');
}
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
var container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue$3.compile = compileToFunctions;
return Vue$3;
}))); | xLua/docs/source/themes/catlib/source/js/vue.js/0 | {
"file_path": "xLua/docs/source/themes/catlib/source/js/vue.js",
"repo_id": "xLua",
"token_count": 101224
} | 2,137 |
/*
(C) 2020 David Lettier
lettier.com
*/
#version 150
uniform sampler2D p3d_Texture0;
uniform sampler2D positionTexture;
uniform vec2 isSmoke;
in vec4 vertexPosition;
in vec4 vertexColor;
in vec2 diffuseCoord;
out vec4 positionOut;
out vec4 smokeMaskOut;
void main() {
positionOut = vertexPosition;
smokeMaskOut = vec4(0.0);
if (isSmoke.x == 1) {
vec4 diffuseColor = texture(p3d_Texture0, diffuseCoord) * vertexColor;
vec2 texSize = textureSize(positionTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 position = texture(positionTexture, texCoord);
if (position.a <= 0.0) {
positionOut = diffuseColor.a > 0.0 ? vertexPosition : vec4(0.0);
} else {
positionOut = mix(position, vertexPosition, diffuseColor.a);
}
smokeMaskOut = diffuseColor * vertexColor;
smokeMaskOut.rgb = vec3(dot(smokeMaskOut.rgb, vec3(1.0 / 3.0)));
}
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/geometry-buffer-2.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/geometry-buffer-2.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 376
} | 0 |
/*
(C) 2019 David Lettier
lettier.com
*/
#version 150
uniform mat4 lensProjection;
uniform sampler2D positionTexture;
uniform sampler2D normalTexture;
uniform sampler2D maskTexture;
uniform vec2 enabled;
out vec4 fragColor;
void main() {
float maxDistance = 8;
float resolution = 0.3;
int steps = 5;
float thickness = 0.5;
vec2 texSize = textureSize(positionTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 uv = vec4(0.0);
vec4 positionFrom = texture(positionTexture, texCoord);
vec4 mask = texture(maskTexture, texCoord);
if ( positionFrom.w <= 0.0
|| enabled.x != 1.0
|| mask.r <= 0.0
) { fragColor = uv; return; }
vec3 unitPositionFrom = normalize(positionFrom.xyz);
vec3 normal = normalize(texture(normalTexture, texCoord).xyz);
vec3 pivot = normalize(reflect(unitPositionFrom, normal));
vec4 positionTo = positionFrom;
vec4 startView = vec4(positionFrom.xyz + (pivot * 0.0), 1.0);
vec4 endView = vec4(positionFrom.xyz + (pivot * maxDistance), 1.0);
vec4 startFrag = startView;
startFrag = lensProjection * startFrag;
startFrag.xyz /= startFrag.w;
startFrag.xy = startFrag.xy * 0.5 + 0.5;
startFrag.xy *= texSize;
vec4 endFrag = endView;
endFrag = lensProjection * endFrag;
endFrag.xyz /= endFrag.w;
endFrag.xy = endFrag.xy * 0.5 + 0.5;
endFrag.xy *= texSize;
vec2 frag = startFrag.xy;
uv.xy = frag / texSize;
float deltaX = endFrag.x - startFrag.x;
float deltaY = endFrag.y - startFrag.y;
float useX = abs(deltaX) >= abs(deltaY) ? 1.0 : 0.0;
float delta = mix(abs(deltaY), abs(deltaX), useX) * clamp(resolution, 0.0, 1.0);
vec2 increment = vec2(deltaX, deltaY) / max(delta, 0.001);
float search0 = 0;
float search1 = 0;
int hit0 = 0;
int hit1 = 0;
float viewDistance = startView.y;
float depth = thickness;
float i = 0;
for (i = 0; i < int(delta); ++i) {
frag += increment;
uv.xy = frag / texSize;
positionTo = texture(positionTexture, uv.xy);
search1 =
mix
( (frag.y - startFrag.y) / deltaY
, (frag.x - startFrag.x) / deltaX
, useX
);
search1 = clamp(search1, 0.0, 1.0);
viewDistance = (startView.y * endView.y) / mix(endView.y, startView.y, search1);
depth = viewDistance - positionTo.y;
if (depth > 0 && depth < thickness) {
hit0 = 1;
break;
} else {
search0 = search1;
}
}
search1 = search0 + ((search1 - search0) / 2.0);
steps *= hit0;
for (i = 0; i < steps; ++i) {
frag = mix(startFrag.xy, endFrag.xy, search1);
uv.xy = frag / texSize;
positionTo = texture(positionTexture, uv.xy);
viewDistance = (startView.y * endView.y) / mix(endView.y, startView.y, search1);
depth = viewDistance - positionTo.y;
if (depth > 0 && depth < thickness) {
hit1 = 1;
search1 = search0 + ((search1 - search0) / 2);
} else {
float temp = search1;
search1 = search1 + ((search1 - search0) / 2);
search0 = temp;
}
}
float visibility =
hit1
* positionTo.w
* ( 1
- max
( dot(-unitPositionFrom, pivot)
, 0
)
)
* ( 1
- clamp
( depth / thickness
, 0
, 1
)
)
* ( 1
- clamp
( length(positionTo - positionFrom)
/ maxDistance
, 0
, 1
)
)
* (uv.x < 0 || uv.x > 1 ? 0 : 1)
* (uv.y < 0 || uv.y > 1 ? 0 : 1);
visibility = clamp(visibility, 0, 1);
uv.ba = vec2(visibility);
fragColor = uv;
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/screen-space-reflection.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/screen-space-reflection.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 1758
} | 1 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Building The Demo | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Building The Demo | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Building The Demo | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="setup.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="running-the-demo.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="building-the-demo">Building The Demo</h2>
<p align="center">
<img src="https://i.imgur.com/PQcDnIu.gif" alt="Building The Demo" title="Building The Demo">
</p>
<p>Before you can try out the demo program, you'll have to build the example code first.</p>
<h3 id="dependencies">Dependencies</h3>
<p>Before you can compile the example code, you'll need to install <a href="https://www.panda3d.org/">Panda3D</a> for your platform. Panda3D is available for Linux, Mac, and Windows.</p>
<h3 id="linux">Linux</h3>
<p>Start by <a href="https://www.panda3d.org/manual/?title=Installing_Panda3D_in_Linux">installing</a> the <a href="https://www.panda3d.org/download/sdk-1-10-9/">Panda3D SDK</a> for your distribution.</p>
<p>Make sure to locate where the Panda3D headers and libraries are. The headers and libraries are most likely in <code>/usr/include/panda3d/</code> and <code>/usr/lib/panda3d/</code> respectively.</p>
<p>Next clone this repository and change directory into it.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb1-1"><a href="#cb1-1"></a><span class="fu">git</span> clone https://github.com/lettier/3d-game-shaders-for-beginners.git</span>
<span id="cb1-2"><a href="#cb1-2"></a><span class="bu">cd</span> 3d-game-shaders-for-beginners/demonstration</span></code></pre></div>
<p>Now compile the source code into an object file.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb2-1"><a href="#cb2-1"></a><span class="ex">g++</span> \</span>
<span id="cb2-2"><a href="#cb2-2"></a> -c src/main.cxx \</span>
<span id="cb2-3"><a href="#cb2-3"></a> -o 3d-game-shaders-for-beginners.o \</span>
<span id="cb2-4"><a href="#cb2-4"></a> -std=gnu++11 \</span>
<span id="cb2-5"><a href="#cb2-5"></a> -O2 \</span>
<span id="cb2-6"><a href="#cb2-6"></a> -I/path/to/python/include/ \</span>
<span id="cb2-7"><a href="#cb2-7"></a> -I/path/to/panda3d/include/</span></code></pre></div>
<p>With the object file created, create the executable by linking the object file to its dependencies.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb3-1"><a href="#cb3-1"></a><span class="ex">g++</span> \</span>
<span id="cb3-2"><a href="#cb3-2"></a> 3d-game-shaders-for-beginners.o \</span>
<span id="cb3-3"><a href="#cb3-3"></a> -o 3d-game-shaders-for-beginners \</span>
<span id="cb3-4"><a href="#cb3-4"></a> -L/path/to/panda3d/lib \</span>
<span id="cb3-5"><a href="#cb3-5"></a> -lp3framework \</span>
<span id="cb3-6"><a href="#cb3-6"></a> -lpanda \</span>
<span id="cb3-7"><a href="#cb3-7"></a> -lpandafx \</span>
<span id="cb3-8"><a href="#cb3-8"></a> -lpandaexpress \</span>
<span id="cb3-9"><a href="#cb3-9"></a> -lpandaphysics \</span>
<span id="cb3-10"><a href="#cb3-10"></a> -lp3dtoolconfig \</span>
<span id="cb3-11"><a href="#cb3-11"></a> -lp3dtool \</span>
<span id="cb3-12"><a href="#cb3-12"></a> -lpthread</span></code></pre></div>
<p>For more help, see the <a href="https://www.panda3d.org/manual/?title=How_to_compile_a_C++_Panda3D_program_on_Linux">Panda3D manual</a>.</p>
<h3 id="mac">Mac</h3>
<p>Start by installing the <a href="https://www.panda3d.org/download/sdk-1-10-9/">Panda3D SDK</a> for Mac.</p>
<p>Make sure to locate where the Panda3D headers and libraries are.</p>
<p>Next clone this repository and change directory into it.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb4-1"><a href="#cb4-1"></a><span class="fu">git</span> clone https://github.com/lettier/3d-game-shaders-for-beginners.git</span>
<span id="cb4-2"><a href="#cb4-2"></a><span class="bu">cd</span> 3d-game-shaders-for-beginners</span></code></pre></div>
<p>Now compile the source code into an object file. You'll have to find where the Python 2.7 and Panda3D include directories are.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb5-1"><a href="#cb5-1"></a><span class="fu">clang</span>++ \</span>
<span id="cb5-2"><a href="#cb5-2"></a> -c main.cxx \</span>
<span id="cb5-3"><a href="#cb5-3"></a> -o 3d-game-shaders-for-beginners.o \</span>
<span id="cb5-4"><a href="#cb5-4"></a> -std=gnu++11 \</span>
<span id="cb5-5"><a href="#cb5-5"></a> -g \</span>
<span id="cb5-6"><a href="#cb5-6"></a> -O2 \</span>
<span id="cb5-7"><a href="#cb5-7"></a> -I/path/to/python/include/ \</span>
<span id="cb5-8"><a href="#cb5-8"></a> -I/path/to/panda3d/include/</span></code></pre></div>
<p>With the object file created, create the executable by linking the object file to its dependencies. You'll need to track down where the Panda3D libraries are located.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb6-1"><a href="#cb6-1"></a><span class="fu">clang</span>++ \</span>
<span id="cb6-2"><a href="#cb6-2"></a> 3d-game-shaders-for-beginners.o \</span>
<span id="cb6-3"><a href="#cb6-3"></a> -o 3d-game-shaders-for-beginners \</span>
<span id="cb6-4"><a href="#cb6-4"></a> -L/path/to/panda3d/lib \</span>
<span id="cb6-5"><a href="#cb6-5"></a> -lp3framework \</span>
<span id="cb6-6"><a href="#cb6-6"></a> -lpanda \</span>
<span id="cb6-7"><a href="#cb6-7"></a> -lpandafx \</span>
<span id="cb6-8"><a href="#cb6-8"></a> -lpandaexpress \</span>
<span id="cb6-9"><a href="#cb6-9"></a> -lpandaphysics \</span>
<span id="cb6-10"><a href="#cb6-10"></a> -lp3dtoolconfig \</span>
<span id="cb6-11"><a href="#cb6-11"></a> -lp3dtool \</span>
<span id="cb6-12"><a href="#cb6-12"></a> -lpthread</span></code></pre></div>
<p>For more help, see the <a href="https://www.panda3d.org/manual/?title=How_to_compile_a_C++_Panda3D_program_on_macOS">Panda3D manual</a>.</p>
<h3 id="windows">Windows</h3>
<p>Start by <a href="https://www.panda3d.org/manual/?title=Installing_Panda3D_in_Windows">installing</a> the <a href="https://www.panda3d.org/download/sdk-1-10-9/">Panda3D SDK</a> for Windows.</p>
<p>Make sure to locate where the Panda3D headers and libraries are.</p>
<p>Next clone this repository and change directory into it.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode bash"><code class="sourceCode bash"><span id="cb7-1"><a href="#cb7-1"></a><span class="fu">git</span> clone https://github.com/lettier/3d-game-shaders-for-beginners.git</span>
<span id="cb7-2"><a href="#cb7-2"></a><span class="bu">cd</span> 3d-game-shaders-for-beginners</span></code></pre></div>
<p>For more help, see the <a href="https://www.panda3d.org/manual/?title=Running_your_Program&language=cxx">Panda3D manual</a>.</p>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="setup.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="running-the-demo.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/building-the-demo.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/building-the-demo.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 5236
} | 2 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Lookup Table | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Lookup Table | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Lookup Table | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="film-grain.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="gamma-correction.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="lookup-table-lut">Lookup Table (LUT)</h2>
<p align="center">
<img src="https://i.imgur.com/WrPzVlW.gif" alt="LUT" title="LUT">
</p>
<p>The lookup table or LUT shader allows you to transform the colors of your game using an image editor like the <a href="https://www.gimp.org/">GIMP</a>. From color grading to turning day into night, the LUT shader is a handy tool for tweaking the look of your game.</p>
<p align="center">
<img src="https://i.imgur.com/NPdJNGj.png" alt="Neutral LUT" title="Neutral LUT">
</p>
<p>Before you can get started, you'll need to find a neutral LUT image. Neutral meaning that it leaves the fragment colors unchanged. The LUT needs to be 256 pixels wide by 16 pixels tall and contain 16 blocks with each block being 16 by 16 pixels.</p>
<p>The LUT is mapped out into 16 blocks. Each block has a different level of blue. As you move across the blocks, from left to right, the amount of blue increases. You can see the amount of blue in each block's upper-left corner. Within each block, the amount of red increases as you move from left to right and the amount of green increases as you move from top to bottom. The upper-left corner of the first block is black since every RGB channel is zero. The lower-right corner of the last block is white since every RGB channel is one.</p>
<p align="center">
<img src="https://i.imgur.com/KyxPm1r.png" alt="LUT And Screenshot" title="LUT And Screenshot">
</p>
<p>With the neutral LUT in hand, take a screenshot of your game and open it in your image editor. Add the neutral LUT as a new layer and merge it with the screenshot. As you manipulate the colors of the screenshot, the LUT will be altered in the same way. When you're done editing, select only the LUT and save it as a new image. You now have your new lookup table and can begin writing your shader.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a> vec2 texSize = textureSize(colorTexture, <span class="dv">0</span>).xy;</span>
<span id="cb1-4"><a href="#cb1-4"></a></span>
<span id="cb1-5"><a href="#cb1-5"></a> vec4 color = texture(colorTexture, gl_FragCoord.xy / texSize);</span>
<span id="cb1-6"><a href="#cb1-6"></a></span>
<span id="cb1-7"><a href="#cb1-7"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The LUT shader is a screen space technique. Therefore, sample the scene's color at the current fragment or screen position.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a> <span class="dt">float</span> u = floor(color.b * <span class="fl">15.0</span>) / <span class="fl">15.0</span> * <span class="fl">240.0</span>;</span>
<span id="cb2-4"><a href="#cb2-4"></a> u = (floor(color.r * <span class="fl">15.0</span>) / <span class="fl">15.0</span> * <span class="fl">15.0</span>) + u;</span>
<span id="cb2-5"><a href="#cb2-5"></a> u /= <span class="fl">255.0</span>;</span>
<span id="cb2-6"><a href="#cb2-6"></a></span>
<span id="cb2-7"><a href="#cb2-7"></a> <span class="dt">float</span> v = ceil(color.g * <span class="fl">15.0</span>);</span>
<span id="cb2-8"><a href="#cb2-8"></a> v /= <span class="fl">15.0</span>;</span>
<span id="cb2-9"><a href="#cb2-9"></a> v = <span class="fl">1.0</span> - v;</span>
<span id="cb2-10"><a href="#cb2-10"></a></span>
<span id="cb2-11"><a href="#cb2-11"></a> <span class="co">// ...</span></span></code></pre></div>
<p>In order to transform the current fragment's color, using the LUT, you'll need to map the color to two UV coordinates on the lookup table texture. The first mapping (shown up above) is to the nearest left or lower bound block location and the second mapping (shown below) is to the nearest right or upper bound block mapping. At the end, you'll combine these two mappings to create the final color transformation.</p>
<p align="center">
<img src="https://i.imgur.com/j2JmyQ2.png" alt="RGB Channel Mapping" title="RGB Channel Mapping">
</p>
<p>Each of the red, green, and blue channels maps to one of 16 possibilities in the LUT. The blue channel maps to one of the 16 upper-left block corners. After the blue channel maps to a block, the red channel maps to one of the 16 horizontal pixel positions within the block and the green channel maps to one of the 16 vertical pixel positions within the block. These three mappings will determine the UV coordinate you'll need to sample a color from the LUT.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span>
<span id="cb3-2"><a href="#cb3-2"></a></span>
<span id="cb3-3"><a href="#cb3-3"></a> u /= <span class="fl">255.0</span>;</span>
<span id="cb3-4"><a href="#cb3-4"></a></span>
<span id="cb3-5"><a href="#cb3-5"></a> v /= <span class="fl">15.0</span>;</span>
<span id="cb3-6"><a href="#cb3-6"></a> v = <span class="fl">1.0</span> - v;</span>
<span id="cb3-7"><a href="#cb3-7"></a></span>
<span id="cb3-8"><a href="#cb3-8"></a> <span class="co">// ...</span></span></code></pre></div>
<p>To calculate the final U coordinate, divide it by 255 since the LUT is 256 pixels wide and U ranges from zero to one. To calculate the final V coordinate, divide it by 15 since the LUT is 16 pixels tall and V ranges from zero to one. You'll also need to subtract the normalized V coordinate from one since V ranges from zero at the bottom to one at the top while the green channel ranges from zero at the top to 15 at the bottom.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span>
<span id="cb4-2"><a href="#cb4-2"></a></span>
<span id="cb4-3"><a href="#cb4-3"></a> vec3 left = texture(lookupTableTexture, vec2(u, v)).rgb;</span>
<span id="cb4-4"><a href="#cb4-4"></a></span>
<span id="cb4-5"><a href="#cb4-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Using the UV coordinates, sample a color from the lookup table. This is the nearest left block color.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a> <span class="co">// ...</span></span>
<span id="cb5-2"><a href="#cb5-2"></a></span>
<span id="cb5-3"><a href="#cb5-3"></a> u = ceil(color.b * <span class="fl">15.0</span>) / <span class="fl">15.0</span> * <span class="fl">240.0</span>;</span>
<span id="cb5-4"><a href="#cb5-4"></a> u = (ceil(color.r * <span class="fl">15.0</span>) / <span class="fl">15.0</span> * <span class="fl">15.0</span>) + u;</span>
<span id="cb5-5"><a href="#cb5-5"></a> u /= <span class="fl">255.0</span>;</span>
<span id="cb5-6"><a href="#cb5-6"></a></span>
<span id="cb5-7"><a href="#cb5-7"></a> v = <span class="fl">1.0</span> - (ceil(color.g * <span class="fl">15.0</span>) / <span class="fl">15.0</span>);</span>
<span id="cb5-8"><a href="#cb5-8"></a></span>
<span id="cb5-9"><a href="#cb5-9"></a> vec3 right = texture(lookupTableTexture, vec2(u, v)).rgb;</span>
<span id="cb5-10"><a href="#cb5-10"></a></span>
<span id="cb5-11"><a href="#cb5-11"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Now you'll need to calculate the UV coordinates for the nearest right block color. Notice how <code>ceil</code> or ceiling is being used now instead of <code>floor</code>.</p>
<p align="center">
<img src="https://i.imgur.com/uciq7Um.png" alt="Mixing" title="Mixing">
</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a> <span class="co">// ...</span></span>
<span id="cb6-2"><a href="#cb6-2"></a></span>
<span id="cb6-3"><a href="#cb6-3"></a> color.r = mix(left.r, right.r, fract(color.r * <span class="fl">15.0</span>));</span>
<span id="cb6-4"><a href="#cb6-4"></a> color.g = mix(left.g, right.g, fract(color.g * <span class="fl">15.0</span>));</span>
<span id="cb6-5"><a href="#cb6-5"></a> color.b = mix(left.b, right.b, fract(color.b * <span class="fl">15.0</span>));</span>
<span id="cb6-6"><a href="#cb6-6"></a></span>
<span id="cb6-7"><a href="#cb6-7"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Not every channel will map perfectly to one of its 16 possibilities. For example, <code>0.5</code> doesn't map perfectly. At the lower bound (<code>floor</code>), it maps to <code>0.4666666666666667</code> and at the upper bound (<code>ceil</code>), it maps to <code>0.5333333333333333</code>. Compare that with <code>0.4</code> which maps to <code>0.4</code> at the lower bound and <code>0.4</code> at the upper bound. For those channels which do not map perfectly, you'll need to mix the left and right sides based on where the channel falls between its lower and upper bound. For <code>0.5</code>, it falls directly between them making the final color a mixture of half left and half right. However, for <code>0.132</code> the mixture will be 98% right and 2% left since the fractional part of <code>0.123</code> times <code>15.0</code> is <code>0.98</code>.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb7-1"><a href="#cb7-1"></a> <span class="co">// ...</span></span>
<span id="cb7-2"><a href="#cb7-2"></a></span>
<span id="cb7-3"><a href="#cb7-3"></a> fragColor = color;</span>
<span id="cb7-4"><a href="#cb7-4"></a></span>
<span id="cb7-5"><a href="#cb7-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Set the fragment color to the final mix and you're done.</p>
<h3 id="source">Source</h3>
<ul>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/lookup-table.frag" target="_blank" rel="noopener noreferrer">lookup-table.frag</a></li>
</ul>
<h2 id="copyright">Copyright</h2>
<p>(C) 2020 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="film-grain.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="gamma-correction.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/lookup-table.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/lookup-table.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 6356
} | 3 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Texturing | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Texturing | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Texturing | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="render-to-texture.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="lighting.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="texturing">Texturing</h2>
<p align="center">
<img src="https://i.imgur.com/cqbgT8b.gif" alt="Diffuse Texture Only" title="Diffuse Texture Only">
</p>
<p>Texturing involves mapping some color or some other kind of vector to a fragment using UV coordinates. Both U and V range from zero to one. Each vertex gets a UV coordinate and this is outputted in the vertex shader.</p>
<p align="center">
<img src="https://i.imgur.com/JjAdNfk.png" alt="UV Interpolation" title="UV Interpolation">
</p>
<p>The fragment shader receives the UV coordinate interpolated. Interpolated meaning the UV coordinate for the fragment is somewhere between the UV coordinates for the vertexes that make up the triangle face.</p>
<h3 id="vertex">Vertex</h3>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a><span class="er">#version 150</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a>uniform mat4 p3d_ModelViewProjectionMatrix;</span>
<span id="cb1-4"><a href="#cb1-4"></a></span>
<span id="cb1-5"><a href="#cb1-5"></a>in vec2 p3d_MultiTexCoord0;</span>
<span id="cb1-6"><a href="#cb1-6"></a></span>
<span id="cb1-7"><a href="#cb1-7"></a>in vec4 p3d_Vertex;</span>
<span id="cb1-8"><a href="#cb1-8"></a></span>
<span id="cb1-9"><a href="#cb1-9"></a>out vec2 texCoord;</span>
<span id="cb1-10"><a href="#cb1-10"></a></span>
<span id="cb1-11"><a href="#cb1-11"></a><span class="dt">void</span> main()</span>
<span id="cb1-12"><a href="#cb1-12"></a>{</span>
<span id="cb1-13"><a href="#cb1-13"></a> texCoord = p3d_MultiTexCoord0;</span>
<span id="cb1-14"><a href="#cb1-14"></a></span>
<span id="cb1-15"><a href="#cb1-15"></a> gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;</span>
<span id="cb1-16"><a href="#cb1-16"></a>}</span></code></pre></div>
<p>Here you see the vertex shader outputting the texture coordinate to the fragment shader. Notice how it's a two dimensional vector. One dimension for U and one for V.</p>
<h3 id="fragment">Fragment</h3>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a><span class="er">#version 150</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a>uniform sampler2D p3d_Texture0;</span>
<span id="cb2-4"><a href="#cb2-4"></a></span>
<span id="cb2-5"><a href="#cb2-5"></a>in vec2 texCoord;</span>
<span id="cb2-6"><a href="#cb2-6"></a></span>
<span id="cb2-7"><a href="#cb2-7"></a>out vec2 fragColor;</span>
<span id="cb2-8"><a href="#cb2-8"></a></span>
<span id="cb2-9"><a href="#cb2-9"></a><span class="dt">void</span> main()</span>
<span id="cb2-10"><a href="#cb2-10"></a>{</span>
<span id="cb2-11"><a href="#cb2-11"></a> texColor = texture(p3d_Texture0, texCoord);</span>
<span id="cb2-12"><a href="#cb2-12"></a></span>
<span id="cb2-13"><a href="#cb2-13"></a> fragColor = texColor;</span>
<span id="cb2-14"><a href="#cb2-14"></a>}</span></code></pre></div>
<p>Here you see the fragment shader looking up the color at its UV coordinate and outputting that as the fragment color.</p>
<h4 id="screen-filled-texture">Screen Filled Texture</h4>
<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="er">#version 150</span></span>
<span id="cb3-2"><a href="#cb3-2"></a></span>
<span id="cb3-3"><a href="#cb3-3"></a>uniform sampler2D screenSizedTexture;</span>
<span id="cb3-4"><a href="#cb3-4"></a></span>
<span id="cb3-5"><a href="#cb3-5"></a>out vec2 fragColor;</span>
<span id="cb3-6"><a href="#cb3-6"></a></span>
<span id="cb3-7"><a href="#cb3-7"></a><span class="dt">void</span> main()</span>
<span id="cb3-8"><a href="#cb3-8"></a>{</span>
<span id="cb3-9"><a href="#cb3-9"></a> vec2 texSize = textureSize(texture, <span class="dv">0</span>).xy;</span>
<span id="cb3-10"><a href="#cb3-10"></a> vec2 texCoord = gl_FragCoord.xy / texSize;</span>
<span id="cb3-11"><a href="#cb3-11"></a></span>
<span id="cb3-12"><a href="#cb3-12"></a> texColor = texture(screenSizedTexture, texCoord);</span>
<span id="cb3-13"><a href="#cb3-13"></a></span>
<span id="cb3-14"><a href="#cb3-14"></a> fragColor = texColor;</span>
<span id="cb3-15"><a href="#cb3-15"></a>}</span></code></pre></div>
<p>When performing render to texture, the mesh is a flat rectangle with the same aspect ratio as the screen. Because of this, you can calculate the UV coordinates knowing only A) the width and height of the screen sized texture being UV mapped to the rectangle and B) the fragment's x and y coordinate. To map x to U, divide x by the width of the input texture. Similarly, to map y to V, divide y by the height of the input texture. You'll see this technique used in the example code.</p>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="render-to-texture.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="lighting.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/texturing.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/texturing.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 4395
} | 4 |
[:arrow_backward:](reference-frames.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](render-to-texture.md)
# 3D Game Shaders For Beginners
## GLSL
<p align="center">
<img src="https://i.imgur.com/7b5MCBG.gif" alt="" title="">
</p>
Instead of using the
[fixed-function](https://en.wikipedia.org/wiki/Fixed-function)
pipeline,
you'll be using the programmable GPU rendering pipeline.
Since it is programmable, it is up to you to supply the programming in the form of shaders.
A shader is a (typically small) program you write using a syntax reminiscent of C.
The programmable GPU rendering pipeline has various different stages that you can program with shaders.
The different types of shaders include vertex, tessellation, geometry, fragment, and compute.
You'll only need to focus on the vertex and fragment stages for the techniques below.
```c
#version 150
void main() {}
```
Here is a bare-bones GLSL shader consisting of the GLSL version number and the main function.
```c
#version 150
uniform mat4 p3d_ModelViewProjectionMatrix;
in vec4 p3d_Vertex;
void main()
{
gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;
}
```
Here is a stripped down GLSL vertex shader that transforms an incoming vertex to clip space
and outputs this new position as the vertex's homogeneous position.
The `main` procedure doesn't return anything since it is `void` and the `gl_Position` variable is a built-in output.
Take note of the keywords `uniform` and `in`.
The `uniform` keyword means this global variable is the same for all vertexes.
Panda3D sets the `p3d_ModelViewProjectionMatrix` for you and it is the same matrix for each vertex.
The `in` keyword means this global variable is being given to the shader.
The vertex shader receives each vertex that makes up the geometry the vertex shader is attached to.
```c
#version 150
out vec4 fragColor;
void main() {
fragColor = vec4(0, 1, 0, 1);
}
```
Here is a stripped down GLSL fragment shader that outputs the fragment color as solid green.
Keep in mind that a fragment affects at most one screen pixel but a single pixel can be affected by many fragments.
Take note of the `out` keyword.
The `out` keyword means this global variable is being set by the shader.
The name `fragColor` is arbitrary so feel free to choose a different one.
<p align="center">
<img src="https://i.imgur.com/V25UzMa.gif" alt="Output of the stripped down shaders." title="Output of the stripped down shaders.">
</p>
This is the output of the two shaders shown above.
## Copyright
(C) 2019 David Lettier
<br>
[lettier.com](https://www.lettier.com)
[:arrow_backward:](reference-frames.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](render-to-texture.md)
| 3d-game-shaders-for-beginners/sections/glsl.md/0 | {
"file_path": "3d-game-shaders-for-beginners/sections/glsl.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 864
} | 5 |
[:arrow_backward:](bloom.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](motion-blur.md)
# 3D Game Shaders For Beginners
## Screen Space Ambient Occlusion (SSAO)
<p align="center">
<img src="https://i.imgur.com/o7lCukD.gif" alt="SSAO" title="SSAO">
</p>
SSAO is one of those effects you never knew you needed and can't live without once you have it.
It can take a scene from mediocre to wow!
For fairly static scenes, you can bake ambient occlusion into a texture but for more dynamic scenes, you'll need a shader.
SSAO is one of the more fairly involved shading techniques, but once you pull it off, you'll feel like a shader master.
By using only a handful of textures, SSAO can approximate the
[ambient occlusion](https://en.wikipedia.org/wiki/Ambient_occlusion)
of a scene.
This is faster than trying to compute the ambient occlusion by going through all of the scene's geometry.
These handful of textures all originate in screen space giving screen space ambient occlusion its name.
### Inputs
The SSAO shader will need the following inputs.
- Vertex position vectors in view space.
- Vertex normal vectors in view space.
- Sample vectors in tangent space.
- Noise vectors in tangent space.
- The camera lens' projection matrix.
### Vertex Positions
<p align="center">
<img src="https://i.imgur.com/gr7IxKv.png" alt="Panda3D Vertex Positions" title="Panda3D Vertex Positions">
</p>
Storing the vertex positions into a framebuffer texture is not a necessity.
You can recreate them from the [camera's depth buffer](http://theorangeduck.com/page/pure-depth-ssao).
This being a beginners guide, I'll avoid this optimization and keep it straight forward.
Feel free to use the depth buffer, however, for your implementation.
```cpp
PT(Texture) depthTexture =
new Texture("depthTexture");
depthTexture->set_format
( Texture::Format::F_depth_component32
);
PT(GraphicsOutput) depthBuffer =
graphicsOutput->make_texture_buffer
( "depthBuffer"
, 0
, 0
, depthTexture
);
depthBuffer->set_clear_color
( LVecBase4f(0, 0, 0, 0)
);
NodePath depthCameraNP =
window->make_camera();
DCAST(Camera, depthCameraNP.node())->set_lens
( window->get_camera(0)->get_lens()
);
PT(DisplayRegion) depthBufferRegion =
depthBuffer->make_display_region
( 0
, 1
, 0
, 1
);
depthBufferRegion->set_camera(depthCameraNP);
```
If you do decide to use the depth buffer, here's how you can set it up using Panda3D.
```c
in vec4 vertexPosition;
out vec4 fragColor;
void main() {
fragColor = vertexPosition;
}
```
Here's the simple shader used to render out the view space vertex positions into a framebuffer texture.
The more involved work is setting up the framebuffer texture such that the fragment vector components it receives
are not clamped to `[0, 1]` and that each one has a high enough precision (a high enough number of bits).
For example, if a particular interpolated vertex position is `<-139.444444566, 0.00000034343, 2.5>`,
you don't want it stored into the texture as `<0.0, 0.0, 1.0>`.
```c
// ...
FrameBufferProperties fbp = FrameBufferProperties::get_default();
// ...
fbp.set_rgba_bits(32, 32, 32, 32);
fbp.set_rgb_color(true);
fbp.set_float_color(true);
// ...
```
Here's how the example code sets up the framebuffer texture to store the vertex positions.
It wants 32 bits per red, green, blue, and alpha components and disables clamping the values to `[0, 1]`
The `set_rgba_bits(32, 32, 32, 32)` call sets the bits and also disables the clamping.
```c
glTexImage2D
( GL_TEXTURE_2D
, 0
, GL_RGB32F
, 1200
, 900
, 0
, GL_RGB
, GL_FLOAT
, nullptr
);
```
Here's the equivalent OpenGL call.
`GL_RGB32F` sets the bits and also disables the clamping.
<blockquote>
If the color buffer is fixed-point, the components of the source and destination
values and blend factors are each clamped to [0, 1] or [−1, 1] respectively for
an unsigned normalized or signed normalized color buffer prior to evaluating the blend
equation.
If the color buffer is floating-point, no clamping occurs.
<br>
<br>
<footer>
<a href="https://www.khronos.org/registry/OpenGL/specs/gl/glspec44.core.pdf">Source</a>
</footer>
</blockquote>
<p align="center">
<img src="https://i.imgur.com/V4nETME.png" alt="OpenGL Vertex Positions" title="OpenGL Vertex Positions">
</p>
Here you see the vertex positions with y being the up vector.
Recall that Panda3D sets z as the up vector but OpenGL uses y as the up vector.
The position shader outputs the vertex positions with z being up since Panda3D
was configured with `gl-coordinate-system default`.
### Vertex Normals
<p align="center">
<img src="https://i.imgur.com/ilnbkzq.gif" alt="Panda3d Vertex Normals" title="Panda3d Vertex Normals">
</p>
You'll need the vertex normals to correctly orient the samples you'll take in the SSAO shader.
The example code generates multiple sample vectors distributed in a hemisphere
but you could use a sphere and do away with the need for normals all together.
```c
in vec3 vertexNormal;
out vec4 fragColor;
void main() {
vec3 normal = normalize(vertexNormal);
fragColor = vec4(normal, 1);
}
```
Like the position shader, the normal shader is simple as well.
Be sure to normalize the vertex normal and remember that they are in view space.
<p align="center">
<img src="https://i.imgur.com/ucdx9Kp.gif" alt="OpenGL Vertex Normals" title="OpenGL Vertex Normals">
</p>
Here you see the vertex normals with y being the up vector.
Recall that Panda3D sets z as the up vector but OpenGL uses y as the up vector.
The normal shader outputs the vertex positions with z being up since Panda3D
was configured with `gl-coordinate-system default`.
<p align="center">
<img src="https://i.imgur.com/fiHXBex.gif" alt="SSAO using the normal maps." title="SSAO using the normal maps.">
</p>
Here you see SSAO being used with the normal maps instead of the vertex normals.
This adds an extra level of detail and will pair nicely with the normal mapped lighting.
```c
// ...
normal =
normalize
( normalTex.rgb
* 2.0
- 1.0
);
normal =
normalize
( mat3
( tangent
, binormal
, vertexNormal
)
* normal
);
// ...
```
To use the normal maps instead,
you'll need to transform the normal mapped normals from tangent space to view space
just like you did in the lighting calculations.
### Samples
To determine the amount of ambient occlusion for any particular fragment,
you'll need to sample the surrounding area.
The more samples you use, the better the approximation at the cost of performance.
```cpp
// ...
for (int i = 0; i < numberOfSamples; ++i) {
LVecBase3f sample =
LVecBase3f
( randomFloats(generator) * 2.0 - 1.0
, randomFloats(generator) * 2.0 - 1.0
, randomFloats(generator)
).normalized();
float rand = randomFloats(generator);
sample[0] *= rand;
sample[1] *= rand;
sample[2] *= rand;
float scale = (float) i / (float) numberOfSamples;
scale = lerp(0.1, 1.0, scale * scale);
sample[0] *= scale;
sample[1] *= scale;
sample[2] *= scale;
ssaoSamples.push_back(sample);
}
// ...
```
The example code generates a number of random samples distributed in a hemisphere.
These `ssaoSamples` will be sent to the SSAO shader.
```cpp
LVecBase3f sample =
LVecBase3f
( randomFloats(generator) * 2.0 - 1.0
, randomFloats(generator) * 2.0 - 1.0
, randomFloats(generator) * 2.0 - 1.0
).normalized();
```
If you'd like to distribute your samples in a sphere instead,
change the random `z` component to range from negative one to one.
### Noise
```c
// ...
for (int i = 0; i < numberOfNoise; ++i) {
LVecBase3f noise =
LVecBase3f
( randomFloats(generator) * 2.0 - 1.0
, randomFloats(generator) * 2.0 - 1.0
, 0.0
);
ssaoNoise.push_back(noise);
}
// ...
```
To get a good sweep of the sampled area, you'll need to generate some noise vectors.
These noise vectors will randomly tilt the hemisphere around the current fragment.
### Ambient Occlusion
<p align="center">
<img src="https://i.imgur.com/KKt74VE.gif" alt="SSAO Texture" title="SSAO Texture">
</p>
SSAO works by sampling the view space around a fragment.
The more samples that are below a surface, the darker the fragment color.
These samples are positioned at the fragment and pointed in the general direction of the vertex normal.
Each sample is used to look up a position in the position framebuffer texture.
The position returned is compared to the sample.
If the sample is farther away from the camera than the position, the sample counts towards the fragment being occluded.
<p align="center">
<img src="https://i.imgur.com/Nm4CJDN.gif" alt="SSAO Sampling" title="SSAO Sampling">
</p>
Here you see the space above the surface being sampled for occlusion.
```c
// ...
float radius = 1;
float bias = 0.01;
float magnitude = 1.5;
float contrast = 1.5;
// ...
```
Like some of the other techniques,
the SSAO shader has a few control knobs you can tweak to get the exact look you're going for.
The `bias` adds to the sample's distance from the camera.
You can use the bias to combat "acne".
The `radius` increases or decreases the coverage area of the sample space.
The `magnitude` either lightens or darkens the occlusion map.
The `contrast` either washes out or increases the starkness of the occlusion map.
```c
// ...
vec4 position = texture(positionTexture, texCoord);
vec3 normal = normalize(texture(normalTexture, texCoord).xyz);
int noiseX = int(gl_FragCoord.x - 0.5) % 4;
int noiseY = int(gl_FragCoord.y - 0.5) % 4;
vec3 random = noise[noiseX + (noiseY * 4)];
// ...
```
Retrieve the position, normal, and random vector for later use.
Recall that the example code created a set number of random vectors.
The random vector is chosen based on the current fragment's screen position.
```c
// ...
vec3 tangent = normalize(random - normal * dot(random, normal));
vec3 binormal = cross(normal, tangent);
mat3 tbn = mat3(tangent, binormal, normal);
// ...
```
Using the random and normal vectors, assemble the tangent, binormal, and normal matrix.
You'll need this matrix to transform the sample vectors from tangent space to view space.
```c
// ...
float occlusion = NUM_SAMPLES;
for (int i = 0; i < NUM_SAMPLES; ++i) {
// ...
}
// ...
```
With the matrix in hand, the shader can now loop through the samples, subtracting how many are not occluded.
```c
// ...
vec3 samplePosition = tbn * samples[i];
samplePosition = position.xyz + samplePosition * radius;
// ...
```
Using the matrix, position the sample near the vertex/fragment position and scale it by the radius.
```c
// ...
vec4 offsetUV = vec4(samplePosition, 1.0);
offsetUV = lensProjection * offsetUV;
offsetUV.xyz /= offsetUV.w;
offsetUV.xy = offsetUV.xy * 0.5 + 0.5;
// ...
```
Using the sample's position in view space, transform it from view space to clip space to UV space.
```c
-1 * 0.5 + 0.5 = 0
1 * 0.5 + 0.5 = 1
```
Recall that clip space components range from negative one to one and that UV coordinates range from zero to one.
To transform clip space coordinates to UV coordinates, multiply by one half and add one half.
```c
// ...
vec4 offsetPosition = texture(positionTexture, offsetUV.xy);
float occluded = 0;
if (samplePosition.y + bias <= offsetPosition.y) { occluded = 0; } else { occluded = 1; }
// ...
```
Using the offset UV coordinates,
created by projecting the 3D sample onto the 2D position texture,
find the corresponding position vector.
This takes you from view space to clip space to UV space back to view space.
The shader takes this round trip to find out if some geometry is behind, at, or in front of this sample.
If the sample is in front of or at some geometry, this sample doesn't count towards the fragment being occluded.
If the sample is behind some geometry, this sample counts towards the fragment being occluded.
```c
// ...
float intensity =
smoothstep
( 0.0
, 1.0
, radius
/ abs(position.y - offsetPosition.y)
);
occluded *= intensity;
occlusion -= occluded;
// ...
```
Now weight this sampled position by how far it is inside or outside the radius.
Finally, subtract this sample from the occlusion factor since it assumes all of the samples are occluded before the loop.
```c
// ...
occlusion /= NUM_SAMPLES;
// ...
fragColor = vec4(vec3(occlusion), position.a);
// ...
```
Divide the occluded count by the number of samples to scale the occlusion factor from `[0, NUM_SAMPLES]` to `[0, 1]`.
Zero means full occlusion and one means no occlusion.
Now assign the occlusion factor to the fragment's color and you're done.
```c
// ...
fragColor = vec4(vec3(occlusion), position.a);
// ...
```
For the demo's purposes,
the example code sets the alpha channel to alpha channel of the position framebuffer texture to avoid covering up the background.
### Blurring
<p align="center">
<img src="https://i.imgur.com/QsqOhFR.gif" alt="SSAO Blur Texture" title="SSAO Blur Texture">
</p>
The SSAO framebuffer texture is noisy as is.
You'll want to blur it to remove the noise.
Refer back to the section on [blurring](blur.md).
For the best results, use a median or Kuwahara filter to preserve the sharp edges.
### Ambient Color
```c
// ...
vec2 ssaoBlurTexSize = textureSize(ssaoBlurTexture, 0).xy;
vec2 ssaoBlurTexCoord = gl_FragCoord.xy / ssaoBlurTexSize;
float ssao = texture(ssaoBlurTexture, ssaoBlurTexCoord).r;
vec4 ambient = p3d_Material.ambient * p3d_LightModel.ambient * diffuseTex * ssao;
// ...
```
The final stop for SSAO is back in the lighting calculation.
Here you see the occlusion factor being looked up in the
SSAO framebuffer texture and then included in the ambient light calculation.
### Source
- [main.cxx](../demonstration/src/main.cxx)
- [basic.vert](../demonstration/shaders/vertex/basic.vert)
- [base.vert](../demonstration/shaders/vertex/base.vert)
- [base.frag](../demonstration/shaders/fragment/base.frag)
- [position.frag](../demonstration/shaders/fragment/position.frag)
- [normal.frag](../demonstration/shaders/fragment/normal.frag)
- [ssao.frag](../demonstration/shaders/fragment/ssao.frag)
- [median-filter.frag](../demonstration/shaders/fragment/median-filter.frag)
- [kuwahara-filter.frag](../demonstration/shaders/fragment/kuwahara-filter.frag)
## Copyright
(C) 2019 David Lettier
<br>
[lettier.com](https://www.lettier.com)
[:arrow_backward:](bloom.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](motion-blur.md)
| 3d-game-shaders-for-beginners/sections/ssao.md/0 | {
"file_path": "3d-game-shaders-for-beginners/sections/ssao.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 5146
} | 6 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef air_RpcLibAdaptorsBase_hpp
#define air_RpcLibAdaptorsBase_hpp
#include "common/Common.hpp"
#include "common/CommonStructs.hpp"
#include "physics/Kinematics.hpp"
#include "physics/Environment.hpp"
#include "common/ImageCaptureBase.hpp"
#include "safety/SafetyEval.hpp"
#include "api/WorldSimApiBase.hpp"
#include "common/common_utils/WindowsApisCommonPre.hpp"
#include "rpc/msgpack.hpp"
#include "common/common_utils/WindowsApisCommonPost.hpp"
namespace msr
{
namespace airlib_rpclib
{
class RpcLibAdaptorsBase
{
public:
template <typename TSrc, typename TDest>
static void to(const std::vector<TSrc>& s, std::vector<TDest>& d)
{
d.clear();
for (size_t i = 0; i < s.size(); ++i)
d.push_back(s.at(i).to());
}
template <typename TSrc, typename TDest>
static void from(const std::vector<TSrc>& s, std::vector<TDest>& d)
{
d.clear();
for (size_t i = 0; i < s.size(); ++i)
d.push_back(TDest(s.at(i)));
}
struct Vector2r
{
msr::airlib::real_T x_val = 0, y_val = 0;
MSGPACK_DEFINE_MAP(x_val, y_val);
Vector2r()
{
}
Vector2r(const msr::airlib::Vector2r& s)
{
x_val = s.x();
y_val = s.y();
}
msr::airlib::Vector2r to() const
{
return msr::airlib::Vector2r(x_val, y_val);
}
};
struct Vector3r
{
msr::airlib::real_T x_val = 0, y_val = 0, z_val = 0;
MSGPACK_DEFINE_MAP(x_val, y_val, z_val);
Vector3r()
{
}
Vector3r(const msr::airlib::Vector3r& s)
{
x_val = s.x();
y_val = s.y();
z_val = s.z();
}
msr::airlib::Vector3r to() const
{
return msr::airlib::Vector3r(x_val, y_val, z_val);
}
};
struct CollisionInfo
{
bool has_collided = false;
Vector3r normal;
Vector3r impact_point;
Vector3r position;
msr::airlib::real_T penetration_depth = 0;
msr::airlib::TTimePoint time_stamp = 0;
std::string object_name;
int object_id = -1;
MSGPACK_DEFINE_MAP(has_collided, penetration_depth, time_stamp, normal, impact_point, position, object_name, object_id);
CollisionInfo()
{
}
CollisionInfo(const msr::airlib::CollisionInfo& s)
{
has_collided = s.has_collided;
normal = s.normal;
impact_point = s.impact_point;
position = s.position;
penetration_depth = s.penetration_depth;
time_stamp = s.time_stamp;
object_name = s.object_name;
object_id = s.object_id;
}
msr::airlib::CollisionInfo to() const
{
return msr::airlib::CollisionInfo(has_collided, normal.to(), impact_point.to(), position.to(), penetration_depth, time_stamp, object_name, object_id);
}
};
struct Quaternionr
{
msr::airlib::real_T w_val = 1, x_val = 0, y_val = 0, z_val = 0;
MSGPACK_DEFINE_MAP(w_val, x_val, y_val, z_val);
Quaternionr()
{
}
Quaternionr(const msr::airlib::Quaternionr& s)
{
w_val = s.w();
x_val = s.x();
y_val = s.y();
z_val = s.z();
}
msr::airlib::Quaternionr to() const
{
return msr::airlib::Quaternionr(w_val, x_val, y_val, z_val);
}
};
struct Pose
{
Vector3r position;
Quaternionr orientation;
MSGPACK_DEFINE_MAP(position, orientation);
Pose()
{
}
Pose(const msr::airlib::Pose& s)
{
position = s.position;
orientation = s.orientation;
}
msr::airlib::Pose to() const
{
return msr::airlib::Pose(position.to(), orientation.to());
}
};
struct GeoPoint
{
double latitude = 0, longitude = 0;
float altitude = 0;
MSGPACK_DEFINE_MAP(latitude, longitude, altitude);
GeoPoint()
{
}
GeoPoint(const msr::airlib::GeoPoint& s)
{
latitude = s.latitude;
longitude = s.longitude;
altitude = s.altitude;
}
msr::airlib::GeoPoint to() const
{
return msr::airlib::GeoPoint(latitude, longitude, altitude);
}
};
struct RCData
{
uint64_t timestamp = 0;
float pitch = 0, roll = 0, throttle = 0, yaw = 0;
float left_z = 0, right_z = 0;
uint16_t switches = 0;
std::string vendor_id = "";
bool is_initialized = false; //is RC connected?
bool is_valid = false; //must be true for data to be valid
MSGPACK_DEFINE_MAP(timestamp, pitch, roll, throttle, yaw, left_z, right_z, switches, vendor_id, is_initialized, is_valid);
RCData()
{
}
RCData(const msr::airlib::RCData& s)
{
timestamp = s.timestamp;
pitch = s.pitch;
roll = s.roll;
throttle = s.throttle;
yaw = s.yaw;
left_z = s.left_z;
right_z = s.right_z;
switches = s.switches;
vendor_id = s.vendor_id;
is_initialized = s.is_initialized;
is_valid = s.is_valid;
}
msr::airlib::RCData to() const
{
msr::airlib::RCData d;
d.timestamp = timestamp;
d.pitch = pitch;
d.roll = roll;
d.throttle = throttle;
d.yaw = yaw;
d.left_z = left_z;
d.right_z = right_z;
d.switches = switches;
d.vendor_id = vendor_id;
d.is_initialized = is_initialized;
d.is_valid = is_valid;
return d;
}
};
struct ProjectionMatrix
{
float matrix[4][4];
MSGPACK_DEFINE_MAP(matrix);
ProjectionMatrix()
{
}
ProjectionMatrix(const msr::airlib::ProjectionMatrix& s)
{
for (auto i = 0; i < 4; ++i)
for (auto j = 0; j < 4; ++j)
matrix[i][j] = s.matrix[i][j];
}
msr::airlib::ProjectionMatrix to() const
{
msr::airlib::ProjectionMatrix s;
for (auto i = 0; i < 4; ++i)
for (auto j = 0; j < 4; ++j)
s.matrix[i][j] = matrix[i][j];
return s;
}
};
struct Box2D
{
Vector2r min;
Vector2r max;
MSGPACK_DEFINE_MAP(min, max);
Box2D()
{
}
Box2D(const msr::airlib::Box2D& s)
{
min = s.min;
max = s.max;
}
msr::airlib::Box2D to() const
{
msr::airlib::Box2D s;
s.min = min.to();
s.max = max.to();
return s;
}
};
struct Box3D
{
Vector3r min;
Vector3r max;
MSGPACK_DEFINE_MAP(min, max);
Box3D()
{
}
Box3D(const msr::airlib::Box3D& s)
{
min = s.min;
max = s.max;
}
msr::airlib::Box3D to() const
{
msr::airlib::Box3D s;
s.min = min.to();
s.max = max.to();
return s;
}
};
struct DetectionInfo
{
std::string name;
GeoPoint geo_point;
Box2D box2D;
Box3D box3D;
Pose relative_pose;
MSGPACK_DEFINE_MAP(name, geo_point, box2D, box3D, relative_pose);
DetectionInfo()
{
}
DetectionInfo(const msr::airlib::DetectionInfo& d)
{
name = d.name;
geo_point = d.geo_point;
box2D = d.box2D;
box3D = d.box3D;
relative_pose = d.relative_pose;
}
msr::airlib::DetectionInfo to() const
{
msr::airlib::DetectionInfo d;
d.name = name;
d.geo_point = geo_point.to();
d.box2D = box2D.to();
d.box3D = box3D.to();
d.relative_pose = relative_pose.to();
return d;
}
static std::vector<DetectionInfo> from(
const std::vector<msr::airlib::DetectionInfo>& request)
{
std::vector<DetectionInfo> request_adaptor;
for (const auto& item : request)
request_adaptor.push_back(DetectionInfo(item));
return request_adaptor;
}
static std::vector<msr::airlib::DetectionInfo> to(
const std::vector<DetectionInfo>& request_adapter)
{
std::vector<msr::airlib::DetectionInfo> request;
for (const auto& item : request_adapter)
request.push_back(item.to());
return request;
}
};
struct CameraInfo
{
Pose pose;
float fov;
ProjectionMatrix proj_mat;
MSGPACK_DEFINE_MAP(pose, fov, proj_mat);
CameraInfo()
{
}
CameraInfo(const msr::airlib::CameraInfo& s)
{
pose = s.pose;
fov = s.fov;
proj_mat = ProjectionMatrix(s.proj_mat);
}
msr::airlib::CameraInfo to() const
{
msr::airlib::CameraInfo s;
s.pose = pose.to();
s.fov = fov;
s.proj_mat = proj_mat.to();
return s;
}
};
struct KinematicsState
{
Vector3r position;
Quaternionr orientation;
Vector3r linear_velocity;
Vector3r angular_velocity;
Vector3r linear_acceleration;
Vector3r angular_acceleration;
MSGPACK_DEFINE_MAP(position, orientation, linear_velocity, angular_velocity, linear_acceleration, angular_acceleration);
KinematicsState()
{
}
KinematicsState(const msr::airlib::Kinematics::State& s)
{
position = s.pose.position;
orientation = s.pose.orientation;
linear_velocity = s.twist.linear;
angular_velocity = s.twist.angular;
linear_acceleration = s.accelerations.linear;
angular_acceleration = s.accelerations.angular;
}
msr::airlib::Kinematics::State to() const
{
msr::airlib::Kinematics::State s;
s.pose.position = position.to();
s.pose.orientation = orientation.to();
s.twist.linear = linear_velocity.to();
s.twist.angular = angular_velocity.to();
s.accelerations.linear = linear_acceleration.to();
s.accelerations.angular = angular_acceleration.to();
return s;
}
};
struct EnvironmentState
{
Vector3r position;
GeoPoint geo_point;
//these fields are computed
Vector3r gravity;
float air_pressure;
float temperature;
float air_density;
MSGPACK_DEFINE_MAP(position, geo_point, gravity, air_pressure, temperature, air_density);
EnvironmentState()
{
}
EnvironmentState(const msr::airlib::Environment::State& s)
{
position = s.position;
geo_point = s.geo_point;
gravity = s.gravity;
air_pressure = s.air_pressure;
temperature = s.temperature;
air_density = s.air_density;
}
msr::airlib::Environment::State to() const
{
msr::airlib::Environment::State s;
s.position = position.to();
s.geo_point = geo_point.to();
s.gravity = gravity.to();
s.air_pressure = air_pressure;
s.temperature = temperature;
s.air_density = air_density;
return s;
}
};
struct ImageRequest
{
std::string camera_name;
msr::airlib::ImageCaptureBase::ImageType image_type;
bool pixels_as_float;
bool compress;
MSGPACK_DEFINE_MAP(camera_name, image_type, pixels_as_float, compress);
ImageRequest()
{
}
ImageRequest(const msr::airlib::ImageCaptureBase::ImageRequest& s)
: camera_name(s.camera_name)
, image_type(s.image_type)
, pixels_as_float(s.pixels_as_float)
, compress(s.compress)
{
}
msr::airlib::ImageCaptureBase::ImageRequest to() const
{
return { camera_name, image_type, pixels_as_float, compress };
}
static std::vector<ImageRequest> from(
const std::vector<msr::airlib::ImageCaptureBase::ImageRequest>& request)
{
std::vector<ImageRequest> request_adaptor;
for (const auto& item : request)
request_adaptor.push_back(ImageRequest(item));
return request_adaptor;
}
static std::vector<msr::airlib::ImageCaptureBase::ImageRequest> to(
const std::vector<ImageRequest>& request_adapter)
{
std::vector<msr::airlib::ImageCaptureBase::ImageRequest> request;
for (const auto& item : request_adapter)
request.push_back(item.to());
return request;
}
};
struct ImageResponse
{
std::vector<uint8_t> image_data_uint8;
std::vector<float> image_data_float;
std::string camera_name;
Vector3r camera_position;
Quaternionr camera_orientation;
msr::airlib::TTimePoint time_stamp;
std::string message;
bool pixels_as_float;
bool compress;
int width, height;
msr::airlib::ImageCaptureBase::ImageType image_type;
MSGPACK_DEFINE_MAP(image_data_uint8, image_data_float, camera_position, camera_name,
camera_orientation, time_stamp, message, pixels_as_float, compress, width, height, image_type);
ImageResponse()
{
}
ImageResponse(const msr::airlib::ImageCaptureBase::ImageResponse& s)
{
pixels_as_float = s.pixels_as_float;
image_data_uint8 = s.image_data_uint8;
image_data_float = s.image_data_float;
camera_name = s.camera_name;
camera_position = Vector3r(s.camera_position);
camera_orientation = Quaternionr(s.camera_orientation);
time_stamp = s.time_stamp;
message = s.message;
compress = s.compress;
width = s.width;
height = s.height;
image_type = s.image_type;
}
msr::airlib::ImageCaptureBase::ImageResponse to() const
{
msr::airlib::ImageCaptureBase::ImageResponse d;
d.pixels_as_float = pixels_as_float;
if (!pixels_as_float)
d.image_data_uint8 = image_data_uint8;
else
d.image_data_float = image_data_float;
d.camera_name = camera_name;
d.camera_position = camera_position.to();
d.camera_orientation = camera_orientation.to();
d.time_stamp = time_stamp;
d.message = message;
d.compress = compress;
d.width = width;
d.height = height;
d.image_type = image_type;
return d;
}
static std::vector<msr::airlib::ImageCaptureBase::ImageResponse> to(
const std::vector<ImageResponse>& response_adapter)
{
std::vector<msr::airlib::ImageCaptureBase::ImageResponse> response;
for (const auto& item : response_adapter)
response.push_back(item.to());
return response;
}
static std::vector<ImageResponse> from(
const std::vector<msr::airlib::ImageCaptureBase::ImageResponse>& response)
{
std::vector<ImageResponse> response_adapter;
for (const auto& item : response)
response_adapter.push_back(ImageResponse(item));
return response_adapter;
}
};
struct LidarData
{
msr::airlib::TTimePoint time_stamp; // timestamp
std::vector<float> point_cloud; // data
Pose pose;
std::vector<int> segmentation;
MSGPACK_DEFINE_MAP(time_stamp, point_cloud, pose, segmentation);
LidarData()
{
}
LidarData(const msr::airlib::LidarData& s)
{
time_stamp = s.time_stamp;
point_cloud = s.point_cloud;
pose = s.pose;
segmentation = s.segmentation;
}
msr::airlib::LidarData to() const
{
msr::airlib::LidarData d;
d.time_stamp = time_stamp;
d.point_cloud = point_cloud;
d.pose = pose.to();
d.segmentation = segmentation;
return d;
}
};
struct ImuData
{
msr::airlib::TTimePoint time_stamp;
Quaternionr orientation;
Vector3r angular_velocity;
Vector3r linear_acceleration;
MSGPACK_DEFINE_MAP(time_stamp, orientation, angular_velocity, linear_acceleration);
ImuData()
{
}
ImuData(const msr::airlib::ImuBase::Output& s)
{
time_stamp = s.time_stamp;
orientation = s.orientation;
angular_velocity = s.angular_velocity;
linear_acceleration = s.linear_acceleration;
}
msr::airlib::ImuBase::Output to() const
{
msr::airlib::ImuBase::Output d;
d.time_stamp = time_stamp;
d.orientation = orientation.to();
d.angular_velocity = angular_velocity.to();
d.linear_acceleration = linear_acceleration.to();
return d;
}
};
struct BarometerData
{
msr::airlib::TTimePoint time_stamp;
msr::airlib::real_T altitude;
msr::airlib::real_T pressure;
msr::airlib::real_T qnh;
MSGPACK_DEFINE_MAP(time_stamp, altitude, pressure, qnh);
BarometerData()
{
}
BarometerData(const msr::airlib::BarometerBase::Output& s)
{
time_stamp = s.time_stamp;
altitude = s.altitude;
pressure = s.pressure;
qnh = s.qnh;
}
msr::airlib::BarometerBase::Output to() const
{
msr::airlib::BarometerBase::Output d;
d.time_stamp = time_stamp;
d.altitude = altitude;
d.pressure = pressure;
d.qnh = qnh;
return d;
}
};
struct MagnetometerData
{
msr::airlib::TTimePoint time_stamp;
Vector3r magnetic_field_body;
std::vector<float> magnetic_field_covariance; // not implemented in MagnetometerBase.hpp
MSGPACK_DEFINE_MAP(time_stamp, magnetic_field_body, magnetic_field_covariance);
MagnetometerData()
{
}
MagnetometerData(const msr::airlib::MagnetometerBase::Output& s)
{
time_stamp = s.time_stamp;
magnetic_field_body = s.magnetic_field_body;
magnetic_field_covariance = s.magnetic_field_covariance;
}
msr::airlib::MagnetometerBase::Output to() const
{
msr::airlib::MagnetometerBase::Output d;
d.time_stamp = time_stamp;
d.magnetic_field_body = magnetic_field_body.to();
d.magnetic_field_covariance = magnetic_field_covariance;
return d;
}
};
struct GnssReport
{
GeoPoint geo_point;
msr::airlib::real_T eph = 0.0, epv = 0.0;
Vector3r velocity;
msr::airlib::GpsBase::GnssFixType fix_type;
uint64_t time_utc = 0;
MSGPACK_DEFINE_MAP(geo_point, eph, epv, velocity, fix_type, time_utc);
GnssReport()
{
}
GnssReport(const msr::airlib::GpsBase::GnssReport& s)
{
geo_point = s.geo_point;
eph = s.eph;
epv = s.epv;
velocity = s.velocity;
fix_type = s.fix_type;
time_utc = s.time_utc;
}
msr::airlib::GpsBase::GnssReport to() const
{
msr::airlib::GpsBase::GnssReport d;
d.geo_point = geo_point.to();
d.eph = eph;
d.epv = epv;
d.velocity = velocity.to();
d.fix_type = fix_type;
d.time_utc = time_utc;
return d;
}
};
struct GpsData
{
msr::airlib::TTimePoint time_stamp;
GnssReport gnss;
bool is_valid = false;
MSGPACK_DEFINE_MAP(time_stamp, gnss, is_valid);
GpsData()
{
}
GpsData(const msr::airlib::GpsBase::Output& s)
{
time_stamp = s.time_stamp;
gnss = s.gnss;
is_valid = s.is_valid;
}
msr::airlib::GpsBase::Output to() const
{
msr::airlib::GpsBase::Output d;
d.time_stamp = time_stamp;
d.gnss = gnss.to();
d.is_valid = is_valid;
return d;
}
};
struct DistanceSensorData
{
msr::airlib::TTimePoint time_stamp;
msr::airlib::real_T distance; //meters
msr::airlib::real_T min_distance; //m
msr::airlib::real_T max_distance; //m
Pose relative_pose;
MSGPACK_DEFINE_MAP(time_stamp, distance, min_distance, max_distance, relative_pose);
DistanceSensorData()
{
}
DistanceSensorData(const msr::airlib::DistanceSensorData& s)
{
time_stamp = s.time_stamp;
distance = s.distance;
min_distance = s.min_distance;
max_distance = s.max_distance;
relative_pose = s.relative_pose;
}
msr::airlib::DistanceSensorData to() const
{
msr::airlib::DistanceSensorData d;
d.time_stamp = time_stamp;
d.distance = distance;
d.min_distance = min_distance;
d.max_distance = max_distance;
d.relative_pose = relative_pose.to();
return d;
}
};
struct MeshPositionVertexBuffersResponse
{
Vector3r position;
Quaternionr orientation;
std::vector<float> vertices;
std::vector<uint32_t> indices;
std::string name;
MSGPACK_DEFINE_MAP(position, orientation, vertices, indices, name);
MeshPositionVertexBuffersResponse()
{
}
MeshPositionVertexBuffersResponse(const msr::airlib::MeshPositionVertexBuffersResponse& s)
{
position = Vector3r(s.position);
orientation = Quaternionr(s.orientation);
vertices = s.vertices;
indices = s.indices;
if (vertices.size() == 0)
vertices.push_back(0);
if (indices.size() == 0)
indices.push_back(0);
name = s.name;
}
msr::airlib::MeshPositionVertexBuffersResponse to() const
{
msr::airlib::MeshPositionVertexBuffersResponse d;
d.position = position.to();
d.orientation = orientation.to();
d.vertices = vertices;
d.indices = indices;
d.name = name;
return d;
}
static std::vector<msr::airlib::MeshPositionVertexBuffersResponse> to(
const std::vector<MeshPositionVertexBuffersResponse>& response_adapter)
{
std::vector<msr::airlib::MeshPositionVertexBuffersResponse> response;
for (const auto& item : response_adapter)
response.push_back(item.to());
return response;
}
static std::vector<MeshPositionVertexBuffersResponse> from(
const std::vector<msr::airlib::MeshPositionVertexBuffersResponse>& response)
{
std::vector<MeshPositionVertexBuffersResponse> response_adapter;
for (const auto& item : response)
response_adapter.push_back(MeshPositionVertexBuffersResponse(item));
return response_adapter;
}
};
};
}
} //namespace
MSGPACK_ADD_ENUM(msr::airlib::SafetyEval::SafetyViolationType_);
MSGPACK_ADD_ENUM(msr::airlib::SafetyEval::ObsAvoidanceStrategy);
MSGPACK_ADD_ENUM(msr::airlib::ImageCaptureBase::ImageType);
MSGPACK_ADD_ENUM(msr::airlib::WorldSimApiBase::WeatherParameter);
MSGPACK_ADD_ENUM(msr::airlib::GpsBase::GnssFixType);
#endif
| AirSim/AirLib/include/api/RpcLibAdaptorsBase.hpp/0 | {
"file_path": "AirSim/AirLib/include/api/RpcLibAdaptorsBase.hpp",
"repo_id": "AirSim",
"token_count": 15862
} | 7 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef msr_airlib_FrequencyLimiter_hpp
#define msr_airlib_FrequencyLimiter_hpp
#include "common/Common.hpp"
#include "UpdatableObject.hpp"
#include "common/Common.hpp"
namespace msr
{
namespace airlib
{
class FrequencyLimiter : public UpdatableObject
{
public:
FrequencyLimiter(real_T frequency = Utils::max<float>(), real_T startup_delay = 0)
{
initialize(frequency, startup_delay);
}
void initialize(real_T frequency = Utils::max<float>(), real_T startup_delay = 0)
{
frequency_ = frequency;
startup_delay_ = startup_delay;
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
last_time_ = clock()->nowNanos();
first_time_ = last_time_;
if (Utils::isApproximatelyZero(frequency_))
interval_size_sec_ = 1E10; //some high number
else
interval_size_sec_ = 1.0f / frequency_;
elapsed_total_sec_ = 0;
elapsed_interval_sec_ = 0;
last_elapsed_interval_sec_ = 0;
update_count_ = 0;
interval_complete_ = false;
startup_complete_ = false;
}
virtual void failResetUpdateOrdering(std::string err) override
{
unused(err);
// Do nothing.
// Disable checks for reset/update sequence because
// this object may get created but not used.
}
virtual void update() override
{
UpdatableObject::update();
elapsed_total_sec_ = clock()->elapsedSince(first_time_);
elapsed_interval_sec_ = clock()->elapsedSince(last_time_);
++update_count_;
//if startup_delay_ > 0 then we consider startup_delay_ as the first interval
//that needs to be complete
if (!startup_complete_) {
if (Utils::isDefinitelyGreaterThan(startup_delay_, 0.0f)) {
//see if we have spent startup_delay_ time yet
interval_complete_ = elapsed_interval_sec_ >= startup_delay_;
}
else //no special startup delay is needed
startup_complete_ = true;
}
//if startup is complete, we will do regular intervals from now one
if (startup_complete_)
interval_complete_ = elapsed_interval_sec_ >= interval_size_sec_;
//when any interval is done, reset the state and repeat
if (interval_complete_) {
last_elapsed_interval_sec_ = elapsed_interval_sec_;
last_time_ = clock()->nowNanos();
elapsed_interval_sec_ = 0;
startup_complete_ = true;
}
}
//*** End: UpdatableState implementation ***//
TTimeDelta getElapsedTotalSec() const
{
return elapsed_total_sec_;
}
TTimeDelta getElapsedIntervalSec() const
{
return elapsed_interval_sec_;
}
TTimeDelta getLastElapsedIntervalSec() const
{
return last_elapsed_interval_sec_;
}
bool isWaitComplete() const
{
return interval_complete_;
}
bool isStartupComplete() const
{
return startup_complete_;
}
uint getUpdateCount() const
{
return update_count_;
}
private:
real_T interval_size_sec_;
TTimeDelta elapsed_total_sec_;
TTimeDelta elapsed_interval_sec_;
TTimeDelta last_elapsed_interval_sec_;
uint update_count_;
real_T frequency_;
real_T startup_delay_;
bool interval_complete_;
bool startup_complete_;
TTimePoint last_time_, first_time_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/common/FrequencyLimiter.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/FrequencyLimiter.hpp",
"repo_id": "AirSim",
"token_count": 1913
} | 8 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef commn_utils_AsyncTasker_hpp
#define commn_utils_AsyncTasker_hpp
#include "ctpl_stl.h"
#include <functional>
class AsyncTasker
{
public:
AsyncTasker(unsigned int thread_count = 4)
: threads_(thread_count), error_handler_([](std::exception e) { unused(e); })
{
}
void setErrorHandler(std::function<void(std::exception&)> errorHandler)
{
error_handler_ = errorHandler;
}
void execute(std::function<void()> func, unsigned int iterations = 1)
{
if (iterations < 1)
return;
if (iterations == 1) {
threads_.push([=](int i) {
unused(i);
try {
func();
}
catch (std::exception& e) {
error_handler_(e);
};
});
}
else {
threads_.push([=](int i) {
unused(i);
try {
for (unsigned int itr = 0; itr < iterations; ++itr) {
func();
}
}
catch (std::exception& e) {
// if task failed we shouldn't try additional iterations.
error_handler_(e);
};
});
}
}
private:
ctpl::thread_pool threads_;
std::function<void(std::exception&)> error_handler_;
};
#endif
| AirSim/AirLib/include/common/common_utils/AsyncTasker.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/common_utils/AsyncTasker.hpp",
"repo_id": "AirSim",
"token_count": 802
} | 9 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef airsim_core_PhysicsBodyVertex_hpp
#define airsim_core_PhysicsBodyVertex_hpp
#include "common/UpdatableObject.hpp"
#include "common/Common.hpp"
#include "common/CommonStructs.hpp"
namespace msr
{
namespace airlib
{
class PhysicsBodyVertex : public UpdatableObject
{
protected:
virtual void setWrench(Wrench& wrench)
{
unused(wrench);
//derived class should override if this is force/torque
//generating vertex
}
public:
real_T getDragFactor() const
{
return drag_factor_;
}
void setDragFactor(real_T val)
{
drag_factor_ = val;
}
PhysicsBodyVertex()
{
//allow default constructor with later call for initialize
}
PhysicsBodyVertex(const Vector3r& position, const Vector3r& normal, real_T drag_factor = 0)
{
initialize(position, normal, drag_factor);
}
void initialize(const Vector3r& position, const Vector3r& normal, real_T drag_factor = 0)
{
initial_position_ = position;
initial_normal_ = normal;
drag_factor_ = drag_factor;
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
position_ = initial_position_;
normal_ = initial_normal_;
current_wrench_ = Wrench::zero();
}
virtual void update() override
{
UpdatableObject::update();
setWrench(current_wrench_);
}
//*** End: UpdatableState implementation ***//
//getters, setters
Vector3r getPosition() const
{
return position_;
}
void setPosition(const Vector3r& position)
{
position_ = position;
}
Vector3r getNormal() const
{
return normal_;
}
void setNormal(const Vector3r& normal)
{
normal_ = normal;
}
Wrench getWrench() const
{
return current_wrench_;
}
private:
Vector3r initial_position_, position_;
Vector3r initial_normal_, normal_;
Wrench current_wrench_;
real_T drag_factor_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/physics/PhysicsBodyVertex.hpp/0 | {
"file_path": "AirSim/AirLib/include/physics/PhysicsBodyVertex.hpp",
"repo_id": "AirSim",
"token_count": 1151
} | 10 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef msr_airlib_Distance_hpp
#define msr_airlib_Distance_hpp
#include <random>
#include "common/Common.hpp"
#include "DistanceSimpleParams.hpp"
#include "DistanceBase.hpp"
#include "common/GaussianMarkov.hpp"
#include "common/DelayLine.hpp"
#include "common/FrequencyLimiter.hpp"
namespace msr
{
namespace airlib
{
class DistanceSimple : public DistanceBase
{
public:
DistanceSimple(const AirSimSettings::DistanceSetting& setting = AirSimSettings::DistanceSetting())
: DistanceBase(setting.sensor_name)
{
// initialize params
params_.initializeFromSettings(setting);
uncorrelated_noise_ = RandomGeneratorGausianR(0.0f, params_.uncorrelated_noise_sigma);
//correlated_noise_.initialize(params_.correlated_noise_tau, params_.correlated_noise_sigma, 0.0f);
//initialize frequency limiter
freq_limiter_.initialize(params_.update_frequency, params_.startup_delay);
delay_line_.initialize(params_.update_latency);
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
//correlated_noise_.reset();
uncorrelated_noise_.reset();
freq_limiter_.reset();
delay_line_.reset();
delay_line_.push_back(getOutputInternal());
}
virtual void update() override
{
DistanceBase::update();
freq_limiter_.update();
if (freq_limiter_.isWaitComplete()) {
delay_line_.push_back(getOutputInternal());
}
delay_line_.update();
if (freq_limiter_.isWaitComplete())
setOutput(delay_line_.getOutput());
}
//*** End: UpdatableState implementation ***//
virtual ~DistanceSimple() = default;
const DistanceSimpleParams& getParams() const
{
return params_;
}
protected:
virtual real_T getRayLength(const Pose& pose) = 0;
private: //methods
DistanceSensorData getOutputInternal()
{
DistanceSensorData output;
const GroundTruth& ground_truth = getGroundTruth();
//order of Pose addition is important here because it also adds quaternions which is not commutative!
auto distance = getRayLength(params_.relative_pose + ground_truth.kinematics->pose);
//add noise in distance (about 0.2m sigma)
distance += uncorrelated_noise_.next();
output.distance = distance;
output.min_distance = params_.min_distance;
output.max_distance = params_.max_distance;
output.relative_pose = params_.relative_pose;
output.time_stamp = clock()->nowNanos();
return output;
}
private:
DistanceSimpleParams params_;
//GaussianMarkov correlated_noise_;
RandomGeneratorGausianR uncorrelated_noise_;
FrequencyLimiter freq_limiter_;
DelayLine<DistanceSensorData> delay_line_;
//start time
};
}
} //namespace
#endif
| AirSim/AirLib/include/sensors/distance/DistanceSimple.hpp/0 | {
"file_path": "AirSim/AirLib/include/sensors/distance/DistanceSimple.hpp",
"repo_id": "AirSim",
"token_count": 1380
} | 11 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef air_CarRpcLibAdaptors_hpp
#define air_CarRpcLibAdaptors_hpp
#include "common/Common.hpp"
#include "common/CommonStructs.hpp"
#include "api/RpcLibAdaptorsBase.hpp"
#include "common/ImageCaptureBase.hpp"
#include "vehicles/car/api/CarApiBase.hpp"
#include "common/common_utils/WindowsApisCommonPre.hpp"
#include "rpc/msgpack.hpp"
#include "common/common_utils/WindowsApisCommonPost.hpp"
namespace msr
{
namespace airlib_rpclib
{
class CarRpcLibAdaptors : public RpcLibAdaptorsBase
{
public:
struct CarControls
{
float throttle = 0;
float steering = 0;
float brake = 0;
bool handbrake = false;
bool is_manual_gear = false;
int manual_gear = 0;
bool gear_immediate = true;
MSGPACK_DEFINE_MAP(throttle, steering, brake, handbrake, is_manual_gear, manual_gear, gear_immediate);
CarControls()
{
}
CarControls(const msr::airlib::CarApiBase::CarControls& s)
{
throttle = s.throttle;
steering = s.steering;
brake = s.brake;
handbrake = s.handbrake;
is_manual_gear = s.is_manual_gear;
manual_gear = s.manual_gear;
gear_immediate = s.gear_immediate;
}
msr::airlib::CarApiBase::CarControls to() const
{
return msr::airlib::CarApiBase::CarControls(throttle, steering, brake, handbrake, is_manual_gear, manual_gear, gear_immediate);
}
};
struct CarState
{
float speed;
int gear;
float rpm;
float maxrpm;
bool handbrake;
KinematicsState kinematics_estimated;
uint64_t timestamp;
MSGPACK_DEFINE_MAP(speed, gear, rpm, maxrpm, handbrake, kinematics_estimated, timestamp);
CarState()
{
}
CarState(const msr::airlib::CarApiBase::CarState& s)
{
speed = s.speed;
gear = s.gear;
rpm = s.rpm;
maxrpm = s.maxrpm;
handbrake = s.handbrake;
timestamp = s.timestamp;
kinematics_estimated = s.kinematics_estimated;
}
msr::airlib::CarApiBase::CarState to() const
{
return msr::airlib::CarApiBase::CarState(
speed, gear, rpm, maxrpm, handbrake, kinematics_estimated.to(), timestamp);
}
};
};
}
} //namespace
#endif
| AirSim/AirLib/include/vehicles/car/api/CarRpcLibAdaptors.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/car/api/CarRpcLibAdaptors.hpp",
"repo_id": "AirSim",
"token_count": 1440
} | 12 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef msr_airlib_vehicles_ArduCopter_hpp
#define msr_airlib_vehicles_ArduCopter_hpp
#include "vehicles/multirotor/firmwares/arducopter/ArduCopterApi.hpp"
#include "vehicles/multirotor/MultiRotorParams.hpp"
#include "common/AirSimSettings.hpp"
#include "sensors/SensorFactory.hpp"
namespace msr
{
namespace airlib
{
class ArduCopterParams : public MultiRotorParams
{
public:
ArduCopterParams(const AirSimSettings::MavLinkVehicleSetting& vehicle_setting, std::shared_ptr<const SensorFactory> sensor_factory)
: sensor_factory_(sensor_factory)
{
connection_info_ = getConnectionInfo(vehicle_setting);
}
virtual ~ArduCopterParams() = default;
virtual std::unique_ptr<MultirotorApiBase> createMultirotorApi() override
{
return std::unique_ptr<MultirotorApiBase>(new ArduCopterApi(this, connection_info_));
}
protected:
virtual void setupParams() override
{
auto& params = getParams();
// Use connection_info_.model for the model name, see Px4MultiRotorParams for example
// Only Generic for now
setupFrameGenericQuad(params);
}
virtual const SensorFactory* getSensorFactory() const override
{
return sensor_factory_.get();
}
static const AirSimSettings::MavLinkConnectionInfo& getConnectionInfo(const AirSimSettings::MavLinkVehicleSetting& vehicle_setting)
{
return vehicle_setting.connection_info;
}
private:
AirSimSettings::MavLinkConnectionInfo connection_info_;
std::shared_ptr<const SensorFactory> sensor_factory_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/vehicles/multirotor/firmwares/arducopter/ArduCopterParams.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/arducopter/ArduCopterParams.hpp",
"repo_id": "AirSim",
"token_count": 741
} | 13 |
#pragma once
#include <vector>
#include "interfaces/CommonStructs.hpp"
#include "interfaces/IBoard.hpp"
#include "interfaces/ICommLink.hpp"
#include "interfaces/IStateEstimator.hpp"
#include "interfaces/IFirmware.hpp"
#include "Params.hpp"
#include "RemoteControl.hpp"
#include "OffboardApi.hpp"
#include "Mixer.hpp"
#include "CascadeController.hpp"
#include "AdaptiveController.hpp"
namespace simple_flight
{
class Firmware : public IFirmware
{
public:
Firmware(Params* params, IBoard* board, ICommLink* comm_link, IStateEstimator* state_estimator)
: params_(params), board_(board), comm_link_(comm_link), state_estimator_(state_estimator), offboard_api_(params, board, board, state_estimator, comm_link), mixer_(params)
{
switch (params->controller_type) {
case Params::ControllerType::Cascade:
controller_ = std::unique_ptr<CascadeController>(new CascadeController(params, board, comm_link));
break;
case Params::ControllerType::Adaptive:
controller_ = std::unique_ptr<AdaptiveController>(new AdaptiveController());
break;
default:
throw std::invalid_argument("Cannot recognize controller specified by params->controller_type");
}
controller_->initialize(&offboard_api_, state_estimator_);
}
virtual void reset() override
{
IFirmware::reset();
board_->reset();
comm_link_->reset();
controller_->reset();
offboard_api_.reset();
motor_outputs_.assign(params_->motor.motor_count, 0);
}
virtual void update() override
{
IFirmware::update();
board_->update();
offboard_api_.update();
controller_->update();
const Axis4r& output_controls = controller_->getOutput();
// if last goal mode is passthrough for all axes (which means moveByMotorPWMs was called),
// we directly set the motor outputs to controller outputs
// note that the order of motors is as explained MultiRotorParams::initializeRotorQuadX()
if (controller_->isLastGoalModeAllPassthrough()) {
for (uint16_t motor_index = 0; motor_index < params_->motor.motor_count; ++motor_index)
motor_outputs_[motor_index] = output_controls[motor_index];
}
else {
// apply motor mixing matrix to convert from controller output to motor outputs
mixer_.getMotorOutput(output_controls, motor_outputs_);
}
//finally write the motor outputs
for (uint16_t motor_index = 0; motor_index < params_->motor.motor_count; ++motor_index)
board_->writeOutput(motor_index, motor_outputs_.at(motor_index));
comm_link_->update();
}
virtual IOffboardApi& offboardApi() override
{
return offboard_api_;
}
private:
//objects we use
Params* params_;
IBoard* board_;
ICommLink* comm_link_;
IStateEstimator* state_estimator_;
OffboardApi offboard_api_;
Mixer mixer_;
std::unique_ptr<IController> controller_;
std::vector<float> motor_outputs_;
};
} //namespace
| AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Firmware.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/Firmware.hpp",
"repo_id": "AirSim",
"token_count": 1268
} | 14 |
#pragma once
#include <cstdint>
namespace simple_flight
{
class IBoardOutputPins
{
public:
virtual void writeOutput(uint16_t index, float val) = 0; //val = -1 to 1 for reversible motors otherwise 0 to 1
virtual void setLed(uint8_t index, int32_t color) = 0;
virtual ~IBoardOutputPins() = default;
};
}
| AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoardOutputPins.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoardOutputPins.hpp",
"repo_id": "AirSim",
"token_count": 115
} | 15 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//in header only mode, control library is not available
#ifndef AIRLIB_HEADER_ONLY
//RPC code requires C++14. If build system like Unreal doesn't support it then use compiled binaries
#ifndef AIRLIB_NO_RPC
//if using Unreal Build system then include precompiled header file first
#include "vehicles/car/api/CarRpcLibServer.hpp"
#include "common/Common.hpp"
STRICT_MODE_OFF
#ifndef RPCLIB_MSGPACK
#define RPCLIB_MSGPACK clmdep_msgpack
#endif // !RPCLIB_MSGPACK
#include "common/common_utils/MinWinDefines.hpp"
#undef NOUSER
#include "common/common_utils/WindowsApisCommonPre.hpp"
#undef FLOAT
#undef check
#include "rpc/server.h"
//TODO: HACK: UE4 defines macro with stupid names like "check" that conflicts with msgpack library
#ifndef check
#define check(expr) (static_cast<void>((expr)))
#endif
#include "common/common_utils/WindowsApisCommonPost.hpp"
#include "vehicles/car/api/CarRpcLibAdaptors.hpp"
STRICT_MODE_ON
namespace msr
{
namespace airlib
{
typedef msr::airlib_rpclib::CarRpcLibAdaptors CarRpcLibAdaptors;
CarRpcLibServer::CarRpcLibServer(ApiProvider* api_provider, string server_address, uint16_t port)
: RpcLibServerBase(api_provider, server_address, port)
{
(static_cast<rpc::server*>(getServer()))->bind("getCarState", [&](const std::string& vehicle_name) -> CarRpcLibAdaptors::CarState {
return CarRpcLibAdaptors::CarState(getVehicleApi(vehicle_name)->getCarState());
});
(static_cast<rpc::server*>(getServer()))->bind("setCarControls", [&](const CarRpcLibAdaptors::CarControls& controls, const std::string& vehicle_name) -> void {
getVehicleApi(vehicle_name)->setCarControls(controls.to());
});
(static_cast<rpc::server*>(getServer()))->bind("getCarControls", [&](const std::string& vehicle_name) -> CarRpcLibAdaptors::CarControls {
return CarRpcLibAdaptors::CarControls(getVehicleApi(vehicle_name)->getCarControls());
});
}
//required for pimpl
CarRpcLibServer::~CarRpcLibServer()
{
}
}
} //namespace
#endif
#endif
| AirSim/AirLib/src/vehicles/car/api/CarRpcLibServer.cpp/0 | {
"file_path": "AirSim/AirLib/src/vehicles/car/api/CarRpcLibServer.cpp",
"repo_id": "AirSim",
"token_count": 820
} | 16 |
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AirSimTargetPlatformVersion>$([System.String]::Copy('$(WindowsSDKVersion)').Replace('\',''))</AirSimTargetPlatformVersion>
<WindowsTargetPlatformVersion>$(AirSimTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
</Project> | AirSim/AirSim.props/0 | {
"file_path": "AirSim/AirSim.props",
"repo_id": "AirSim",
"token_count": 118
} | 17 |
#pragma once
#include "common/Common.hpp"
class RandomPointPoseGeneratorNoRoll
{
public:
private:
typedef common_utils::RandomGeneratorGaussianF RandomGeneratorGaussianF;
typedef msr::airlib::Vector3r Vector3r;
typedef msr::airlib::Quaternionr Quaternionr;
typedef common_utils::Utils Utils;
typedef msr::airlib::VectorMath VectorMath;
public:
Vector3r position;
Quaternionr orientation;
public:
RandomPointPoseGeneratorNoRoll(int random_seed)
: //settings are for neighbourhood environement
//sigma = desired_max / 2 so 95% of the times we in desired
rand_xy_(0.0f, 75.0f)
, rand_z_(-5.0f, 4.0f)
, rand_pitch_(0.0f, M_PIf / 8)
, rand_yaw_(0.0f, M_PIf)
{
rand_xy_.seed(random_seed);
rand_z_.seed(random_seed);
rand_pitch_.seed(random_seed);
rand_yaw_.seed(random_seed);
}
void next()
{
position.x() = rand_xy_.next();
position.y() = rand_xy_.next();
position.z() = Utils::clip(rand_z_.next(), -10.0f, -1.0f);
float pitch = Utils::clip(rand_pitch_.next(), -M_PIf / 2, M_PIf / 2);
float yaw = Utils::clip(rand_yaw_.next(), -M_PIf, M_PIf);
orientation = VectorMath::toQuaternion(pitch, 0, yaw);
}
private:
RandomGeneratorGaussianF rand_xy_, rand_z_, rand_pitch_, rand_yaw_;
}; | AirSim/Examples/DataCollection/RandomPointPoseGeneratorNoRoll.h/0 | {
"file_path": "AirSim/Examples/DataCollection/RandomPointPoseGeneratorNoRoll.h",
"repo_id": "AirSim",
"token_count": 627
} | 18 |
<UserControl x:Class="LogViewer.Controls.MeshViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LogViewer.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Viewport3D Name="MainViewPort" ClipToBounds="True">
<Viewport3D.Camera>
<PerspectiveCamera
FarPlaneDistance="200"
LookDirection="0,0,0"
UpDirection="0,1,0"
NearPlaneDistance="1"
Position="20,20,20"
FieldOfView="75" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight
Color="White"
Direction="-2,-3,-1" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="xAxis">
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="-100 0 0 100 0 0 -100 1 0 100 1 0 -100 0 1 100 0 1 -100 1 1 100 1 1"
TriangleIndices="2 3 1 2 1 0 7 1 3 7 5 1 6 5 7 6 4 5 6 2 0 2 0 4 2 7 3 2 6 7 0 1 5 0 5 4">
</MeshGeometry3D>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<SolidColorBrush Color="Gray"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="yAxis">
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="0 -100 0 0 100 0 1 -100 0 1 100 0 0 -100 1 0 100 1 1 -100 1 1 100 1"
TriangleIndices="2 3 1 2 1 0 7 1 3 7 5 1 6 5 7 6 4 5 6 2 0 2 0 4 2 7 3 2 6 7 0 1 5 0 5 4">
</MeshGeometry3D>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<SolidColorBrush Color="Gray"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</Grid>
</UserControl>
| AirSim/LogViewer/LogViewer/Controls/MeshViewer.xaml/0 | {
"file_path": "AirSim/LogViewer/LogViewer/Controls/MeshViewer.xaml",
"repo_id": "AirSim",
"token_count": 2132
} | 19 |
using LogViewer.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LogViewer.Model
{
public interface IDataLog
{
/// <summary>
/// Returns the start time of the data in the log
/// </summary>
DateTime StartTime { get; }
/// <summary>
/// Returns the duration of the log from timestamp of first entry to the last.
/// </summary>
TimeSpan Duration { get; }
/// <summary>
/// Get all data values matching the given schema item.
/// </summary>
/// <param name="schema">The type of data values we are trying to fetch</param>
/// <param name="startTime">Limit the values to anything after this startTime</param>
/// <param name="duration">Limit the values to this time span from the start time</param>
/// <returns></returns>
IEnumerable<DataValue> GetDataValues(LogItemSchema schema, DateTime startTime, TimeSpan duration);
/// <summary>
/// This method returns a constant stream of values matching the schema in the case that the log
/// support live reading of values, like hte MavlinkLog. This stream blocks when there are no more
/// matching values.
/// </summary>
IEnumerable<DataValue> LiveQuery(LogItemSchema schema, CancellationToken token);
/// <summary>
/// This method gets the LogEntry items representing a row from the log.
/// </summary>
IEnumerable<LogEntry> GetRows(string typeName, DateTime startTime, TimeSpan duration);
/// <summary>
/// Extract actual flight times from the log (based on when the motors were actually on).
/// </summary>
IEnumerable<Flight> GetFlights();
/// <summary>
/// Convert the time in the LogEntryGPS structure to a DateTime that can be cared with a Flight.
/// </summary>
/// <returns></returns>
DateTime GetTime(ulong timeMs);
/// <summary>
/// This returns a potentially hierarchical schema showing the data values in this log and their associated names
/// </summary>
LogItemSchema Schema { get; }
}
public class Flight
{
public IDataLog Log { get; set; }
public DateTime StartTime { get; set; }
public TimeSpan Duration { get; set; }
public string Name { get; set; }
}
}
| AirSim/LogViewer/LogViewer/Model/IDataLog.cs/0 | {
"file_path": "AirSim/LogViewer/LogViewer/Model/IDataLog.cs",
"repo_id": "AirSim",
"token_count": 920
} | 20 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using LogViewer.Model;
namespace LogViewer.Controls
{
public class HierarchicalLogItemSchemaStyleSelector : StyleSelector
{
Style containerStyle;
Style leafStyle;
public override Style SelectStyle(object item, DependencyObject d)
{
FrameworkElement element = d as FrameworkElement;
if (element != null && item != null && item is LogItemSchema)
{
LogItemSchema category = item as LogItemSchema;
if (category.HasChildren)
{
if (containerStyle == null)
{
containerStyle = element.FindResource("ContainerListItemStyle") as Style;
}
return containerStyle;
}
else
{
if (leafStyle == null)
{
leafStyle = element.FindResource("ChildListItemStyle") as Style;
}
return leafStyle;
}
}
return null;
}
}
public class HierarchicalLogItemSchemaTemplateSelector : DataTemplateSelector
{
DataTemplate container;
DataTemplate leaf;
public override DataTemplate SelectTemplate(object item, DependencyObject d)
{
FrameworkElement element = d as FrameworkElement;
if (element != null && item != null && item is LogItemSchema)
{
LogItemSchema category = item as LogItemSchema;
if (category.HasChildren)
{
if (container == null)
{
container = element.FindResource("ContainerLogItemSchemaTemplate") as DataTemplate;
}
return container;
}
else
{
if (leaf == null)
{
leaf = element.FindResource("LeafLogItemSchemaTemplate") as DataTemplate;
}
return leaf;
}
}
return null;
}
}
}
| AirSim/LogViewer/LogViewer/Utilities/HierarchicalCategoryTemplateSelector.cs/0 | {
"file_path": "AirSim/LogViewer/LogViewer/Utilities/HierarchicalCategoryTemplateSelector.cs",
"repo_id": "AirSim",
"token_count": 1255
} | 21 |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{29C99047-525D-4389-9BF1-CC130755A135}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.Networking</RootNamespace>
<AssemblyName>Networking</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>$(MyKeyFile)</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Mavlink\MavlinkChannel.cs" />
<Compile Include="Mavlink\MavlinkTypes.cs" />
<Compile Include="Mavlink\Port.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SerialPort.cs" />
<Compile Include="UdpPort.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | AirSim/LogViewer/Networking/Networking.csproj/0 | {
"file_path": "AirSim/LogViewer/Networking/Networking.csproj",
"repo_id": "AirSim",
"token_count": 1728
} | 22 |
@echo off
set SCRIPT_PATH=%~dp0
cd %~dp0
msbuild MavLinkComGenerator.csproj
bin\Debug\MavLinkComGenerator.exe -xml:%SCRIPT_PATH%\..\mavlink\message_definitions\common.xml -out:%SCRIPT_PATH%\..\include
copy ..\include\MavLinkMessages.cpp ..\src
del ..\include\MavLinkMessages.cpp
goto :eof
| AirSim/MavLinkCom/MavLinkComGenerator/regen.cmd/0 | {
"file_path": "AirSim/MavLinkCom/MavLinkComGenerator/regen.cmd",
"repo_id": "AirSim",
"token_count": 121
} | 23 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef common_utils_Semaphore_hpp
#define common_utils_Semaphore_hpp
#include <memory>
namespace mavlink_utils
{
/*
A semaphore is used to signal an event across threads. One thread blocks on Wait() until
the other thread calls Signal. It is a counting semaphore so if the thread calls Signal
before the Wait() then the Wait() does not block.
*/
class Semaphore
{
public:
Semaphore();
~Semaphore();
// Increment the semaphore count to unblock the next waiter (the next wait caller will return).
// Throws exception if an error occurs.
void post();
// wait indefinitely for one call to post. If post has already been called then wait returns immediately
// decrementing the count so the next wait in the queue will block. Throws exception if an error occurs.
void wait();
// wait for a given number of milliseconds for one call to post. Returns false if a timeout or EINTR occurs.
// If post has already been called then timed_wait returns immediately decrementing the count so the next
// wait will block. Throws exception if an error occurs.
bool timed_wait(int milliseconds);
private:
class semaphore_impl;
std::unique_ptr<semaphore_impl> impl_;
};
}
#endif
| AirSim/MavLinkCom/include/Semaphore.hpp/0 | {
"file_path": "AirSim/MavLinkCom/include/Semaphore.hpp",
"repo_id": "AirSim",
"token_count": 391
} | 24 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "MavLinkConnection.hpp"
#include "impl/MavLinkConnectionImpl.hpp"
using namespace mavlinkcom;
using namespace mavlinkcom_impl;
MavLinkConnection::MavLinkConnection()
{
pImpl.reset(new MavLinkConnectionImpl());
}
std::shared_ptr<MavLinkConnection> MavLinkConnection::connectSerial(const std::string& nodeName, const std::string& portName, int baudrate, const std::string& initString)
{
return MavLinkConnectionImpl::connectSerial(nodeName, portName, baudrate, initString);
}
std::shared_ptr<MavLinkConnection> MavLinkConnection::connectLocalUdp(const std::string& nodeName, const std::string& localAddr, int localPort)
{
return MavLinkConnectionImpl::connectLocalUdp(nodeName, localAddr, localPort);
}
std::shared_ptr<MavLinkConnection> MavLinkConnection::connectRemoteUdp(const std::string& nodeName, const std::string& localAddr, const std::string& remoteAddr, int remotePort)
{
return MavLinkConnectionImpl::connectRemoteUdp(nodeName, localAddr, remoteAddr, remotePort);
}
std::shared_ptr<MavLinkConnection> MavLinkConnection::connectTcp(const std::string& nodeName, const std::string& localAddr, const std::string& remoteIpAddr, int remotePort)
{
return MavLinkConnectionImpl::connectTcp(nodeName, localAddr, remoteIpAddr, remotePort);
}
std::string MavLinkConnection::acceptTcp(const std::string& nodeName, const std::string& localAddr, int listeningPort)
{
return pImpl->acceptTcp(shared_from_this(), nodeName, localAddr, listeningPort);
}
void MavLinkConnection::startListening(const std::string& nodeName, std::shared_ptr<Port> connectedPort)
{
pImpl->startListening(shared_from_this(), nodeName, connectedPort);
}
// log every message that is "sent" using sendMessage.
void MavLinkConnection::startLoggingSendMessage(std::shared_ptr<MavLinkLog> log)
{
pImpl->startLoggingSendMessage(log);
}
void MavLinkConnection::stopLoggingSendMessage()
{
pImpl->stopLoggingSendMessage();
}
// log every message that is "received"
void MavLinkConnection::startLoggingReceiveMessage(std::shared_ptr<MavLinkLog> log)
{
pImpl->startLoggingReceiveMessage(log);
}
void MavLinkConnection::stopLoggingReceiveMessage()
{
pImpl->stopLoggingReceiveMessage();
}
void MavLinkConnection::close()
{
pImpl->close();
}
bool MavLinkConnection::isOpen()
{
return pImpl->isOpen();
}
void MavLinkConnection::ignoreMessage(uint8_t message_id)
{
pImpl->ignoreMessage(message_id);
}
int MavLinkConnection::prepareForSending(MavLinkMessage& msg)
{
return pImpl->prepareForSending(msg);
}
std::string MavLinkConnection::getName()
{
return pImpl->getName();
}
int MavLinkConnection::getTargetComponentId()
{
return pImpl->getTargetComponentId();
}
int MavLinkConnection::getTargetSystemId()
{
return pImpl->getTargetSystemId();
}
uint8_t MavLinkConnection::getNextSequence()
{
return pImpl->getNextSequence();
}
void MavLinkConnection::sendMessage(const MavLinkMessageBase& msg)
{
pImpl->sendMessage(msg);
}
void MavLinkConnection::sendMessage(const MavLinkMessage& msg)
{
pImpl->sendMessage(msg);
}
int MavLinkConnection::subscribe(MessageHandler handler)
{
return pImpl->subscribe(handler);
}
void MavLinkConnection::unsubscribe(int id)
{
pImpl->unsubscribe(id);
}
bool MavLinkConnection::isPublishThread() const
{
return pImpl->isPublishThread();
}
MavLinkConnection::~MavLinkConnection()
{
pImpl->close();
pImpl = nullptr;
}
void MavLinkConnection::join(std::shared_ptr<MavLinkConnection> remote, bool subscribeToLeft, bool subscribeToRight)
{
pImpl->join(remote, subscribeToLeft, subscribeToRight);
}
// get the next telemetry snapshot, then clear the internal counters and start over. This way each snapshot
// gives you a picture of what happened in whatever timeslice you decide to call this method.
void MavLinkConnection::getTelemetry(MavLinkTelemetry& result)
{
pImpl->getTelemetry(result);
}
//MavLinkConnection::MavLinkConnection(MavLinkConnection&&) = default;
//MavLinkConnection& MavLinkConnection::operator=(MavLinkConnection&&) = default;
| AirSim/MavLinkCom/src/MavLinkConnection.cpp/0 | {
"file_path": "AirSim/MavLinkCom/src/MavLinkConnection.cpp",
"repo_id": "AirSim",
"token_count": 1364
} | 25 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef MavLinkCom_MavLinkComImpl_hpp
#define MavLinkCom_MavLinkComImpl_hpp
#include <memory>
#include <string>
#include <vector>
#include <mutex>
#include <chrono>
#include "MavLinkNode.hpp"
#include "MavLinkNodeImpl.hpp"
#include "MavLinkFtpClient.hpp"
#include <stdio.h>
#include <string>
namespace mavlinkcom_impl
{
class MavLinkFtpClientImpl : public MavLinkNodeImpl
{
public:
MavLinkFtpClientImpl(int localSystemId, int localComponentId);
~MavLinkFtpClientImpl();
bool isSupported();
void list(MavLinkFtpProgress& progress, const std::string& remotePath, std::vector<MavLinkFileInfo>& files);
void get(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath);
void put(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath);
void remove(MavLinkFtpProgress& progress, const std::string& remotePath);
void mkdir(MavLinkFtpProgress& progress, const std::string& remotePath);
void rmdir(MavLinkFtpProgress& progress, const std::string& remotePath);
void cancel();
private:
void nextStep();
void listDirectory();
void removeFile();
void readFile();
void writeFile();
void mkdir();
void rmdir();
void handleListResponse();
void handleReadResponse();
void handleWriteResponse();
void handleRemoveResponse();
void handleRmdirResponse();
void handleMkdirResponse();
void reset();
void handleResponse(const MavLinkMessage& msg);
bool createLocalFile();
bool openSourceFile();
void subscribe();
void close();
void recordMessageSent();
void recordMessageReceived();
void runStateMachine();
void retry();
std::string replaceAll(std::string s, char toFind, char toReplace);
std::string normalize(std::string arg);
std::string toPX4Path(std::string arg);
// the following state is needed to implement a restartable state machine for each command
// with a watchdog
enum FtpCommandEnum
{
FtpCommandNone,
FtpCommandList,
FtpCommandGet,
FtpCommandPut,
FtpCommandRemove,
FtpCommandMkdir,
FtpCommandRmdir
};
FtpCommandEnum command_ = FtpCommandNone;
std::string local_file_;
std::string remote_file_;
FILE* file_ptr_ = nullptr;
int bytes_read_ = 0;
bool remote_file_open_ = false;
int bytes_written_ = 0;
uint64_t file_size_ = 0;
uint32_t file_index_ = 0;
int sequence_ = 0;
int subscription_ = 0;
bool waiting_ = false;
bool success_ = false;
int errorCode_ = 0;
std::chrono::milliseconds start_time_;
std::chrono::milliseconds total_time_;
int messages_ = 0;
int retries_ = 0;
MavLinkFileTransferProtocol last_message_;
bool watch_dog_running_ = false;
std::mutex mutex_;
std::vector<mavlinkcom::MavLinkFileInfo>* files_ = nullptr;
MavLinkFtpProgress* progress_ = nullptr;
};
}
#endif
| AirSim/MavLinkCom/src/impl/MavLinkFtpClientImpl.hpp/0 | {
"file_path": "AirSim/MavLinkCom/src/impl/MavLinkFtpClientImpl.hpp",
"repo_id": "AirSim",
"token_count": 1133
} | 26 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef SERIAL_COM_SERIALPORT_HPP
#define SERIAL_COM_SERIALPORT_HPP
#include <string>
#include <memory>
#include "Port.h"
#include "Utils.hpp"
enum Parity
{
Parity_None = (0x0100),
Parity_Odd = (0x0200),
Parity_Even = (0x0400),
Parity_Mark = (0x0800),
Parity_Space = (0x1000)
};
enum StopBits
{
StopBits_None = 0,
StopBits_10 = (0x0001),
StopBits_15 = (0x0002),
StopBits_20 = (0x0004)
};
enum Handshake
{
Handshake_None,
Handshake_XonXoff,
Handshake_RequestToSend,
Handshake_RequestToSendXonXoff
};
class SerialPort : public Port
{
public:
SerialPort();
~SerialPort();
// open the serial port
virtual int connect(const char* portName, int baudRate);
// write to the serial port
virtual int write(const uint8_t* ptr, int count);
// read a given number of bytes from the port.
virtual int read(uint8_t* buffer, int bytesToRead);
// close the port.
virtual void close();
virtual bool isClosed();
virtual int getRssi(const char* ifaceName)
{
unused(ifaceName);
return 0; // not supported on serial port.
}
private:
int setAttributes(int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs, int readTimeout, int writeTimeout);
class serialport_impl;
std::unique_ptr<serialport_impl> impl_;
};
#endif
| AirSim/MavLinkCom/src/serial_com/SerialPort.hpp/0 | {
"file_path": "AirSim/MavLinkCom/src/serial_com/SerialPort.hpp",
"repo_id": "AirSim",
"token_count": 574
} | 27 |
from __future__ import print_function
from .utils import *
from .types import *
import msgpackrpc #install as admin: pip install msgpack-rpc-python
import numpy as np #pip install numpy
import msgpack
import time
import math
import logging
class VehicleClient:
def __init__(self, ip = "", port = 41451, timeout_value = 3600):
if (ip == ""):
ip = "127.0.0.1"
self.client = msgpackrpc.Client(msgpackrpc.Address(ip, port), timeout = timeout_value, pack_encoding = 'utf-8', unpack_encoding = 'utf-8')
#----------------------------------- Common vehicle APIs ---------------------------------------------
def reset(self):
"""
Reset the vehicle to its original starting state
Note that you must call `enableApiControl` and `armDisarm` again after the call to reset
"""
self.client.call('reset')
def ping(self):
"""
If connection is established then this call will return true otherwise it will be blocked until timeout
Returns:
bool:
"""
return self.client.call('ping')
def getClientVersion(self):
return 1 # sync with C++ client
def getServerVersion(self):
return self.client.call('getServerVersion')
def getMinRequiredServerVersion(self):
return 1 # sync with C++ client
def getMinRequiredClientVersion(self):
return self.client.call('getMinRequiredClientVersion')
#basic flight control
def enableApiControl(self, is_enabled, vehicle_name = ''):
"""
Enables or disables API control for vehicle corresponding to vehicle_name
Args:
is_enabled (bool): True to enable, False to disable API control
vehicle_name (str, optional): Name of the vehicle to send this command to
"""
self.client.call('enableApiControl', is_enabled, vehicle_name)
def isApiControlEnabled(self, vehicle_name = ''):
"""
Returns true if API control is established.
If false (which is default) then API calls would be ignored. After a successful call to `enableApiControl`, `isApiControlEnabled` should return true.
Args:
vehicle_name (str, optional): Name of the vehicle
Returns:
bool: If API control is enabled
"""
return self.client.call('isApiControlEnabled', vehicle_name)
def armDisarm(self, arm, vehicle_name = ''):
"""
Arms or disarms vehicle
Args:
arm (bool): True to arm, False to disarm the vehicle
vehicle_name (str, optional): Name of the vehicle to send this command to
Returns:
bool: Success
"""
return self.client.call('armDisarm', arm, vehicle_name)
def simPause(self, is_paused):
"""
Pauses simulation
Args:
is_paused (bool): True to pause the simulation, False to release
"""
self.client.call('simPause', is_paused)
def simIsPause(self):
"""
Returns true if the simulation is paused
Returns:
bool: If the simulation is paused
"""
return self.client.call("simIsPaused")
def simContinueForTime(self, seconds):
"""
Continue the simulation for the specified number of seconds
Args:
seconds (float): Time to run the simulation for
"""
self.client.call('simContinueForTime', seconds)
def simContinueForFrames(self, frames):
"""
Continue (or resume if paused) the simulation for the specified number of frames, after which the simulation will be paused.
Args:
frames (int): Frames to run the simulation for
"""
self.client.call('simContinueForFrames', frames)
def getHomeGeoPoint(self, vehicle_name = ''):
"""
Get the Home location of the vehicle
Args:
vehicle_name (str, optional): Name of vehicle to get home location of
Returns:
GeoPoint: Home location of the vehicle
"""
return GeoPoint.from_msgpack(self.client.call('getHomeGeoPoint', vehicle_name))
def confirmConnection(self):
"""
Checks state of connection every 1 sec and reports it in Console so user can see the progress for connection.
"""
if self.ping():
print("Connected!")
else:
print("Ping returned false!")
server_ver = self.getServerVersion()
client_ver = self.getClientVersion()
server_min_ver = self.getMinRequiredServerVersion()
client_min_ver = self.getMinRequiredClientVersion()
ver_info = "Client Ver:" + str(client_ver) + " (Min Req: " + str(client_min_ver) + \
"), Server Ver:" + str(server_ver) + " (Min Req: " + str(server_min_ver) + ")"
if server_ver < server_min_ver:
print(ver_info, file=sys.stderr)
print("AirSim server is of older version and not supported by this client. Please upgrade!")
elif client_ver < client_min_ver:
print(ver_info, file=sys.stderr)
print("AirSim client is of older version and not supported by this server. Please upgrade!")
else:
print(ver_info)
print('')
def simSetLightIntensity(self, light_name, intensity):
"""
Change intensity of named light
Args:
light_name (str): Name of light to change
intensity (float): New intensity value
Returns:
bool: True if successful, otherwise False
"""
return self.client.call("simSetLightIntensity", light_name, intensity)
def simSwapTextures(self, tags, tex_id = 0, component_id = 0, material_id = 0):
"""
Runtime Swap Texture API
See https://microsoft.github.io/AirSim/retexturing/ for details
Args:
tags (str): string of "," or ", " delimited tags to identify on which actors to perform the swap
tex_id (int, optional): indexes the array of textures assigned to each actor undergoing a swap
If out-of-bounds for some object's texture set, it will be taken modulo the number of textures that were available
component_id (int, optional):
material_id (int, optional):
Returns:
list[str]: List of objects which matched the provided tags and had the texture swap perfomed
"""
return self.client.call("simSwapTextures", tags, tex_id, component_id, material_id)
def simSetObjectMaterial(self, object_name, material_name, component_id = 0):
"""
Runtime Swap Texture API
See https://microsoft.github.io/AirSim/retexturing/ for details
Args:
object_name (str): name of object to set material for
material_name (str): name of material to set for object
component_id (int, optional) : index of material elements
Returns:
bool: True if material was set
"""
return self.client.call("simSetObjectMaterial", object_name, material_name, component_id)
def simSetObjectMaterialFromTexture(self, object_name, texture_path, component_id = 0):
"""
Runtime Swap Texture API
See https://microsoft.github.io/AirSim/retexturing/ for details
Args:
object_name (str): name of object to set material for
texture_path (str): path to texture to set for object
component_id (int, optional) : index of material elements
Returns:
bool: True if material was set
"""
return self.client.call("simSetObjectMaterialFromTexture", object_name, texture_path, component_id)
# time-of-day control
#time - of - day control
def simSetTimeOfDay(self, is_enabled, start_datetime = "", is_start_datetime_dst = False, celestial_clock_speed = 1, update_interval_secs = 60, move_sun = True):
"""
Control the position of Sun in the environment
Sun's position is computed using the coordinates specified in `OriginGeopoint` in settings for the date-time specified in the argument,
else if the string is empty, current date & time is used
Args:
is_enabled (bool): True to enable time-of-day effect, False to reset the position to original
start_datetime (str, optional): Date & Time in %Y-%m-%d %H:%M:%S format, e.g. `2018-02-12 15:20:00`
is_start_datetime_dst (bool, optional): True to adjust for Daylight Savings Time
celestial_clock_speed (float, optional): Run celestial clock faster or slower than simulation clock
E.g. Value 100 means for every 1 second of simulation clock, Sun's position is advanced by 100 seconds
so Sun will move in sky much faster
update_interval_secs (float, optional): Interval to update the Sun's position
move_sun (bool, optional): Whether or not to move the Sun
"""
self.client.call('simSetTimeOfDay', is_enabled, start_datetime, is_start_datetime_dst, celestial_clock_speed, update_interval_secs, move_sun)
#weather
def simEnableWeather(self, enable):
"""
Enable Weather effects. Needs to be called before using `simSetWeatherParameter` API
Args:
enable (bool): True to enable, False to disable
"""
self.client.call('simEnableWeather', enable)
def simSetWeatherParameter(self, param, val):
"""
Enable various weather effects
Args:
param (WeatherParameter): Weather effect to be enabled
val (float): Intensity of the effect, Range 0-1
"""
self.client.call('simSetWeatherParameter', param, val)
#camera control
#simGetImage returns compressed png in array of bytes
#image_type uses one of the ImageType members
def simGetImage(self, camera_name, image_type, vehicle_name = '', external = False):
"""
Get a single image
Returns bytes of png format image which can be dumped into abinary file to create .png image
`string_to_uint8_array()` can be used to convert into Numpy unit8 array
See https://microsoft.github.io/AirSim/image_apis/ for details
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
image_type (ImageType): Type of image required
vehicle_name (str, optional): Name of the vehicle with the camera
external (bool, optional): Whether the camera is an External Camera
Returns:
Binary string literal of compressed png image
"""
#todo : in future remove below, it's only for compatibility to pre v1.2
camera_name = str(camera_name)
#because this method returns std::vector < uint8>, msgpack decides to encode it as a string unfortunately.
result = self.client.call('simGetImage', camera_name, image_type, vehicle_name, external)
if (result == "" or result == "\0"):
return None
return result
#camera control
#simGetImage returns compressed png in array of bytes
#image_type uses one of the ImageType members
def simGetImages(self, requests, vehicle_name = '', external = False):
"""
Get multiple images
See https://microsoft.github.io/AirSim/image_apis/ for details and examples
Args:
requests (list[ImageRequest]): Images required
vehicle_name (str, optional): Name of vehicle associated with the camera
external (bool, optional): Whether the camera is an External Camera
Returns:
list[ImageResponse]:
"""
responses_raw = self.client.call('simGetImages', requests, vehicle_name, external)
return [ImageResponse.from_msgpack(response_raw) for response_raw in responses_raw]
#CinemAirSim
def simGetPresetLensSettings(self, camera_name, vehicle_name = '', external = False):
result = self.client.call('simGetPresetLensSettings', camera_name, vehicle_name, external)
if (result == "" or result == "\0"):
return None
return result
def simGetLensSettings(self, camera_name, vehicle_name = '', external = False):
result = self.client.call('simGetLensSettings', camera_name, vehicle_name, external)
if (result == "" or result == "\0"):
return None
return result
def simSetPresetLensSettings(self, preset_lens_settings, camera_name, vehicle_name = '', external = False):
self.client.call("simSetPresetLensSettings", preset_lens_settings, camera_name, vehicle_name, external)
def simGetPresetFilmbackSettings(self, camera_name, vehicle_name = '', external = False):
result = self.client.call('simGetPresetFilmbackSettings', camera_name, vehicle_name, external)
if (result == "" or result == "\0"):
return None
return result
def simSetPresetFilmbackSettings(self, preset_filmback_settings, camera_name, vehicle_name = '', external = False):
self.client.call("simSetPresetFilmbackSettings", preset_filmback_settings, camera_name, vehicle_name, external)
def simGetFilmbackSettings(self, camera_name, vehicle_name = '', external = False):
result = self.client.call('simGetFilmbackSettings', camera_name, vehicle_name, external)
if (result == "" or result == "\0"):
return None
return result
def simSetFilmbackSettings(self, sensor_width, sensor_height, camera_name, vehicle_name = '', external = False):
return self.client.call("simSetFilmbackSettings", sensor_width, sensor_height, camera_name, vehicle_name, external)
def simGetFocalLength(self, camera_name, vehicle_name = '', external = False):
return self.client.call("simGetFocalLength", camera_name, vehicle_name, external)
def simSetFocalLength(self, focal_length, camera_name, vehicle_name = '', external = False):
self.client.call("simSetFocalLength", focal_length, camera_name, vehicle_name, external)
def simEnableManualFocus(self, enable, camera_name, vehicle_name = '', external = False):
self.client.call("simEnableManualFocus", enable, camera_name, vehicle_name, external)
def simGetFocusDistance(self, camera_name, vehicle_name = '', external = False):
return self.client.call("simGetFocusDistance", camera_name, vehicle_name, external)
def simSetFocusDistance(self, focus_distance, camera_name, vehicle_name = '', external = False):
self.client.call("simSetFocusDistance", focus_distance, camera_name, vehicle_name, external)
def simGetFocusAperture(self, camera_name, vehicle_name = '', external = False):
return self.client.call("simGetFocusAperture", camera_name, vehicle_name, external)
def simSetFocusAperture(self, focus_aperture, camera_name, vehicle_name = '', external = False):
self.client.call("simSetFocusAperture", focus_aperture, camera_name, vehicle_name, external)
def simEnableFocusPlane(self, enable, camera_name, vehicle_name = '', external = False):
self.client.call("simEnableFocusPlane", enable, camera_name, vehicle_name, external)
def simGetCurrentFieldOfView(self, camera_name, vehicle_name = '', external = False):
return self.client.call("simGetCurrentFieldOfView", camera_name, vehicle_name, external)
#End CinemAirSim
def simTestLineOfSightToPoint(self, point, vehicle_name = ''):
"""
Returns whether the target point is visible from the perspective of the inputted vehicle
Args:
point (GeoPoint): target point
vehicle_name (str, optional): Name of vehicle
Returns:
[bool]: Success
"""
return self.client.call('simTestLineOfSightToPoint', point, vehicle_name)
def simTestLineOfSightBetweenPoints(self, point1, point2):
"""
Returns whether the target point is visible from the perspective of the source point
Args:
point1 (GeoPoint): source point
point2 (GeoPoint): target point
Returns:
[bool]: Success
"""
return self.client.call('simTestLineOfSightBetweenPoints', point1, point2)
def simGetWorldExtents(self):
"""
Returns a list of GeoPoints representing the minimum and maximum extents of the world
Returns:
list[GeoPoint]
"""
responses_raw = self.client.call('simGetWorldExtents')
return [GeoPoint.from_msgpack(response_raw) for response_raw in responses_raw]
def simRunConsoleCommand(self, command):
"""
Allows the client to execute a command in Unreal's native console, via an API.
Affords access to the countless built-in commands such as "stat unit", "stat fps", "open [map]", adjust any config settings, etc. etc.
Allows the user to create bespoke APIs very easily, by adding a custom event to the level blueprint, and then calling the console command "ce MyEventName [args]". No recompilation of AirSim needed!
Args:
command ([string]): Desired Unreal Engine Console command to run
Returns:
[bool]: Success
"""
return self.client.call('simRunConsoleCommand', command)
#gets the static meshes in the unreal scene
def simGetMeshPositionVertexBuffers(self):
"""
Returns the static meshes that make up the scene
See https://microsoft.github.io/AirSim/meshes/ for details and how to use this
Returns:
list[MeshPositionVertexBuffersResponse]:
"""
responses_raw = self.client.call('simGetMeshPositionVertexBuffers')
return [MeshPositionVertexBuffersResponse.from_msgpack(response_raw) for response_raw in responses_raw]
def simGetCollisionInfo(self, vehicle_name = ''):
"""
Args:
vehicle_name (str, optional): Name of the Vehicle to get the info of
Returns:
CollisionInfo:
"""
return CollisionInfo.from_msgpack(self.client.call('simGetCollisionInfo', vehicle_name))
def simSetVehiclePose(self, pose, ignore_collision, vehicle_name = ''):
"""
Set the pose of the vehicle
If you don't want to change position (or orientation) then just set components of position (or orientation) to floating point nan values
Args:
pose (Pose): Desired Pose pf the vehicle
ignore_collision (bool): Whether to ignore any collision or not
vehicle_name (str, optional): Name of the vehicle to move
"""
self.client.call('simSetVehiclePose', pose, ignore_collision, vehicle_name)
def simGetVehiclePose(self, vehicle_name = ''):
"""
The position inside the returned Pose is in the frame of the vehicle's starting point
Args:
vehicle_name (str, optional): Name of the vehicle to get the Pose of
Returns:
Pose:
"""
pose = self.client.call('simGetVehiclePose', vehicle_name)
return Pose.from_msgpack(pose)
def simSetTraceLine(self, color_rgba, thickness=1.0, vehicle_name = ''):
"""
Modify the color and thickness of the line when Tracing is enabled
Tracing can be enabled by pressing T in the Editor or setting `EnableTrace` to `True` in the Vehicle Settings
Args:
color_rgba (list): desired RGBA values from 0.0 to 1.0
thickness (float, optional): Thickness of the line
vehicle_name (string, optional): Name of the vehicle to set Trace line values for
"""
self.client.call('simSetTraceLine', color_rgba, thickness, vehicle_name)
def simGetObjectPose(self, object_name):
"""
The position inside the returned Pose is in the world frame
Args:
object_name (str): Object to get the Pose of
Returns:
Pose:
"""
pose = self.client.call('simGetObjectPose', object_name)
return Pose.from_msgpack(pose)
def simSetObjectPose(self, object_name, pose, teleport = True):
"""
Set the pose of the object(actor) in the environment
The specified actor must have Mobility set to movable, otherwise there will be undefined behaviour.
See https://www.unrealengine.com/en-US/blog/moving-physical-objects for details on how to set Mobility and the effect of Teleport parameter
Args:
object_name (str): Name of the object(actor) to move
pose (Pose): Desired Pose of the object
teleport (bool, optional): Whether to move the object immediately without affecting their velocity
Returns:
bool: If the move was successful
"""
return self.client.call('simSetObjectPose', object_name, pose, teleport)
def simGetObjectScale(self, object_name):
"""
Gets scale of an object in the world
Args:
object_name (str): Object to get the scale of
Returns:
airsim.Vector3r: Scale
"""
scale = self.client.call('simGetObjectScale', object_name)
return Vector3r.from_msgpack(scale)
def simSetObjectScale(self, object_name, scale_vector):
"""
Sets scale of an object in the world
Args:
object_name (str): Object to set the scale of
scale_vector (airsim.Vector3r): Desired scale of object
Returns:
bool: True if scale change was successful
"""
return self.client.call('simSetObjectScale', object_name, scale_vector)
def simListSceneObjects(self, name_regex = '.*'):
"""
Lists the objects present in the environment
Default behaviour is to list all objects, regex can be used to return smaller list of matching objects or actors
Args:
name_regex (str, optional): String to match actor names against, e.g. "Cylinder.*"
Returns:
list[str]: List containing all the names
"""
return self.client.call('simListSceneObjects', name_regex)
def simLoadLevel(self, level_name):
"""
Loads a level specified by its name
Args:
level_name (str): Name of the level to load
Returns:
bool: True if the level was successfully loaded
"""
return self.client.call('simLoadLevel', level_name)
def simListAssets(self):
"""
Lists all the assets present in the Asset Registry
Returns:
list[str]: Names of all the assets
"""
return self.client.call('simListAssets')
def simSpawnObject(self, object_name, asset_name, pose, scale, physics_enabled=False, is_blueprint=False):
"""Spawned selected object in the world
Args:
object_name (str): Desired name of new object
asset_name (str): Name of asset(mesh) in the project database
pose (airsim.Pose): Desired pose of object
scale (airsim.Vector3r): Desired scale of object
physics_enabled (bool, optional): Whether to enable physics for the object
is_blueprint (bool, optional): Whether to spawn a blueprint or an actor
Returns:
str: Name of spawned object, in case it had to be modified
"""
return self.client.call('simSpawnObject', object_name, asset_name, pose, scale, physics_enabled, is_blueprint)
def simDestroyObject(self, object_name):
"""Removes selected object from the world
Args:
object_name (str): Name of object to be removed
Returns:
bool: True if object is queued up for removal
"""
return self.client.call('simDestroyObject', object_name)
def simSetSegmentationObjectID(self, mesh_name, object_id, is_name_regex = False):
"""
Set segmentation ID for specific objects
See https://microsoft.github.io/AirSim/image_apis/#segmentation for details
Args:
mesh_name (str): Name of the mesh to set the ID of (supports regex)
object_id (int): Object ID to be set, range 0-255
RBG values for IDs can be seen at https://microsoft.github.io/AirSim/seg_rgbs.txt
is_name_regex (bool, optional): Whether the mesh name is a regex
Returns:
bool: If the mesh was found
"""
return self.client.call('simSetSegmentationObjectID', mesh_name, object_id, is_name_regex)
def simGetSegmentationObjectID(self, mesh_name):
"""
Returns Object ID for the given mesh name
Mapping of Object IDs to RGB values can be seen at https://microsoft.github.io/AirSim/seg_rgbs.txt
Args:
mesh_name (str): Name of the mesh to get the ID of
"""
return self.client.call('simGetSegmentationObjectID', mesh_name)
def simAddDetectionFilterMeshName(self, camera_name, image_type, mesh_name, vehicle_name = '', external = False):
"""
Add mesh name to detect in wild card format
For example: simAddDetectionFilterMeshName("Car_*") will detect all instance named "Car_*"
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
image_type (ImageType): Type of image required
mesh_name (str): mesh name in wild card format
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
"""
self.client.call('simAddDetectionFilterMeshName', camera_name, image_type, mesh_name, vehicle_name, external)
def simSetDetectionFilterRadius(self, camera_name, image_type, radius_cm, vehicle_name = '', external = False):
"""
Set detection radius for all cameras
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
image_type (ImageType): Type of image required
radius_cm (int): Radius in [cm]
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
"""
self.client.call('simSetDetectionFilterRadius', camera_name, image_type, radius_cm, vehicle_name, external)
def simClearDetectionMeshNames(self, camera_name, image_type, vehicle_name = '', external = False):
"""
Clear all mesh names from detection filter
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
image_type (ImageType): Type of image required
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
"""
self.client.call('simClearDetectionMeshNames', camera_name, image_type, vehicle_name, external)
def simGetDetections(self, camera_name, image_type, vehicle_name = '', external = False):
"""
Get current detections
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
image_type (ImageType): Type of image required
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
Returns:
DetectionInfo array
"""
responses_raw = self.client.call('simGetDetections', camera_name, image_type, vehicle_name, external)
return [DetectionInfo.from_msgpack(response_raw) for response_raw in responses_raw]
def simPrintLogMessage(self, message, message_param = "", severity = 0):
"""
Prints the specified message in the simulator's window.
If message_param is supplied, then it's printed next to the message and in that case if this API is called with same message value
but different message_param again then previous line is overwritten with new line (instead of API creating new line on display).
For example, `simPrintLogMessage("Iteration: ", to_string(i))` keeps updating same line on display when API is called with different values of i.
The valid values of severity parameter is 0 to 3 inclusive that corresponds to different colors.
Args:
message (str): Message to be printed
message_param (str, optional): Parameter to be printed next to the message
severity (int, optional): Range 0-3, inclusive, corresponding to the severity of the message
"""
self.client.call('simPrintLogMessage', message, message_param, severity)
def simGetCameraInfo(self, camera_name, vehicle_name = '', external=False):
"""
Get details about the camera
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
Returns:
CameraInfo:
"""
#TODO : below str() conversion is only needed for legacy reason and should be removed in future
return CameraInfo.from_msgpack(self.client.call('simGetCameraInfo', str(camera_name), vehicle_name, external))
def simGetDistortionParams(self, camera_name, vehicle_name = '', external = False):
"""
Get camera distortion parameters
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
Returns:
List (float): List of distortion parameter values corresponding to K1, K2, K3, P1, P2 respectively.
"""
return self.client.call('simGetDistortionParams', str(camera_name), vehicle_name, external)
def simSetDistortionParams(self, camera_name, distortion_params, vehicle_name = '', external = False):
"""
Set camera distortion parameters
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
distortion_params (dict): Dictionary of distortion param names and corresponding values
{"K1": 0.0, "K2": 0.0, "K3": 0.0, "P1": 0.0, "P2": 0.0}
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
"""
for param_name, value in distortion_params.items():
self.simSetDistortionParam(camera_name, param_name, value, vehicle_name, external)
def simSetDistortionParam(self, camera_name, param_name, value, vehicle_name = '', external = False):
"""
Set single camera distortion parameter
Args:
camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used
param_name (str): Name of distortion parameter
value (float): Value of distortion parameter
vehicle_name (str, optional): Vehicle which the camera is associated with
external (bool, optional): Whether the camera is an External Camera
"""
self.client.call('simSetDistortionParam', str(camera_name), param_name, value, vehicle_name, external)
def simSetCameraPose(self, camera_name, pose, vehicle_name = '', external = False):
"""
- Control the pose of a selected camera
Args:
camera_name (str): Name of the camera to be controlled
pose (Pose): Pose representing the desired position and orientation of the camera
vehicle_name (str, optional): Name of vehicle which the camera corresponds to
external (bool, optional): Whether the camera is an External Camera
"""
#TODO : below str() conversion is only needed for legacy reason and should be removed in future
self.client.call('simSetCameraPose', str(camera_name), pose, vehicle_name, external)
def simSetCameraFov(self, camera_name, fov_degrees, vehicle_name = '', external = False):
"""
- Control the field of view of a selected camera
Args:
camera_name (str): Name of the camera to be controlled
fov_degrees (float): Value of field of view in degrees
vehicle_name (str, optional): Name of vehicle which the camera corresponds to
external (bool, optional): Whether the camera is an External Camera
"""
#TODO : below str() conversion is only needed for legacy reason and should be removed in future
self.client.call('simSetCameraFov', str(camera_name), fov_degrees, vehicle_name, external)
def simGetGroundTruthKinematics(self, vehicle_name = ''):
"""
Get Ground truth kinematics of the vehicle
The position inside the returned KinematicsState is in the frame of the vehicle's starting point
Args:
vehicle_name (str, optional): Name of the vehicle
Returns:
KinematicsState: Ground truth of the vehicle
"""
kinematics_state = self.client.call('simGetGroundTruthKinematics', vehicle_name)
return KinematicsState.from_msgpack(kinematics_state)
simGetGroundTruthKinematics.__annotations__ = {'return': KinematicsState}
def simSetKinematics(self, state, ignore_collision, vehicle_name = ''):
"""
Set the kinematics state of the vehicle
If you don't want to change position (or orientation) then just set components of position (or orientation) to floating point nan values
Args:
state (KinematicsState): Desired Pose pf the vehicle
ignore_collision (bool): Whether to ignore any collision or not
vehicle_name (str, optional): Name of the vehicle to move
"""
self.client.call('simSetKinematics', state, ignore_collision, vehicle_name)
def simGetGroundTruthEnvironment(self, vehicle_name = ''):
"""
Get ground truth environment state
The position inside the returned EnvironmentState is in the frame of the vehicle's starting point
Args:
vehicle_name (str, optional): Name of the vehicle
Returns:
EnvironmentState: Ground truth environment state
"""
env_state = self.client.call('simGetGroundTruthEnvironment', vehicle_name)
return EnvironmentState.from_msgpack(env_state)
simGetGroundTruthEnvironment.__annotations__ = {'return': EnvironmentState}
#sensor APIs
def getImuData(self, imu_name = '', vehicle_name = ''):
"""
Args:
imu_name (str, optional): Name of IMU to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
ImuData:
"""
return ImuData.from_msgpack(self.client.call('getImuData', imu_name, vehicle_name))
def getBarometerData(self, barometer_name = '', vehicle_name = ''):
"""
Args:
barometer_name (str, optional): Name of Barometer to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
BarometerData:
"""
return BarometerData.from_msgpack(self.client.call('getBarometerData', barometer_name, vehicle_name))
def getMagnetometerData(self, magnetometer_name = '', vehicle_name = ''):
"""
Args:
magnetometer_name (str, optional): Name of Magnetometer to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
MagnetometerData:
"""
return MagnetometerData.from_msgpack(self.client.call('getMagnetometerData', magnetometer_name, vehicle_name))
def getGpsData(self, gps_name = '', vehicle_name = ''):
"""
Args:
gps_name (str, optional): Name of GPS to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
GpsData:
"""
return GpsData.from_msgpack(self.client.call('getGpsData', gps_name, vehicle_name))
def getDistanceSensorData(self, distance_sensor_name = '', vehicle_name = ''):
"""
Args:
distance_sensor_name (str, optional): Name of Distance Sensor to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
DistanceSensorData:
"""
return DistanceSensorData.from_msgpack(self.client.call('getDistanceSensorData', distance_sensor_name, vehicle_name))
def getLidarData(self, lidar_name = '', vehicle_name = ''):
"""
Args:
lidar_name (str, optional): Name of Lidar to get data from, specified in settings.json
vehicle_name (str, optional): Name of vehicle to which the sensor corresponds to
Returns:
LidarData:
"""
return LidarData.from_msgpack(self.client.call('getLidarData', lidar_name, vehicle_name))
def simGetLidarSegmentation(self, lidar_name = '', vehicle_name = ''):
"""
NOTE: Deprecated API, use `getLidarData()` API instead
Returns Segmentation ID of each point's collided object in the last Lidar update
Args:
lidar_name (str, optional): Name of Lidar sensor
vehicle_name (str, optional): Name of the vehicle wth the sensor
Returns:
list[int]: Segmentation IDs of the objects
"""
logging.warning("simGetLidarSegmentation API is deprecated, use getLidarData() API instead")
return self.getLidarData(lidar_name, vehicle_name).segmentation
#Plotting APIs
def simFlushPersistentMarkers(self):
"""
Clear any persistent markers - those plotted with setting `is_persistent=True` in the APIs below
"""
self.client.call('simFlushPersistentMarkers')
def simPlotPoints(self, points, color_rgba=[1.0, 0.0, 0.0, 1.0], size = 10.0, duration = -1.0, is_persistent = False):
"""
Plot a list of 3D points in World NED frame
Args:
points (list[Vector3r]): List of Vector3r objects
color_rgba (list, optional): desired RGBA values from 0.0 to 1.0
size (float, optional): Size of plotted point
duration (float, optional): Duration (seconds) to plot for
is_persistent (bool, optional): If set to True, the desired object will be plotted for infinite time.
"""
self.client.call('simPlotPoints', points, color_rgba, size, duration, is_persistent)
def simPlotLineStrip(self, points, color_rgba=[1.0, 0.0, 0.0, 1.0], thickness = 5.0, duration = -1.0, is_persistent = False):
"""
Plots a line strip in World NED frame, defined from points[0] to points[1], points[1] to points[2], ... , points[n-2] to points[n-1]
Args:
points (list[Vector3r]): List of 3D locations of line start and end points, specified as Vector3r objects
color_rgba (list, optional): desired RGBA values from 0.0 to 1.0
thickness (float, optional): Thickness of line
duration (float, optional): Duration (seconds) to plot for
is_persistent (bool, optional): If set to True, the desired object will be plotted for infinite time.
"""
self.client.call('simPlotLineStrip', points, color_rgba, thickness, duration, is_persistent)
def simPlotLineList(self, points, color_rgba=[1.0, 0.0, 0.0, 1.0], thickness = 5.0, duration = -1.0, is_persistent = False):
"""
Plots a line strip in World NED frame, defined from points[0] to points[1], points[2] to points[3], ... , points[n-2] to points[n-1]
Args:
points (list[Vector3r]): List of 3D locations of line start and end points, specified as Vector3r objects. Must be even
color_rgba (list, optional): desired RGBA values from 0.0 to 1.0
thickness (float, optional): Thickness of line
duration (float, optional): Duration (seconds) to plot for
is_persistent (bool, optional): If set to True, the desired object will be plotted for infinite time.
"""
self.client.call('simPlotLineList', points, color_rgba, thickness, duration, is_persistent)
def simPlotArrows(self, points_start, points_end, color_rgba=[1.0, 0.0, 0.0, 1.0], thickness = 5.0, arrow_size = 2.0, duration = -1.0, is_persistent = False):
"""
Plots a list of arrows in World NED frame, defined from points_start[0] to points_end[0], points_start[1] to points_end[1], ... , points_start[n-1] to points_end[n-1]
Args:
points_start (list[Vector3r]): List of 3D start positions of arrow start positions, specified as Vector3r objects
points_end (list[Vector3r]): List of 3D end positions of arrow start positions, specified as Vector3r objects
color_rgba (list, optional): desired RGBA values from 0.0 to 1.0
thickness (float, optional): Thickness of line
arrow_size (float, optional): Size of arrow head
duration (float, optional): Duration (seconds) to plot for
is_persistent (bool, optional): If set to True, the desired object will be plotted for infinite time.
"""
self.client.call('simPlotArrows', points_start, points_end, color_rgba, thickness, arrow_size, duration, is_persistent)
def simPlotStrings(self, strings, positions, scale = 5, color_rgba=[1.0, 0.0, 0.0, 1.0], duration = -1.0):
"""
Plots a list of strings at desired positions in World NED frame.
Args:
strings (list[String], optional): List of strings to plot
positions (list[Vector3r]): List of positions where the strings should be plotted. Should be in one-to-one correspondence with the strings' list
scale (float, optional): Font scale of transform name
color_rgba (list, optional): desired RGBA values from 0.0 to 1.0
duration (float, optional): Duration (seconds) to plot for
"""
self.client.call('simPlotStrings', strings, positions, scale, color_rgba, duration)
def simPlotTransforms(self, poses, scale = 5.0, thickness = 5.0, duration = -1.0, is_persistent = False):
"""
Plots a list of transforms in World NED frame.
Args:
poses (list[Pose]): List of Pose objects representing the transforms to plot
scale (float, optional): Length of transforms' axes
thickness (float, optional): Thickness of transforms' axes
duration (float, optional): Duration (seconds) to plot for
is_persistent (bool, optional): If set to True, the desired object will be plotted for infinite time.
"""
self.client.call('simPlotTransforms', poses, scale, thickness, duration, is_persistent)
def simPlotTransformsWithNames(self, poses, names, tf_scale = 5.0, tf_thickness = 5.0, text_scale = 10.0, text_color_rgba = [1.0, 0.0, 0.0, 1.0], duration = -1.0):
"""
Plots a list of transforms with their names in World NED frame.
Args:
poses (list[Pose]): List of Pose objects representing the transforms to plot
names (list[string]): List of strings with one-to-one correspondence to list of poses
tf_scale (float, optional): Length of transforms' axes
tf_thickness (float, optional): Thickness of transforms' axes
text_scale (float, optional): Font scale of transform name
text_color_rgba (list, optional): desired RGBA values from 0.0 to 1.0 for the transform name
duration (float, optional): Duration (seconds) to plot for
"""
self.client.call('simPlotTransformsWithNames', poses, names, tf_scale, tf_thickness, text_scale, text_color_rgba, duration)
def cancelLastTask(self, vehicle_name = ''):
"""
Cancel previous Async task
Args:
vehicle_name (str, optional): Name of the vehicle
"""
self.client.call('cancelLastTask', vehicle_name)
#Recording APIs
def startRecording(self):
"""
Start Recording
Recording will be done according to the settings
"""
self.client.call('startRecording')
def stopRecording(self):
"""
Stop Recording
"""
self.client.call('stopRecording')
def isRecording(self):
"""
Whether Recording is running or not
Returns:
bool: True if Recording, else False
"""
return self.client.call('isRecording')
def simSetWind(self, wind):
"""
Set simulated wind, in World frame, NED direction, m/s
Args:
wind (Vector3r): Wind, in World frame, NED direction, in m/s
"""
self.client.call('simSetWind', wind)
def simCreateVoxelGrid(self, position, x, y, z, res, of):
"""
Construct and save a binvox-formatted voxel grid of environment
Args:
position (Vector3r): Position around which voxel grid is centered in m
x, y, z (int): Size of each voxel grid dimension in m
res (float): Resolution of voxel grid in m
of (str): Name of output file to save voxel grid as
Returns:
bool: True if output written to file successfully, else False
"""
return self.client.call('simCreateVoxelGrid', position, x, y, z, res, of)
#Add new vehicle via RPC
def simAddVehicle(self, vehicle_name, vehicle_type, pose, pawn_path = ""):
"""
Create vehicle at runtime
Args:
vehicle_name (str): Name of the vehicle being created
vehicle_type (str): Type of vehicle, e.g. "simpleflight"
pose (Pose): Initial pose of the vehicle
pawn_path (str, optional): Vehicle blueprint path, default empty wbich uses the default blueprint for the vehicle type
Returns:
bool: Whether vehicle was created
"""
return self.client.call('simAddVehicle', vehicle_name, vehicle_type, pose, pawn_path)
def listVehicles(self):
"""
Lists the names of current vehicles
Returns:
list[str]: List containing names of all vehicles
"""
return self.client.call('listVehicles')
def getSettingsString(self):
"""
Fetch the settings text being used by AirSim
Returns:
str: Settings text in JSON format
"""
return self.client.call('getSettingsString')
#----------------------------------- Multirotor APIs ---------------------------------------------
class MultirotorClient(VehicleClient, object):
def __init__(self, ip = "", port = 41451, timeout_value = 3600):
super(MultirotorClient, self).__init__(ip, port, timeout_value)
def takeoffAsync(self, timeout_sec = 20, vehicle_name = ''):
"""
Takeoff vehicle to 3m above ground. Vehicle should not be moving when this API is used
Args:
timeout_sec (int, optional): Timeout for the vehicle to reach desired altitude
vehicle_name (str, optional): Name of the vehicle to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('takeoff', timeout_sec, vehicle_name)
def landAsync(self, timeout_sec = 60, vehicle_name = ''):
"""
Land the vehicle
Args:
timeout_sec (int, optional): Timeout for the vehicle to land
vehicle_name (str, optional): Name of the vehicle to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('land', timeout_sec, vehicle_name)
def goHomeAsync(self, timeout_sec = 3e+38, vehicle_name = ''):
"""
Return vehicle to Home i.e. Launch location
Args:
timeout_sec (int, optional): Timeout for the vehicle to reach desired altitude
vehicle_name (str, optional): Name of the vehicle to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('goHome', timeout_sec, vehicle_name)
#APIs for control
def moveByVelocityBodyFrameAsync(self, vx, vy, vz, duration, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(), vehicle_name = ''):
"""
Args:
vx (float): desired velocity in the X axis of the vehicle's local NED frame.
vy (float): desired velocity in the Y axis of the vehicle's local NED frame.
vz (float): desired velocity in the Z axis of the vehicle's local NED frame.
duration (float): Desired amount of time (seconds), to send this command for
drivetrain (DrivetrainType, optional):
yaw_mode (YawMode, optional):
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByVelocityBodyFrame', vx, vy, vz, duration, drivetrain, yaw_mode, vehicle_name)
def moveByVelocityZBodyFrameAsync(self, vx, vy, z, duration, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(), vehicle_name = ''):
"""
Args:
vx (float): desired velocity in the X axis of the vehicle's local NED frame
vy (float): desired velocity in the Y axis of the vehicle's local NED frame
z (float): desired Z value (in local NED frame of the vehicle)
duration (float): Desired amount of time (seconds), to send this command for
drivetrain (DrivetrainType, optional):
yaw_mode (YawMode, optional):
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByVelocityZBodyFrame', vx, vy, z, duration, drivetrain, yaw_mode, vehicle_name)
def moveByAngleZAsync(self, pitch, roll, z, yaw, duration, vehicle_name = ''):
logging.warning("moveByAngleZAsync API is deprecated, use moveByRollPitchYawZAsync() API instead")
return self.client.call_async('moveByRollPitchYawZ', roll, -pitch, -yaw, z, duration, vehicle_name)
def moveByAngleThrottleAsync(self, pitch, roll, throttle, yaw_rate, duration, vehicle_name = ''):
logging.warning("moveByAngleThrottleAsync API is deprecated, use moveByRollPitchYawrateThrottleAsync() API instead")
return self.client.call_async('moveByRollPitchYawrateThrottle', roll, -pitch, -yaw_rate, throttle, duration, vehicle_name)
def moveByVelocityAsync(self, vx, vy, vz, duration, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(), vehicle_name = ''):
"""
Args:
vx (float): desired velocity in world (NED) X axis
vy (float): desired velocity in world (NED) Y axis
vz (float): desired velocity in world (NED) Z axis
duration (float): Desired amount of time (seconds), to send this command for
drivetrain (DrivetrainType, optional):
yaw_mode (YawMode, optional):
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByVelocity', vx, vy, vz, duration, drivetrain, yaw_mode, vehicle_name)
def moveByVelocityZAsync(self, vx, vy, z, duration, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(), vehicle_name = ''):
return self.client.call_async('moveByVelocityZ', vx, vy, z, duration, drivetrain, yaw_mode, vehicle_name)
def moveOnPathAsync(self, path, velocity, timeout_sec = 3e+38, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(),
lookahead = -1, adaptive_lookahead = 1, vehicle_name = ''):
return self.client.call_async('moveOnPath', path, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead, vehicle_name)
def moveToPositionAsync(self, x, y, z, velocity, timeout_sec = 3e+38, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(),
lookahead = -1, adaptive_lookahead = 1, vehicle_name = ''):
return self.client.call_async('moveToPosition', x, y, z, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead, vehicle_name)
def moveToGPSAsync(self, latitude, longitude, altitude, velocity, timeout_sec = 3e+38, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(),
lookahead = -1, adaptive_lookahead = 1, vehicle_name = ''):
return self.client.call_async('moveToGPS', latitude, longitude, altitude, velocity, timeout_sec, drivetrain, yaw_mode, lookahead, adaptive_lookahead, vehicle_name)
def moveToZAsync(self, z, velocity, timeout_sec = 3e+38, yaw_mode = YawMode(), lookahead = -1, adaptive_lookahead = 1, vehicle_name = ''):
return self.client.call_async('moveToZ', z, velocity, timeout_sec, yaw_mode, lookahead, adaptive_lookahead, vehicle_name)
def moveByManualAsync(self, vx_max, vy_max, z_min, duration, drivetrain = DrivetrainType.MaxDegreeOfFreedom, yaw_mode = YawMode(), vehicle_name = ''):
"""
- Read current RC state and use it to control the vehicles.
Parameters sets up the constraints on velocity and minimum altitude while flying. If RC state is detected to violate these constraints
then that RC state would be ignored.
Args:
vx_max (float): max velocity allowed in x direction
vy_max (float): max velocity allowed in y direction
vz_max (float): max velocity allowed in z direction
z_min (float): min z allowed for vehicle position
duration (float): after this duration vehicle would switch back to non-manual mode
drivetrain (DrivetrainType): when ForwardOnly, vehicle rotates itself so that its front is always facing the direction of travel. If MaxDegreeOfFreedom then it doesn't do that (crab-like movement)
yaw_mode (YawMode): Specifies if vehicle should face at given angle (is_rate=False) or should be rotating around its axis at given rate (is_rate=True)
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByManual', vx_max, vy_max, z_min, duration, drivetrain, yaw_mode, vehicle_name)
def rotateToYawAsync(self, yaw, timeout_sec = 3e+38, margin = 5, vehicle_name = ''):
return self.client.call_async('rotateToYaw', yaw, timeout_sec, margin, vehicle_name)
def rotateByYawRateAsync(self, yaw_rate, duration, vehicle_name = ''):
return self.client.call_async('rotateByYawRate', yaw_rate, duration, vehicle_name)
def hoverAsync(self, vehicle_name = ''):
return self.client.call_async('hover', vehicle_name)
def moveByRC(self, rcdata = RCData(), vehicle_name = ''):
return self.client.call('moveByRC', rcdata, vehicle_name)
#low - level control API
def moveByMotorPWMsAsync(self, front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm, duration, vehicle_name = ''):
"""
- Directly control the motors using PWM values
Args:
front_right_pwm (float): PWM value for the front right motor (between 0.0 to 1.0)
rear_left_pwm (float): PWM value for the rear left motor (between 0.0 to 1.0)
front_left_pwm (float): PWM value for the front left motor (between 0.0 to 1.0)
rear_right_pwm (float): PWM value for the rear right motor (between 0.0 to 1.0)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByMotorPWMs', front_right_pwm, rear_left_pwm, front_left_pwm, rear_right_pwm, duration, vehicle_name)
def moveByRollPitchYawZAsync(self, roll, pitch, yaw, z, duration, vehicle_name = ''):
"""
- z is given in local NED frame of the vehicle.
- Roll angle, pitch angle, and yaw angle set points are given in **radians**, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll (float): Desired roll angle, in radians.
pitch (float): Desired pitch angle, in radians.
yaw (float): Desired yaw angle, in radians.
z (float): Desired Z value (in local NED frame of the vehicle)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByRollPitchYawZ', roll, -pitch, -yaw, z, duration, vehicle_name)
def moveByRollPitchYawThrottleAsync(self, roll, pitch, yaw, throttle, duration, vehicle_name = ''):
"""
- Desired throttle is between 0.0 to 1.0
- Roll angle, pitch angle, and yaw angle are given in **degrees** when using PX4 and in **radians** when using SimpleFlight, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll (float): Desired roll angle.
pitch (float): Desired pitch angle.
yaw (float): Desired yaw angle.
throttle (float): Desired throttle (between 0.0 to 1.0)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByRollPitchYawThrottle', roll, -pitch, -yaw, throttle, duration, vehicle_name)
def moveByRollPitchYawrateThrottleAsync(self, roll, pitch, yaw_rate, throttle, duration, vehicle_name = ''):
"""
- Desired throttle is between 0.0 to 1.0
- Roll angle, pitch angle, and yaw rate set points are given in **radians**, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll (float): Desired roll angle, in radians.
pitch (float): Desired pitch angle, in radians.
yaw_rate (float): Desired yaw rate, in radian per second.
throttle (float): Desired throttle (between 0.0 to 1.0)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByRollPitchYawrateThrottle', roll, -pitch, -yaw_rate, throttle, duration, vehicle_name)
def moveByRollPitchYawrateZAsync(self, roll, pitch, yaw_rate, z, duration, vehicle_name = ''):
"""
- z is given in local NED frame of the vehicle.
- Roll angle, pitch angle, and yaw rate set points are given in **radians**, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll (float): Desired roll angle, in radians.
pitch (float): Desired pitch angle, in radians.
yaw_rate (float): Desired yaw rate, in radian per second.
z (float): Desired Z value (in local NED frame of the vehicle)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByRollPitchYawrateZ', roll, -pitch, -yaw_rate, z, duration, vehicle_name)
def moveByAngleRatesZAsync(self, roll_rate, pitch_rate, yaw_rate, z, duration, vehicle_name = ''):
"""
- z is given in local NED frame of the vehicle.
- Roll rate, pitch rate, and yaw rate set points are given in **radians**, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll_rate (float): Desired roll rate, in radians / second
pitch_rate (float): Desired pitch rate, in radians / second
yaw_rate (float): Desired yaw rate, in radians / second
z (float): Desired Z value (in local NED frame of the vehicle)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByAngleRatesZ', roll_rate, -pitch_rate, -yaw_rate, z, duration, vehicle_name)
def moveByAngleRatesThrottleAsync(self, roll_rate, pitch_rate, yaw_rate, throttle, duration, vehicle_name = ''):
"""
- Desired throttle is between 0.0 to 1.0
- Roll rate, pitch rate, and yaw rate set points are given in **radians**, in the body frame.
- The body frame follows the Front Left Up (FLU) convention, and right-handedness.
- Frame Convention:
- X axis is along the **Front** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **roll** angle.
| Hence, rolling with a positive angle is equivalent to translating in the **right** direction, w.r.t. our FLU body frame.
- Y axis is along the **Left** direction of the quadrotor.
| Clockwise rotation about this axis defines a positive **pitch** angle.
| Hence, pitching with a positive angle is equivalent to translating in the **front** direction, w.r.t. our FLU body frame.
- Z axis is along the **Up** direction.
| Clockwise rotation about this axis defines a positive **yaw** angle.
| Hence, yawing with a positive angle is equivalent to rotated towards the **left** direction wrt our FLU body frame. Or in an anticlockwise fashion in the body XY / FL plane.
Args:
roll_rate (float): Desired roll rate, in radians / second
pitch_rate (float): Desired pitch rate, in radians / second
yaw_rate (float): Desired yaw rate, in radians / second
throttle (float): Desired throttle (between 0.0 to 1.0)
duration (float): Desired amount of time (seconds), to send this command for
vehicle_name (str, optional): Name of the multirotor to send this command to
Returns:
msgpackrpc.future.Future: future. call .join() to wait for method to finish. Example: client.METHOD().join()
"""
return self.client.call_async('moveByAngleRatesThrottle', roll_rate, -pitch_rate, -yaw_rate, throttle, duration, vehicle_name)
def setAngleRateControllerGains(self, angle_rate_gains=AngleRateControllerGains(), vehicle_name = ''):
"""
- Modifying these gains will have an affect on *ALL* move*() APIs.
This is because any velocity setpoint is converted to an angle level setpoint which is tracked with an angle level controllers.
That angle level setpoint is itself tracked with and angle rate controller.
- This function should only be called if the default angle rate control PID gains need to be modified.
Args:
angle_rate_gains (AngleRateControllerGains):
- Correspond to the roll, pitch, yaw axes, defined in the body frame.
- Pass AngleRateControllerGains() to reset gains to default recommended values.
vehicle_name (str, optional): Name of the multirotor to send this command to
"""
self.client.call('setAngleRateControllerGains', *(angle_rate_gains.to_lists()+(vehicle_name,)))
def setAngleLevelControllerGains(self, angle_level_gains=AngleLevelControllerGains(), vehicle_name = ''):
"""
- Sets angle level controller gains (used by any API setting angle references - for ex: moveByRollPitchYawZAsync(), moveByRollPitchYawThrottleAsync(), etc)
- Modifying these gains will also affect the behaviour of moveByVelocityAsync() API.
This is because the AirSim flight controller will track velocity setpoints by converting them to angle set points.
- This function should only be called if the default angle level control PID gains need to be modified.
- Passing AngleLevelControllerGains() sets gains to default airsim values.
Args:
angle_level_gains (AngleLevelControllerGains):
- Correspond to the roll, pitch, yaw axes, defined in the body frame.
- Pass AngleLevelControllerGains() to reset gains to default recommended values.
vehicle_name (str, optional): Name of the multirotor to send this command to
"""
self.client.call('setAngleLevelControllerGains', *(angle_level_gains.to_lists()+(vehicle_name,)))
def setVelocityControllerGains(self, velocity_gains=VelocityControllerGains(), vehicle_name = ''):
"""
- Sets velocity controller gains for moveByVelocityAsync().
- This function should only be called if the default velocity control PID gains need to be modified.
- Passing VelocityControllerGains() sets gains to default airsim values.
Args:
velocity_gains (VelocityControllerGains):
- Correspond to the world X, Y, Z axes.
- Pass VelocityControllerGains() to reset gains to default recommended values.
- Modifying velocity controller gains will have an affect on the behaviour of moveOnSplineAsync() and moveOnSplineVelConstraintsAsync(), as they both use velocity control to track the trajectory.
vehicle_name (str, optional): Name of the multirotor to send this command to
"""
self.client.call('setVelocityControllerGains', *(velocity_gains.to_lists()+(vehicle_name,)))
def setPositionControllerGains(self, position_gains=PositionControllerGains(), vehicle_name = ''):
"""
Sets position controller gains for moveByPositionAsync.
This function should only be called if the default position control PID gains need to be modified.
Args:
position_gains (PositionControllerGains):
- Correspond to the X, Y, Z axes.
- Pass PositionControllerGains() to reset gains to default recommended values.
vehicle_name (str, optional): Name of the multirotor to send this command to
"""
self.client.call('setPositionControllerGains', *(position_gains.to_lists()+(vehicle_name,)))
#query vehicle state
def getMultirotorState(self, vehicle_name = ''):
"""
The position inside the returned MultirotorState is in the frame of the vehicle's starting point
Args:
vehicle_name (str, optional): Vehicle to get the state of
Returns:
MultirotorState:
"""
return MultirotorState.from_msgpack(self.client.call('getMultirotorState', vehicle_name))
getMultirotorState.__annotations__ = {'return': MultirotorState}
#query rotor states
def getRotorStates(self, vehicle_name = ''):
"""
Used to obtain the current state of all a multirotor's rotors. The state includes the speeds,
thrusts and torques for all rotors.
Args:
vehicle_name (str, optional): Vehicle to get the rotor state of
Returns:
RotorStates: Containing a timestamp and the speed, thrust and torque of all rotors.
"""
return RotorStates.from_msgpack(self.client.call('getRotorStates', vehicle_name))
getRotorStates.__annotations__ = {'return': RotorStates}
#----------------------------------- Car APIs ---------------------------------------------
class CarClient(VehicleClient, object):
def __init__(self, ip = "", port = 41451, timeout_value = 3600):
super(CarClient, self).__init__(ip, port, timeout_value)
def setCarControls(self, controls, vehicle_name = ''):
"""
Control the car using throttle, steering, brake, etc.
Args:
controls (CarControls): Struct containing control values
vehicle_name (str, optional): Name of vehicle to be controlled
"""
self.client.call('setCarControls', controls, vehicle_name)
def getCarState(self, vehicle_name = ''):
"""
The position inside the returned CarState is in the frame of the vehicle's starting point
Args:
vehicle_name (str, optional): Name of vehicle
Returns:
CarState:
"""
state_raw = self.client.call('getCarState', vehicle_name)
return CarState.from_msgpack(state_raw)
def getCarControls(self, vehicle_name=''):
"""
Args:
vehicle_name (str, optional): Name of vehicle
Returns:
CarControls:
"""
controls_raw = self.client.call('getCarControls', vehicle_name)
return CarControls.from_msgpack(controls_raw) | AirSim/PythonClient/airsim/client.py/0 | {
"file_path": "AirSim/PythonClient/airsim/client.py",
"repo_id": "AirSim",
"token_count": 28696
} | 28 |
import setup_path
import airsim
import time
# connect to the AirSim simulator
client = airsim.CarClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
car_controls = airsim.CarControls()
# go forward
car_controls.throttle = 1
car_controls.steering = 1
client.setCarControls(car_controls)
print("Go Forward")
time.sleep(5) # let car drive a bit
print("reset")
client.reset()
time.sleep(5) # let car drive a bit
client.setCarControls(car_controls)
print("Go Forward")
time.sleep(5) # let car drive a bit
| AirSim/PythonClient/car/reset_test_car.py/0 | {
"file_path": "AirSim/PythonClient/car/reset_test_car.py",
"repo_id": "AirSim",
"token_count": 193
} | 29 |
import numpy as np
import airsim
import time
import cv2
import matplotlib.pyplot as plt
import argparse
import sys, signal
import pandas as pd
import pickle
from event_simulator import *
parser = argparse.ArgumentParser(description="Simulate event data from AirSim")
parser.add_argument("--debug", action="store_true")
parser.add_argument("--save", action="store_true")
parser.add_argument("--height", type=int, default=144)
parser.add_argument("--width", type=int, default=256)
class AirSimEventGen:
def __init__(self, W, H, save=False, debug=False):
self.ev_sim = EventSimulator(W, H)
self.H = H
self.W = W
self.image_request = airsim.ImageRequest(
"0", airsim.ImageType.Scene, False, False
)
self.client = airsim.VehicleClient()
self.client.confirmConnection()
self.init = True
self.start_ts = None
self.rgb_image_shape = [H, W, 3]
self.debug = debug
self.save = save
self.event_file = open("events.pkl", "ab")
self.event_fmt = "%1.7f", "%d", "%d", "%d"
if debug:
self.fig, self.ax = plt.subplots(1, 1)
def visualize_events(self, event_img):
event_img = self.convert_event_img_rgb(event_img)
self.ax.cla()
self.ax.imshow(event_img, cmap="viridis")
plt.draw()
plt.pause(0.01)
def convert_event_img_rgb(self, image):
image = image.reshape(self.H, self.W)
out = np.zeros((self.H, self.W, 3), dtype=np.uint8)
out[:, :, 0] = np.clip(image, 0, 1) * 255
out[:, :, 2] = np.clip(image, -1, 0) * -255
return out
def _stop_event_gen(self, signal, frame):
print("\nCtrl+C received. Stopping event sim...")
self.event_file.close()
sys.exit(0)
if __name__ == "__main__":
args = parser.parse_args()
event_generator = AirSimEventGen(args.width, args.height, save=args.save, debug=args.debug)
i = 0
start_time = 0
t_start = time.time()
signal.signal(signal.SIGINT, event_generator._stop_event_gen)
while True:
image_request = airsim.ImageRequest("0", airsim.ImageType.Scene, False, False)
response = event_generator.client.simGetImages([event_generator.image_request])
while response[0].height == 0 or response[0].width == 0:
response = event_generator.client.simGetImages(
[event_generator.image_request]
)
ts = time.time_ns()
if event_generator.init:
event_generator.start_ts = ts
event_generator.init = False
img = np.reshape(
np.fromstring(response[0].image_data_uint8, dtype=np.uint8),
event_generator.rgb_image_shape,
)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).astype(np.float32)
# Add small number to avoid issues with log(I)
img = cv2.add(img, 0.001)
ts = time.time_ns()
ts_delta = (ts - event_generator.start_ts) * 1e-3
# Event sim keeps track of previous image automatically
event_img, events = event_generator.ev_sim.image_callback(img, ts_delta)
if events is not None and events.shape[0] > 0:
if event_generator.save:
# Using pickle dump in a per-frame fashion to save time, instead of savetxt
# Optimizations possible
pickle.dump(events, event_generator.event_file)
if event_generator.debug:
event_generator.visualize_events(event_img)
| AirSim/PythonClient/eventcamera_sim/test_event_sim.py/0 | {
"file_path": "AirSim/PythonClient/eventcamera_sim/test_event_sim.py",
"repo_id": "AirSim",
"token_count": 1603
} | 30 |
import setup_path
import airsim
import time
# This example shows how to use the External Physics Engine
# It allows you to control the drone through setVehiclePose and obtain collision information.
# It is especially useful for injecting your own flight dynamics model to the AirSim drone.
# Use Blocks environment to see the drone colliding and seeing the collision information
# in the command prompt.
# Add this line to your settings.json before running AirSim:
# "PhysicsEngineName":"ExternalPhysicsEngine"
client = airsim.VehicleClient()
client.confirmConnection()
pose = client.simGetVehiclePose()
pose.orientation = airsim.to_quaternion(0.1, 0.1, 0.1)
client.simSetVehiclePose( pose, False )
for i in range(900):
print(i)
pose = client.simGetVehiclePose()
pose.position = pose.position + airsim.Vector3r(0.03, 0, 0)
pose.orientation = pose.orientation + airsim.to_quaternion(0.1, 0.1, 0.1)
client.simSetVehiclePose( pose, False )
time.sleep(0.003)
collision = client.simGetCollisionInfo()
if collision.has_collided:
print(collision)
client.reset() | AirSim/PythonClient/multirotor/external_physics_engine.py/0 | {
"file_path": "AirSim/PythonClient/multirotor/external_physics_engine.py",
"repo_id": "AirSim",
"token_count": 358
} | 31 |
import setup_path
import airsim
import time
# connect to the AirSim simulator
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
print("fly")
client.moveToPositionAsync(0, 0, -10, 5).join()
print("reset")
client.reset()
client.enableApiControl(True)
client.armDisarm(True)
time.sleep(5)
print("done")
print("fly")
client.moveToPositionAsync(0, 0, -10, 5).join()
| AirSim/PythonClient/multirotor/reset_test_drone.py/0 | {
"file_path": "AirSim/PythonClient/multirotor/reset_test_drone.py",
"repo_id": "AirSim",
"token_count": 152
} | 32 |
import numpy as np
import airsim
import gym
from gym import spaces
class AirSimEnv(gym.Env):
metadata = {"render.modes": ["rgb_array"]}
def __init__(self, image_shape):
self.observation_space = spaces.Box(0, 255, shape=image_shape, dtype=np.uint8)
self.viewer = None
def __del__(self):
raise NotImplementedError()
def _get_obs(self):
raise NotImplementedError()
def _compute_reward(self):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
def step(self, action):
raise NotImplementedError()
def render(self):
return self._get_obs()
| AirSim/PythonClient/reinforcement_learning/airgym/envs/airsim_env.py/0 | {
"file_path": "AirSim/PythonClient/reinforcement_learning/airgym/envs/airsim_env.py",
"repo_id": "AirSim",
"token_count": 275
} | 33 |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="16.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), AirSim.props))\AirSim.props" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="RelWithDebInfo|Win32">
<Configuration>RelWithDebInfo</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="RelWithDebInfo|x64">
<Configuration>RelWithDebInfo</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dsimage.cpp" />
<ClCompile Include="sgmstereo.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="sgmstereo.h" />
<ClInclude Include="dsimage.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A01E543F-EF34-46BB-8F3F-29AB84E7A5D4}</ProjectGuid>
<RootNamespace>Features</RootNamespace>
<SccProjectName>SAK</SccProjectName>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
<SccProvider>SAK</SccProvider>
<ProjectName>sgmstereo</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'">..\..\lib\$(PlatformToolset)\$(Platform)\$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'">..\..\obj\$(PlatformToolset)\$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>VRLib\inc\VRLibCore;VRLib\inc\VRLibCV;VRLib\inc\VRLibImageIO;LibJpeg\inc;LibTiff\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>VRLIB_USES_LIBTIFF;VRLIB_USES_LIBJPEG;NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<TreatWarningAsError>false</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>VRLib\inc\VRLibCore;VRLib\inc\VRLibCV;VRLib\inc\VRLibImageIO;LibJpeg\inc;LibTiff\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>VRLIB_USES_LIBTIFF;VRLIB_USES_LIBJPEG;NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<TreatWarningAsError>false</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>VRLib\inc\VRLibCore;VRLib\inc\VRLibCV;VRLib\inc\VRLibImageIO;LibJpeg\inc;LibTiff\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>VRLIB_USES_LIBTIFF;VRLIB_USES_LIBJPEG;NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<TreatWarningAsError>false</TreatWarningAsError>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<FunctionLevelLinking>true</FunctionLevelLinking>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<WholeProgramOptimization>false</WholeProgramOptimization>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<OpenMPSupport>true</OpenMPSupport>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<PreprocessorDefinitions>NOMINMAX;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<FunctionLevelLinking>true</FunctionLevelLinking>
</ClCompile>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | AirSim/SGM/src/sgmstereo/sgmstereo.vcxproj/0 | {
"file_path": "AirSim/SGM/src/sgmstereo/sgmstereo.vcxproj",
"repo_id": "AirSim",
"token_count": 4314
} | 34 |
#pragma once
#include "AirSimStructs.hpp"
#include "UnityImageCapture.h"
#include "vehicles/car/api/CarApiBase.hpp"
#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#elif defined(__linux__) || defined(__APPLE__)
#define EXPORT __attribute__((visibility("default")))
#endif
/*
* Defines all the functions that can be called into Unity
*/
//Function pointers to hold the addresses of the functions that are defined in Unity
extern bool (*SetPose)(AirSimPose pose, bool ignoreCollision, const char* vehicleName);
extern AirSimPose (*GetPose)(const char* vehicleName);
extern AirSimCollisionInfo (*GetCollisionInfo)(const char* vehicleName);
extern AirSimRCData (*GetRCData)(const char* vehicleName);
extern AirSimImageResponse (*GetSimImages)(AirSimImageRequest request, const char* vehicleName);
extern bool (*SetRotorSpeed)(int rotorIndex, RotorInfo rotorInfo, const char* vehicleName);
extern bool (*SetEnableApi)(bool enableApi, const char* vehicleName);
extern bool (*SetCarApiControls)(msr::airlib::CarApiBase::CarControls controls, const char* vehicleName);
extern AirSimCarState (*GetCarState)(const char* vehicleName);
extern AirSimCameraInfo (*GetCameraInfo)(const char* cameraName, const char* vehicleName);
extern bool (*SetCameraPose)(const char* cameraName, AirSimPose pose, const char* vehicleName);
extern bool (*SetCameraFoV)(const char* cameraName, const float fov_degrees, const char* vehicleName);
extern bool (*SetCameraDistortionParam)(const char* cameraName, const char* paramName, const float value, const char* vehicleName);
extern bool (*GetCameraDistortionParams)(const char* cameraName, const char* vehicleName);
extern bool (*SetSegmentationObjectId)(const char* meshName, int objectId, bool isNameRegex);
extern int (*GetSegmentationObjectId)(const char* meshName);
extern bool (*PrintLogMessage)(const char* message, const char* messageParam, const char* vehicleName, int severity);
extern UnityTransform (*GetTransformFromUnity)(const char* vehicleName);
extern bool (*Reset)();
extern AirSimVector (*GetVelocity)(const char* vehicleName);
extern RayCastHitResult (*GetRayCastHit)(AirSimVector startVec, AirSimVector endVec, const char* vehicleName);
extern bool (*Pause)(float timeScale);
// PInvoke call to initialize the function pointers. This function is called from Unity.
extern "C" EXPORT void InitVehicleManager(
bool (*setPose)(AirSimPose pose, bool ignoreCollision, const char* vehicleName),
AirSimPose (*getPose)(const char* vehicleName),
AirSimCollisionInfo (*getCollisionInfo)(const char* vehicleName),
AirSimRCData (*getDroneRCData)(const char* vehicleName),
AirSimImageResponse (*getSimImages)(AirSimImageRequest request, const char* vehicleName),
bool (*setRotorSpeed)(int rotorIndex, RotorInfo rotorInfo, const char* vehicleName),
bool (*setEnableApi)(bool enableApi, const char* vehicleName),
bool (*setCarApiControls)(msr::airlib::CarApiBase::CarControls controls, const char* vehicleName),
AirSimCarState (*getCarState)(const char* vehicleName),
AirSimCameraInfo (*getCameraInfo)(const char* cameraName, const char* vehicleName),
bool (*setCameraPose)(const char* cameraName, AirSimPose pose, const char* vehicleName),
bool (*setCameraFoV)(const char* cameraName, const float fov_degrees, const char* vehicleName),
bool (*setDistortionParam)(const char* cameraName, const char* paramName, const float value, const char* vehicleName),
bool (*getDistortionParams)(const char* cameraName, const char* vehicleName),
bool (*setSegmentationObjectId)(const char* meshName, int objectId, bool isNameRegex),
int (*getSegmentationObjectId)(const char* meshName),
bool (*printLogMessage)(const char* message, const char* messageParam, const char* vehicleName, int severity),
UnityTransform (*getTransformFromUnity)(const char* vehicleName),
bool (*reset)(),
AirSimVector (*getVelocity)(const char* vehicleName),
RayCastHitResult (*getRayCastHit)(AirSimVector startVec, AirSimVector endVec, const char* vehicleName),
bool (*pause)(float timeScale));
| AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PInvokeWrapper.h/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/PInvokeWrapper.h",
"repo_id": "AirSim",
"token_count": 1205
} | 35 |
#include "UnityToAirSimCalls.h"
void StartServerThread(std::string sim_mode_name, int port_number)
{
key = new SimHUD(sim_mode_name, port_number);
key->BeginPlay();
} | AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityToAirSimCalls.cpp/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnityToAirSimCalls.cpp",
"repo_id": "AirSim",
"token_count": 66
} | 36 |
#pragma once
#include <future>
#include "vehicles/multirotor/MultiRotorPhysicsBody.hpp"
#include "vehicles/multirotor/MultiRotorParams.hpp"
#include "physics//Kinematics.hpp"
#include "MultirotorPawnEvents.h"
#include "../../PawnSimApi.h"
class MultirotorPawnSimApi : public PawnSimApi
{
public:
typedef msr::airlib::real_T real_T;
typedef msr::airlib::Utils Utils;
typedef msr::airlib::MultiRotorPhysicsBody MultiRotor;
typedef msr::airlib::StateReporter StateReporter;
typedef msr::airlib::UpdatableObject UpdatableObject;
typedef msr::airlib::Pose Pose;
typedef MultirotorPawnEvents::RotorActuatorInfo RotorActuatorInfo;
public:
virtual void initialize() override;
MultirotorPawnSimApi(const Params& params);
virtual ~MultirotorPawnSimApi() = default;
virtual void updateRenderedState(float dt) override;
virtual void updateRendering(float dt) override;
virtual void resetImplementation() override;
virtual void update() override;
virtual void reportState(StateReporter& reporter) override;
virtual UpdatableObject* getPhysicsBody() override;
virtual void setPose(const Pose& pose, bool ignore_collision) override;
virtual void setKinematics(const msr::airlib::Kinematics::State& state, bool ignore_collision) override;
msr::airlib::MultirotorApiBase* getVehicleApi() const
{
return vehicle_api_.get();
}
private:
std::unique_ptr<msr::airlib::MultirotorApiBase> vehicle_api_;
std::unique_ptr<msr::airlib::MultiRotorParams> vehicle_params_;
std::unique_ptr<MultiRotor> multirotor_physics_body_;
unsigned int rotor_count_;
std::vector<RotorActuatorInfo> rotor_actuator_info_;
enum class PendingPoseStatus
{
NonePending,
RenderStatePending,
RenderPending
} pending_pose_status_;
//show info on collision response from physics engine
msr::airlib::CollisionResponse collision_response;
//when pose needs to set from non-physics thread, we set it as pending
bool pending_pose_collisions_;
Pose pending_phys_pose_; //force new pose through API
//reset must happen while World is locked so its async task initiated from API thread
bool reset_pending_;
bool did_reset_;
std::packaged_task<void()> reset_task_;
Pose last_phys_pose_; //for trace lines showing vehicle path
std::vector<std::string> vehicle_api_messages_;
};
| AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/MultirotorPawnSimApi.h/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/MultirotorPawnSimApi.h",
"repo_id": "AirSim",
"token_count": 871
} | 37 |
fileFormatVersion: 2
guid: 2b02679e19967e4458223b3799ffe90e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs.meta",
"repo_id": "AirSim",
"token_count": 67
} | 38 |
fileFormatVersion: 2
guid: 3db70f24b93815f43a8926a9f089c7be
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WeatherHUDSlider.prefab.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/WeatherHUDSlider.prefab.meta",
"repo_id": "AirSim",
"token_count": 67
} | 39 |
using UnityEngine;
using System;
using AirSimUnity.CarStructs;
namespace AirSimUnity {
/*
* Adaptor to transform data between AirLib and Unity.
*/
public class DataManager {
public static Vector3 ToUnityVector(AirSimVector src) {
Vector3 vector = new Vector3();
SetToUnity(src, ref vector);
return vector;
}
public static AirSimVector ToAirSimVector(Vector3 src) {
AirSimVector vector = new AirSimVector();
SetToAirSim(src, ref vector);
return vector;
}
public static Quaternion ToUnityQuaternion(AirSimQuaternion src) {
Quaternion quat = new Quaternion();
SetToUnity(src, ref quat);
return quat;
}
public static AirSimQuaternion ToAirSimQuaternion(Quaternion src) {
AirSimQuaternion quat = new AirSimQuaternion();
SetToAirSim(src, ref quat);
return quat;
}
public static void SetToUnity(AirSimVector src, ref Vector3 dst) {
dst.Set(src.y, -src.z, src.x);
}
public static void SetToAirSim(Vector3 src, ref AirSimVector dst) {
dst.Set(src.z, src.x, -src.y);
}
public static void SetToUnity(AirSimQuaternion src, ref Quaternion dst) {
dst.Set(-src.y, src.z, -src.x, src.w);
}
public static void SetToAirSim(Quaternion src, ref AirSimQuaternion dst) {
dst.Set(src.z, -src.x, -src.y, src.w);
}
public static void SetCarControls(CarControls src, ref CarControls dst) {
dst.brake = src.brake;
dst.gear_immediate = src.gear_immediate;
dst.handbrake = src.handbrake;
dst.is_manual_gear = src.is_manual_gear;
dst.manual_gear = src.manual_gear;
dst.steering = src.steering;
dst.throttle = src.throttle;
}
public static long GetCurrentTimeInMilli() {
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
}
} | AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataManager.cs/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/DataManager.cs",
"repo_id": "AirSim",
"token_count": 989
} | 40 |
fileFormatVersion: 2
guid: e03150fb5e358274881026fc928ae40f
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Shaders/CameraEffects.shader.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Shaders/CameraEffects.shader.meta",
"repo_id": "AirSim",
"token_count": 77
} | 41 |
fileFormatVersion: 2
guid: c0b2c818a08ca074698c68805ecc817d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car.meta",
"repo_id": "AirSim",
"token_count": 71
} | 42 |
fileFormatVersion: 2
guid: 7781f6e311e2a474bbd5f81d14b48957
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Models.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Models.meta",
"repo_id": "AirSim",
"token_count": 70
} | 43 |
#! /bin/bash
# get path of current script: https://stackoverflow.com/a/39340259/207661
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
pushd "$SCRIPT_DIR" >/dev/null
set -e
set -x
./clean.sh
rsync -a --exclude 'temp' --delete ../../Plugins/AirSim Plugins/
rsync -a --exclude 'temp' --delete ../../../AirLib Plugins/AirSim/Source/
popd >/dev/null | AirSim/Unreal/Environments/Blocks/update_from_git.sh/0 | {
"file_path": "AirSim/Unreal/Environments/Blocks/update_from_git.sh",
"repo_id": "AirSim",
"token_count": 153
} | 44 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "DetectionComponent.h"
#include <Components/SceneCaptureComponent2D.h>
#include <Components/StaticMeshComponent.h>
#include <DrawDebugHelpers.h>
#include <Engine/Engine.h>
#include <Engine/StaticMesh.h>
#include <Engine/TextureRenderTarget2D.h>
#include <EngineUtils.h>
#include <Math/UnrealMathUtility.h>
#include <Kismet/KismetSystemLibrary.h>
#include <Kismet/KismetMathLibrary.h>
#include <Engine/EngineTypes.h>
UDetectionComponent::UDetectionComponent()
: max_distance_to_camera_(20000.f)
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.bStartWithTickEnabled = false;
}
void UDetectionComponent::BeginPlay()
{
Super::BeginPlay();
scene_capture_component_2D_ = CastChecked<USceneCaptureComponent2D>(GetAttachParent());
object_filter_ = FObjectFilter();
}
void UDetectionComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
const TArray<FDetectionInfo>& UDetectionComponent::getDetections()
{
cached_detections_.Empty();
for (TActorIterator<AActor> actor_itr(GetWorld()); actor_itr; ++actor_itr) {
AActor* actor = *actor_itr;
if (object_filter_.matchesActor(actor)) {
if (FVector::Distance(actor->GetActorLocation(), GetComponentLocation()) <= max_distance_to_camera_) {
FBox2D box_2D_out;
if (texture_target_ && calcBoundingFromViewInfo(actor, box_2D_out)) {
FDetectionInfo detection;
detection.Actor = actor;
detection.Box2D = box_2D_out;
FBox box_3D = actor->GetComponentsBoundingBox(true);
detection.Box3D = FBox(getRelativeLocation(box_3D.Min), getRelativeLocation(box_3D.Max));
detection.RelativeTransform = FTransform(getRelativeRotation(actor->GetActorLocation(), actor->GetActorRotation()),
getRelativeLocation(actor->GetActorLocation()));
cached_detections_.Add(detection);
}
}
}
}
return cached_detections_;
}
bool UDetectionComponent::calcBoundingFromViewInfo(AActor* actor, FBox2D& box_out)
{
FVector origin;
FVector extend;
actor->GetActorBounds(true, origin, extend);
TArray<FVector> points;
TArray<FVector2D> points_2D;
bool is_in_camera_view = false;
// get render target for texture size
FRenderTarget* render_target = texture_target_->GameThread_GetRenderTargetResource();
// initialize viewinfo for projection matrix
FMinimalViewInfo info;
info.Location = scene_capture_component_2D_->GetComponentTransform().GetLocation();
info.Rotation = scene_capture_component_2D_->GetComponentTransform().GetRotation().Rotator();
info.FOV = scene_capture_component_2D_->FOVAngle;
info.ProjectionMode = scene_capture_component_2D_->ProjectionType;
info.AspectRatio = float(texture_target_->SizeX) / float(texture_target_->SizeY);
info.OrthoNearClipPlane = 1;
info.OrthoFarClipPlane = 100000;
info.bConstrainAspectRatio = true;
// calculate 3D corner Points of bounding box
points.Add(origin + FVector(extend.X, extend.Y, extend.Z));
points.Add(origin + FVector(-extend.X, extend.Y, extend.Z));
points.Add(origin + FVector(extend.X, -extend.Y, extend.Z));
points.Add(origin + FVector(-extend.X, -extend.Y, extend.Z));
points.Add(origin + FVector(extend.X, extend.Y, -extend.Z));
points.Add(origin + FVector(-extend.X, extend.Y, -extend.Z));
points.Add(origin + FVector(extend.X, -extend.Y, -extend.Z));
points.Add(origin + FVector(-extend.X, -extend.Y, -extend.Z));
// initialize pixel values
FVector2D min_pixel(texture_target_->SizeX, texture_target_->SizeY);
FVector2D max_pixel(0, 0);
FIntRect screen_rect(0, 0, texture_target_->SizeX, texture_target_->SizeY);
// initialize projection data for sceneview
FSceneViewProjectionData projection_data;
projection_data.ViewOrigin = info.Location;
// do some voodoo rotation that is somehow mandatory and stolen from UGameplayStatics::ProjectWorldToScreen
projection_data.ViewRotationMatrix = FInverseRotationMatrix(info.Rotation) * FMatrix(
FPlane(0, 0, 1, 0),
FPlane(1, 0, 0, 0),
FPlane(0, 1, 0, 0),
FPlane(0, 0, 0, 1));
if (scene_capture_component_2D_->bUseCustomProjectionMatrix) {
projection_data.ProjectionMatrix = scene_capture_component_2D_->CustomProjectionMatrix;
}
else {
projection_data.ProjectionMatrix = info.CalculateProjectionMatrix();
}
projection_data.SetConstrainedViewRectangle(screen_rect);
// Project Points to pixels and get the corner pixels
for (FVector& point : points) {
FVector2D Pixel(0, 0);
FSceneView::ProjectWorldToScreen((point), screen_rect, projection_data.ComputeViewProjectionMatrix(), Pixel);
is_in_camera_view |= (Pixel != screen_rect.Min) && (Pixel != screen_rect.Max) && screen_rect.Contains(FIntPoint(Pixel.X, Pixel.Y));
points_2D.Add(Pixel);
max_pixel.X = FMath::Max(Pixel.X, max_pixel.X);
max_pixel.Y = FMath::Max(Pixel.Y, max_pixel.Y);
min_pixel.X = FMath::Min(Pixel.X, min_pixel.X);
min_pixel.Y = FMath::Min(Pixel.Y, min_pixel.Y);
}
// If actor in camera view - check if it's actually visible or hidden
// Check against 8 extend points
bool is_visible = false;
if (is_in_camera_view) {
FHitResult result;
bool is_world_hit;
for (FVector& point : points) {
is_world_hit = GetWorld()->LineTraceSingleByChannel(result, GetComponentLocation(), point, ECC_WorldStatic);
if (is_world_hit) {
if (result.GetActor() == actor) {
is_visible = true;
break;
}
}
}
// If actor in camera view but didn't hit any point out of 8 extend points,
// check against 10 random points
if (!is_visible) {
for (int i = 0; i < 10; i++) {
FVector point = UKismetMathLibrary::RandomPointInBoundingBox(origin, extend);
is_world_hit = GetWorld()->LineTraceSingleByChannel(result, GetComponentLocation(), point, ECC_WorldStatic);
if (is_world_hit) {
if (result.GetActor() == actor) {
is_visible = true;
break;
}
}
}
}
}
FBox2D box_out_temp = FBox2D(min_pixel, max_pixel);
box_out.Min.X = FMath::Clamp<float>(box_out_temp.Min.X, 0, texture_target_->SizeX);
box_out.Min.Y = FMath::Clamp<float>(box_out_temp.Min.Y, 0, texture_target_->SizeY);
box_out.Max.X = FMath::Clamp<float>(box_out_temp.Max.X, 0, texture_target_->SizeX);
box_out.Max.Y = FMath::Clamp<float>(box_out_temp.Max.Y, 0, texture_target_->SizeY);
return is_in_camera_view && is_visible;
}
FVector UDetectionComponent::getRelativeLocation(FVector in_location)
{
return GetComponentTransform().InverseTransformPosition(in_location);
}
FRotator UDetectionComponent::getRelativeRotation(FVector in_location, FRotator in_rotation)
{
FTransform camera_transform(GetComponentRotation(), GetComponentLocation());
FTransform relative_object_transform = camera_transform.GetRelativeTransform(FTransform(in_rotation, in_location));
return relative_object_transform.Rotator();
}
void UDetectionComponent::addMeshName(const std::string& mesh_name)
{
FString name(mesh_name.c_str());
if (!object_filter_.wildcard_mesh_names_.Contains(name)) {
object_filter_.wildcard_mesh_names_.Add(name);
}
}
void UDetectionComponent::setFilterRadius(const float radius_cm)
{
max_distance_to_camera_ = radius_cm;
}
void UDetectionComponent::clearMeshNames()
{
object_filter_.wildcard_mesh_names_.Empty();
}
| AirSim/Unreal/Plugins/AirSim/Source/DetectionComponent.cpp/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/DetectionComponent.cpp",
"repo_id": "AirSim",
"token_count": 3708
} | 45 |
#include "RecordingThread.h"
#include "Async/TaskGraphInterfaces.h"
#include "HAL/RunnableThread.h"
#include <thread>
#include <mutex>
#include "RenderRequest.h"
#include "PIPCamera.h"
std::unique_ptr<FRecordingThread> FRecordingThread::running_instance_;
std::unique_ptr<FRecordingThread> FRecordingThread::finishing_instance_;
msr::airlib::WorkerThreadSignal FRecordingThread::finishing_signal_;
bool FRecordingThread::first_ = true;
FRecordingThread::FRecordingThread()
: stop_task_counter_(0), recording_file_(nullptr), is_ready_(false)
{
thread_.reset(FRunnableThread::Create(this, TEXT("FRecordingThread"), 0, TPri_BelowNormal)); // Windows default, possible to specify more priority
}
void FRecordingThread::startRecording(const RecordingSetting& settings,
const common_utils::UniqueValueMap<std::string, VehicleSimApiBase*>& vehicle_sim_apis)
{
stopRecording();
//TODO: check FPlatformProcess::SupportsMultithreading()?
assert(!isRecording());
running_instance_.reset(new FRecordingThread());
running_instance_->settings_ = settings;
running_instance_->vehicle_sim_apis_ = vehicle_sim_apis;
for (const auto& vehicle_sim_api : vehicle_sim_apis) {
auto vehicle_name = vehicle_sim_api->getVehicleName();
running_instance_->image_captures_[vehicle_name] = vehicle_sim_api->getImageCapture();
running_instance_->last_poses_[vehicle_name] = msr::airlib::Pose();
}
running_instance_->last_screenshot_on_ = 0;
running_instance_->recording_file_.reset(new RecordingFile());
// Just need any 1 instance, to set the header line of the record file
running_instance_->recording_file_->startRecording(*(vehicle_sim_apis.begin()), settings.folder);
// Set is_ready at the end, setting this before can cause a race when the file isn't open yet
running_instance_->is_ready_ = true;
}
FRecordingThread::~FRecordingThread()
{
if (this == running_instance_.get()) stopRecording();
}
void FRecordingThread::init()
{
first_ = true;
}
bool FRecordingThread::isRecording()
{
return running_instance_ != nullptr;
}
void FRecordingThread::stopRecording()
{
if (running_instance_) {
assert(finishing_instance_ == nullptr);
finishing_instance_ = std::move(running_instance_);
assert(!isRecording());
finishing_instance_->Stop();
}
}
void FRecordingThread::killRecording()
{
if (first_) return;
stopRecording();
bool finished = finishing_signal_.waitForRetry(1, 5);
if (!finished) {
UE_LOG(LogTemp, Log, TEXT("killing thread"));
finishing_instance_->thread_->Kill(false);
}
}
/*********************** methods for instance **************************************/
bool FRecordingThread::Init()
{
if (first_) {
first_ = false;
}
else {
finishing_signal_.wait();
}
if (recording_file_) {
UAirBlueprintLib::LogMessage(TEXT("Initiated recording thread"), TEXT(""), LogDebugLevel::Success);
}
return true;
}
uint32 FRecordingThread::Run()
{
while (stop_task_counter_.GetValue() == 0) {
//make sure all vars are set up
if (is_ready_) {
bool interval_elapsed = msr::airlib::ClockFactory::get()->elapsedSince(last_screenshot_on_) > settings_.record_interval;
if (interval_elapsed) {
last_screenshot_on_ = msr::airlib::ClockFactory::get()->nowNanos();
for (const auto& vehicle_sim_api : vehicle_sim_apis_) {
const auto& vehicle_name = vehicle_sim_api->getVehicleName();
const auto* kinematics = vehicle_sim_api->getGroundTruthKinematics();
bool is_pose_unequal = kinematics && last_poses_[vehicle_name] != kinematics->pose;
if (!settings_.record_on_move || is_pose_unequal) {
last_poses_[vehicle_name] = kinematics->pose;
std::vector<ImageCaptureBase::ImageResponse> responses;
image_captures_[vehicle_name]->getImages(settings_.requests[vehicle_name], responses);
recording_file_->appendRecord(responses, vehicle_sim_api);
}
}
}
}
}
recording_file_.reset();
return 0;
}
void FRecordingThread::Stop()
{
stop_task_counter_.Increment();
}
void FRecordingThread::Exit()
{
assert(this == finishing_instance_.get());
if (recording_file_)
recording_file_.reset();
finishing_signal_.signal();
}
| AirSim/Unreal/Plugins/AirSim/Source/Recording/RecordingThread.cpp/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/Recording/RecordingThread.cpp",
"repo_id": "AirSim",
"token_count": 1843
} | 46 |
#pragma once
#include "CoreMinimal.h"
#include <memory>
#include <vector>
#include "Kismet/KismetSystemLibrary.h"
#include "api/VehicleSimApiBase.hpp"
#include "physics/PhysicsEngineBase.hpp"
#include "physics/World.hpp"
#include "physics/PhysicsWorld.hpp"
#include "common/StateReporterWrapper.hpp"
#include "api/ApiServerBase.hpp"
#include "SimModeBase.h"
#include "SimModeWorldBase.generated.h"
extern CORE_API uint32 GFrameNumber;
UCLASS()
class AIRSIM_API ASimModeWorldBase : public ASimModeBase
{
GENERATED_BODY()
public:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void Tick(float DeltaSeconds) override;
virtual void reset() override;
virtual std::string getDebugReport() override;
virtual bool isPaused() const override;
virtual void pause(bool is_paused) override;
virtual void continueForTime(double seconds) override;
virtual void continueForFrames(uint32_t frames) override;
virtual void setWind(const msr::airlib::Vector3r& wind) const override;
protected:
void startAsyncUpdator();
void stopAsyncUpdator();
virtual void updateDebugReport(msr::airlib::StateReporterWrapper& debug_reporter) override;
//should be called by derived class once all api_provider_ is ready to use
void initializeForPlay();
//used for adding physics bodies on the fly
virtual void registerPhysicsBody(msr::airlib::VehicleSimApiBase* physicsBody) override;
long long getPhysicsLoopPeriod() const;
void setPhysicsLoopPeriod(long long period);
private:
typedef msr::airlib::UpdatableObject UpdatableObject;
typedef msr::airlib::PhysicsEngineBase PhysicsEngineBase;
typedef msr::airlib::ClockFactory ClockFactory;
//create the physics engine as needed from settings
std::unique_ptr<PhysicsEngineBase> createPhysicsEngine();
private:
std::unique_ptr<msr::airlib::PhysicsWorld> physics_world_;
PhysicsEngineBase* physics_engine_;
/*
300Hz seems to be minimum for non-aggressive flights
400Hz is needed for moderately aggressive flights (such as
high yaw rate with simultaneous back move)
500Hz is recommended for more aggressive flights
Lenovo P50 high-end config laptop seems to be topping out at 400Hz.
HP Z840 desktop high-end config seems to be able to go up to 500Hz.
To increase freq with limited CPU power, switch Barometer to constant ref mode.
*/
long long physics_loop_period_ = 3000000LL; //3ms
};
| AirSim/Unreal/Plugins/AirSim/Source/SimMode/SimModeWorldBase.h/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/SimMode/SimModeWorldBase.h",
"repo_id": "AirSim",
"token_count": 814
} | 47 |
#pragma once
#include "CoreMinimal.h"
#include "WheeledVehicleMovementComponent4W.h"
#include "CarPawn.h"
#include "CarPawnApi.h"
#include "PawnEvents.h"
#include "PawnSimApi.h"
#include "vehicles/car/api/CarApiBase.hpp"
#include "physics/Kinematics.hpp"
#include "common/Common.hpp"
#include "common/CommonStructs.hpp"
#include "vehicles/car/CarApiFactory.hpp"
class CarPawnSimApi : public PawnSimApi
{
public:
typedef msr::airlib::Utils Utils;
typedef msr::airlib::StateReporter StateReporter;
typedef msr::airlib::UpdatableObject UpdatableObject;
typedef msr::airlib::Pose Pose;
public:
virtual void initialize() override;
virtual ~CarPawnSimApi() = default;
//VehicleSimApiBase interface
//implements game interface to update pawn
CarPawnSimApi(const Params& params,
const msr::airlib::CarApiBase::CarControls& keyboard_controls);
virtual void update() override;
virtual void reportState(StateReporter& reporter) override;
virtual std::string getRecordFileLine(bool is_header_line) const override;
virtual void updateRenderedState(float dt) override;
virtual void updateRendering(float dt) override;
msr::airlib::CarApiBase* getVehicleApi() const
{
return vehicle_api_.get();
}
virtual msr::airlib::VehicleApiBase* getVehicleApiBase() const override
{
return vehicle_api_.get();
}
protected:
virtual void resetImplementation() override;
private:
void updateCarControls();
private:
std::unique_ptr<msr::airlib::CarApiBase> vehicle_api_;
std::unique_ptr<CarPawnApi> pawn_api_;
std::vector<std::string> vehicle_api_messages_;
//storing reference from pawn
const msr::airlib::CarApiBase::CarControls& keyboard_controls_;
msr::airlib::CarApiBase::CarControls joystick_controls_;
msr::airlib::CarApiBase::CarControls current_controls_;
};
| AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarPawnSimApi.h/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarPawnSimApi.h",
"repo_id": "AirSim",
"token_count": 726
} | 48 |
#pragma once
#include "CoreMinimal.h"
#include "PawnSimApi.h"
#include "vehicles/multirotor/MultiRotorPhysicsBody.hpp"
#include "vehicles/multirotor/MultiRotorParams.hpp"
#include "physics//Kinematics.hpp"
#include "common/Common.hpp"
#include "common/CommonStructs.hpp"
#include "common/common_utils/UniqueValueMap.hpp"
#include "MultirotorPawnEvents.h"
#include <future>
class MultirotorPawnSimApi : public PawnSimApi
{
public:
typedef msr::airlib::real_T real_T;
typedef msr::airlib::Utils Utils;
typedef msr::airlib::MultiRotorPhysicsBody MultiRotor;
typedef msr::airlib::StateReporter StateReporter;
typedef msr::airlib::UpdatableObject UpdatableObject;
typedef msr::airlib::Pose Pose;
typedef MultirotorPawnEvents::RotorActuatorInfo RotorActuatorInfo;
public:
virtual void initialize() override;
virtual ~MultirotorPawnSimApi() = default;
//VehicleSimApiBase interface
//implements game interface to update pawn
MultirotorPawnSimApi(const Params& params);
virtual void updateRenderedState(float dt) override;
virtual void updateRendering(float dt) override;
//PhysicsBody interface
//this just wrapped around MultiRotor physics body
virtual void resetImplementation() override;
virtual void update() override;
virtual void reportState(StateReporter& reporter) override;
virtual UpdatableObject* getPhysicsBody() override;
virtual void setPose(const Pose& pose, bool ignore_collision) override;
virtual void setKinematics(const Kinematics::State& state, bool ignore_collision) override;
virtual void pawnTick(float dt) override;
msr::airlib::MultirotorApiBase* getVehicleApi() const
{
return vehicle_api_.get();
}
virtual msr::airlib::VehicleApiBase* getVehicleApiBase() const override
{
return vehicle_api_.get();
}
private:
std::unique_ptr<msr::airlib::MultirotorApiBase> vehicle_api_;
std::unique_ptr<msr::airlib::MultiRotorParams> vehicle_params_;
std::unique_ptr<MultiRotor> multirotor_physics_body_;
unsigned int rotor_count_;
std::vector<RotorActuatorInfo> rotor_actuator_info_;
//show info on collision response from physics engine
CollisionResponse collision_response;
MultirotorPawnEvents* pawn_events_;
//when pose needs to set from non-physics thread, we set it as pending
bool pending_pose_collisions_;
enum class PendingPoseStatus
{
NonePending,
RenderPending
} pending_pose_status_;
Pose pending_phys_pose_; //force new pose through API
//reset must happen while World is locked so its async task initiated from API thread
bool reset_pending_;
bool did_reset_;
std::packaged_task<void()> reset_task_;
Pose last_phys_pose_; //for trace lines showing vehicle path
std::vector<std::string> vehicle_api_messages_;
RotorStates rotor_states_;
};
| AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/MultirotorPawnSimApi.h/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Multirotor/MultirotorPawnSimApi.h",
"repo_id": "AirSim",
"token_count": 1039
} | 49 |
$airSimInstallPath = "C:\AirSim\"
$airSimBinaryZipUrl = "https://github.com/microsoft/AirSim/releases/download/v1.3.1-windows/Blocks.zip"
$airSimBinaryZipFilename = "Blocks.zip"
$airSimBinaryPath = $airSimInstallPath + "blocks\blocks\binaries\win64\blocks.exe"
$airSimBinaryName = "Blocks"
$webClient = new-object System.Net.WebClient
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Enable service
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
#Install Chocolatey
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
# Bypass confirmation in scripts.
choco feature enable --name="'allowGlobalConfirmation'"
choco install python --version=3.8.2
choco install git
# Run time c++
choco install vcredist-all
choco install directx
#Create new folder & set as default directory
New-Item -ItemType directory -Path $airSimInstallPath
cd $airSimInstallPath
# Get AirSim
$webClient.DownloadFile($airSimBinaryZipUrl, $airSimInstallPath + $airSimBinaryZipFilename)
# Unzip AirSim
Expand-Archive $airSimBinaryZipFilename
# Firewall rule for AirSim
New-NetFirewallRule -DisplayName $airSimBinaryName -Direction Inbound -Program $airSimBinaryPath -Action Allow
| AirSim/azure/azure-env-creation/configure-vm.ps1/0 | {
"file_path": "AirSim/azure/azure-env-creation/configure-vm.ps1",
"repo_id": "AirSim",
"token_count": 474
} | 50 |
# Build AirSim on Windows
## Install Unreal Engine
1. [Download](https://www.unrealengine.com/download) the Epic Games Launcher. While the Unreal Engine is open source and free to download, registration is still required.
2. Run the Epic Games Launcher, open the `Unreal Engine` tab on the left pane.
Click on the `Install` button on the top right, which should show the option to download **Unreal Engine >= 4.27**. Chose the install location to suit your needs, as shown in the images below. If you have multiple versions of Unreal installed then **make sure the version you are using is set to `current`** by clicking down arrow next to the Launch button for the version.
**Note**: If you have UE 4.16 or older projects, please see the [upgrade guide](unreal_upgrade.md) to upgrade your projects.


## Build AirSim
* Install Visual Studio 2022.
**Make sure** to select **Desktop Development with C++** and **Windows 10 SDK 10.0.19041** (should be selected by default) and select the latest .NET Framework SDK under the 'Individual Components' tab while installing VS 2022.
* Start `Developer Command Prompt for VS 2022`.
* Clone the repo: `git clone https://github.com/Microsoft/AirSim.git`, and go the AirSim directory by `cd AirSim`.
**Note:** It's generally not a good idea to install AirSim in C drive. This can cause scripts to fail, and requires running VS in Admin mode. Instead clone in a different drive such as D or E.
* Run `build.cmd` from the command line. This will create ready to use plugin bits in the `Unreal\Plugins` folder that can be dropped into any Unreal project.
## Build Unreal Project
Finally, you will need an Unreal project that hosts the environment for your vehicles. Make sure to close and re-open the Unreal Engine and the Epic Games Launcher before building your first environment if you haven't done so already. After restarting the Epic Games Launcher it will ask you to associate project file extensions with Unreal Engine, click on 'fix now' to fix it. AirSim comes with a built-in "Blocks Environment" which you can use, or you can create your own. Please see [setting up Unreal Environment](unreal_proj.md).
## Setup Remote Control (Multirotor only)
A remote control is required if you want to fly manually. See the [remote control setup](remote_control.md) for more details.
Alternatively, you can use [APIs](apis.md) for programmatic control or use the so-called [Computer Vision mode](image_apis.md) to move around using the keyboard.
## How to Use AirSim
Once AirSim is set up by following above steps, you can,
1. Double click on .sln file to load the Blocks project in `Unreal\Environments\Blocks` (or .sln file in your own [custom](unreal_custenv.md) Unreal project). If you don't see .sln file then you probably haven't completed steps in Build Unreal Project section above.
**Note**: Unreal 4.27 will auto-generate the .sln file targetting Visual Studio 2019. Visual Studio 2022 will be able to load and run this .sln, but if you want full Visual Studio 2022 support, you will need to explicitly enable support by going to 'Edit->Editor Preferences->Source Code' and selecting 'Visual Studio 2022' for the 'Source Code Editor' setting.
2. Select your Unreal project as Start Up project (for example, Blocks project) and make sure Build config is set to "Develop Editor" and x64.
3. After Unreal Editor loads, press Play button.
!!! tip
Go to 'Edit->Editor Preferences', in the 'Search' box type 'CPU' and ensure that the 'Use Less CPU when in Background' is unchecked.
See [Using APIs](apis.md) and [settings.json](settings.md) for various options available.
# AirSim on Unity (Experimental)
[Unity](https://unity3d.com/) is another great game engine platform and we have an **experimental** integration of [AirSim with Unity](Unity.md). Please note that this is work in progress and all features may not work yet.
| AirSim/docs/build_windows.md/0 | {
"file_path": "AirSim/docs/build_windows.md",
"repo_id": "AirSim",
"token_count": 1021
} | 51 |
# Welcome to GazeboDrone
GazeboDrone allows connecting a gazebo drone to the AirSim drone, using the gazebo drone as a flight dynamic model (FDM) and AirSim to generate environmental sensor data. It can be used for **Multicopters**, **Fixed-wings** or any other vehicle.
## Dependencies
### Gazebo
Make sure you have installed gazebo dependencies:
```
sudo apt-get install libgazebo9-dev
```
### AirLib
This project is built with GCC 8, so AirLib needs to be built with GCC 8 too.
Run from your AirSim root folder:
```
./clean.sh
./setup.sh
./build.sh --gcc
```
## AirSim simulator
The AirSim UE plugin needs to be built with clang, so you can't use the one compiled in the previous step. You can use [our binaries](https://github.com/microsoft/AirSim/releases) or you can clone AirSim again in another folder and buid it without the above option, then you can [run Blocks](build_linux.md#how-to-use-airsim) or your own environment.
### AirSim settings
Inside your `settings.json` file you need to add this line:
`"PhysicsEngineName":"ExternalPhysicsEngine"`.
You may want to change the visual model of the AirSim drone, for that you can follow [this tutorial.](https://youtu.be/Bp86WiLUC80)
## Build
Execute this from your AirSim root folder:
```
cd GazeboDrone
mkdir build && cd build
cmake -DCMAKE_C_COMPILER=gcc-8 -DCMAKE_CXX_COMPILER=g++-8 ..
make
```
## Run
First run the AirSim simulator and your Gazebo model and then execute this from your AirSim root folder:
```
cd GazeboDrone/build
./GazeboDrone
```
| AirSim/docs/gazebo_drone.md/0 | {
"file_path": "AirSim/docs/gazebo_drone.md",
"repo_id": "AirSim",
"token_count": 498
} | 52 |
# Remote Control
To fly manually, you need remote control or RC. If you don't have one then you can use [APIs](apis.md) to fly programmatically or use so-called [Computer Vision mode](image_apis.md) to move around using keyboard.
## RC Setup for Default Config
By default AirSim uses [simple_flight](simple_flight.md) as its flight controller which connects to RC via USB port to your computer.
You can either use XBox controller or [FrSky Taranis X9D Plus](https://hobbyking.com/en_us/frsky-2-4ghz-accst-taranis-x9d-plus-and-x8r-combo-digital-telemetry-radio-system-mode-2.html). Note that XBox 360 controller is not precise enough and is not recommended if you wanted more real world experience. See FAQ below if things are not working.
### Other Devices
AirSim can detect large variety of devices however devices other than above *might* need extra configuration. In future we will add ability to set this config through settings.json. For now, if things are not working then you might want to try workarounds such as [x360ce](http://www.x360ce.com/) or change code in [SimJoystick.cpp file](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/SimJoyStick/SimJoyStick.cpp#L50).
### Note on FrSky Taranis X9D Plus
[FrSky Taranis X9D Plus](https://hobbyking.com/en_us/frsky-2-4ghz-accst-taranis-x9d-plus-and-x8r-combo-digital-telemetry-radio-system-mode-2.html) is real UAV remote control with an advantage that it has USB port so it can be directly connected to PC. You can [download AirSim config file](misc/AirSim_FrSkyTaranis.bin) and [follow this tutorial](https://www.youtube.com/watch?v=qe-13Gyb0sw) to import it in your RC. You should then see "sim" model in RC with all channels configured properly.
### Note on Linux
Currently default config on Linux is for using Xbox controller. This means other devices might not work properly. In future we will add ability to configure RC in settings.json but for now you *might* have to change code in [SimJoystick.cpp file](https://github.com/microsoft/AirSim/blob/main/Unreal/Plugins/AirSim/Source/SimJoyStick/SimJoyStick.cpp#L340) to use other devices.
## RC Setup for PX4
AirSim supports PX4 flight controller however it requires different setup. There are many remote control options that you can use with quadrotors. We have successfully used FrSky Taranis X9D Plus, FlySky FS-TH9X and Futaba 14SG with AirSim. Following are the high level steps to configure your RC:
1. If you are going to use Hardware-in-Loop mode, you need transmitter for your specific brand of RC and bind it. You can find this information in RC's user guide.
2. For Hardware-in-Loop mode, you connect transmitter to Pixhawk. Usually you can find online doc or YouTube video tutorial on how to do that.
3. [Calibrate your RC in QGroundControl](https://docs.qgroundcontrol.com/en/SetupView/Radio.html).
See [PX4 RC configuration](https://docs.px4.io/en/getting_started/rc_transmitter_receiver.html) and Please see [this guide](https://docs.px4.io/master/en/getting_started/rc_transmitter_receiver.html#px4-compatible-receivers) for more information.
### Using XBox 360 USB Gamepad
You can also use an xbox controller in SITL mode, it just won't be as precise as a real RC controller.
See [xbox controller](xbox_controller.md) for details on how to set that up.
### Using Playstation 3 controller
A Playstation 3 controller is confirmed to work as an AirSim controller. On Windows, an emulator to make it look like an Xbox 360 controller, is required however. Many different solutions are available online, for example [x360ce Xbox 360 Controller Emulator](https://github.com/x360ce/x360ce).
### DJI Controller
Nils Tijtgat wrote an excellent blog on how to get the [DJI controller working with AirSim](https://timebutt.github.io/static/using-a-phantom-dji-controller-in-airsim/).
## FAQ
#### I'm using default config and AirSim says my RC is not detected on USB.
This typically happens if you have multiple RCs and or XBox/Playstation gamepads etc connected. In Windows, hit Windows+S key and search for "Set up USB Game controllers" (in older versions of Windows try "joystick"). This will show you all game controllers connected to your PC. If you don't see yours than Windows haven't detected it and so you need to first solve that issue. If you do see yours but not at the top of the list (i.e. index 0) than you need to tell AirSim because AirSim by default tries to use RC at index 0. To do this, navigate to your `~/Documents/AirSim` folder, open up `settings.json` and add/modify following setting. Below tells AirSim to use RC at index = 2.
```
{
"SettingsVersion": 1.2,
"SimMode": "Multirotor",
"Vehicles": {
"SimpleFlight": {
"VehicleType": "SimpleFlight",
"RC": {
"RemoteControlID": 2
}
}
}
}
```
#### Vehicle seems unstable when using XBox/PS3 controller
Regular gamepads are not very precise and have lot of random noise. Most of the times you may see significant offsets as well (i.e. output is not zero when sticks are at zero). So this behavior is expected.
#### Where is RC calibration in AirSim?
We haven't implemented it yet. This means your RC firmware will need to have a capability to do calibration for now.
#### My RC is not working with PX4 setup.
First you want to make sure your RC is working in [QGroundControl](https://docs.qgroundcontrol.com/en/SetupView/Radio.html). If it doesn't then it will sure not work in AirSim. The PX4 mode is suitable for folks who have at least intermediate level of experience to deal with various issues related to PX4 and we would generally refer you to get help from PX4 forums.
| AirSim/docs/remote_control.md/0 | {
"file_path": "AirSim/docs/remote_control.md",
"repo_id": "AirSim",
"token_count": 1649
} | 53 |
AirSim provides a feature that constructs ground truth voxel grids of the world directly from Unreal Engine. A voxel grid is a representation of the occupancy of a given world/map, by discretizing into cells of a certain size; and recording a voxel if that particular location is occupied.
The logic for constructing the voxel grid is in WorldSimApi.cpp->createVoxelGrid(). For now, the assumption is that the voxel grid is a cube - and the API call from Python is of the structure:
```
simCreateVoxelGrid(self, position, x, y, z, res, of)
position (Vector3r): Global position around which voxel grid is centered in m
x, y, z (float): Size of each voxel grid dimension in m
res (float): Resolution of voxel grid in m
of (str): Name of output file to save voxel grid as
```
Within `createVoxelGrid()`, the main Unreal Engine function that returns occupancy is [OverlapBlockingTestByChannel](https://docs.unrealengine.com/en-US/API/Runtime/Engine/Engine/UWorld/OverlapBlockingTestByChannel/index.html).
```
OverlapBlockingTestByChannel(position, rotation, ECollisionChannel, FCollisionShape, params);
```
This function is called on the positions of all the 'cells' we wish to discretize the map into, and the returned occupancy result is collected into an array `voxel_grid_`. The indexing of the cell occupancy values follows the convention of the [binvox](https://www.patrickmin.com/binvox/binvox.html) format.
```
for (float i = 0; i < ncells_x; i++) {
for (float k = 0; k < ncells_z; k++) {
for (float j = 0; j < ncells_y; j++) {
int idx = i + ncells_x * (k + ncells_z * j);
FVector position = FVector((i - ncells_x /2) * scale_cm, (j - ncells_y /2) * scale_cm, (k - ncells_z /2) * scale_cm) + position_in_UE_frame;
voxel_grid_[idx] = simmode_->GetWorld()->OverlapBlockingTestByChannel(position, FQuat::Identity, ECollisionChannel::ECC_Pawn, FCollisionShape::MakeBox(FVector(scale_cm /2)), params);
}
}
}
```
The occupancy of the map is calculated iteratively over all discretized cells, which can make it an intensive operation depending on the resolution of the cells, and the total size of the area being measured. If the user's map of interest does not change much, it is possible to run the voxel grid operation once on this map, and save the voxel grid and reuse it. For performance, or with dynamic environments, we recommend running the voxel grid generation for a small area around the robot; and subsequently use it for local planning purposes.
The voxel grids are stored in the binvox format which can then be converted by the user into an octomap .bt or any other relevant, desired format. Subsequently, these voxel grids/octomaps can be used within mapping/planning. One nifty little utility to visualize a created binvox files is [viewvox](https://www.patrickmin.com/viewvox/). Similarly, `binvox2bt` can convert the binvox to an octomap file.
##### Example voxel grid in Blocks:

##### Blocks voxel grid converted to Octomap format (visualized in rviz):

As an example, a voxel grid can be constructed as follows, once the Blocks environment is up and running:
```
import airsim
c = airsim.VehicleClient()
center = airsim.Vector3r(0, 0, 0)
output_path = os.path.join(os.getcwd(), "map.binvox")
c.simCreateVoxelGrid(center, 100, 100, 100, 0.5, output_path)
```
And visualized through `viewvox map.binvox`.
| AirSim/docs/voxel_grid.md/0 | {
"file_path": "AirSim/docs/voxel_grid.md",
"repo_id": "AirSim",
"token_count": 1087
} | 54 |
<launch>
<arg name="host" default="localhost" />
<node name="airsim_node" pkg="airsim_ros_pkgs" type="airsim_node" output="screen">
<!-- <node pkg="nodelet" type="nodelet" name="airsim_nodelet_manager" args="manager" output="screen" /> -->
<!-- <node pkg="nodelet" type="nodelet" name="airsim_nodelet" args="standalone airsim_ros_pkgs/airsim_ros_nodelet airsim_nodelet_manager" output="screen"> -->
<param name="is_vulkan" type="bool" value="false" />
<!-- ROS timer rates -->
<param name="update_airsim_img_response_every_n_sec" type="double" value="0.05" />
<param name="update_airsim_control_every_n_sec" type="double" value="0.01" />
<param name="update_lidar_every_n_sec" type="double" value="0.01" />
<param name="world_frame_id" type="string" value="world_enu"/>
<param name="coordinate_system_enu" type="boolean" value="1"/>
<param name="host_ip" type="string" value="$(arg host)" />
</node>
<!-- Joystick control -->
<node name="joy_node" pkg="joy" type="joy_node" />
<node name="car_joy" pkg="airsim_ros_pkgs" type="car_joy"/>
<!-- Static transforms -->
<include file="$(find airsim_ros_pkgs)/launch/static_transforms.launch"/>
</launch> | AirSim/ros/src/airsim_ros_pkgs/launch/airsim_car_with_joy_control.launch/0 | {
"file_path": "AirSim/ros/src/airsim_ros_pkgs/launch/airsim_car_with_joy_control.launch",
"repo_id": "AirSim",
"token_count": 444
} | 55 |
geometry_msgs/Twist twist
string[] vehicle_names | AirSim/ros/src/airsim_ros_pkgs/msg/VelCmdGroup.msg/0 | {
"file_path": "AirSim/ros/src/airsim_ros_pkgs/msg/VelCmdGroup.msg",
"repo_id": "AirSim",
"token_count": 15
} | 56 |
#include <rclcpp/rclcpp.hpp>
#include "airsim_ros_wrapper.h"
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
rclcpp::NodeOptions node_options;
node_options.automatically_declare_parameters_from_overrides(true);
std::shared_ptr<rclcpp::Node> nh = rclcpp::Node::make_shared("airsim_node", node_options);
std::shared_ptr<rclcpp::Node> nh_img = nh->create_sub_node("img");
std::shared_ptr<rclcpp::Node> nh_lidar = nh->create_sub_node("lidar");
std::string host_ip;
nh->get_parameter("host_ip", host_ip);
AirsimROSWrapper airsim_ros_wrapper(nh, nh_img, nh_lidar, host_ip);
if (airsim_ros_wrapper.is_used_img_timer_cb_queue_) {
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(nh_img);
while (rclcpp::ok()) {
executor.spin();
}
}
if (airsim_ros_wrapper.is_used_lidar_timer_cb_queue_) {
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(nh_lidar);
while (rclcpp::ok()) {
executor.spin();
}
}
rclcpp::spin(nh);
return 0;
} | AirSim/ros2/src/airsim_ros_pkgs/src/airsim_node.cpp/0 | {
"file_path": "AirSim/ros2/src/airsim_ros_pkgs/src/airsim_node.cpp",
"repo_id": "AirSim",
"token_count": 536
} | 57 |
// Common/CRC.cs
namespace SevenZip
{
public class CRC
{
public static readonly uint[] Table;
static CRC()
{
Table = new uint[256];
const uint kPoly = 0xEDB88320;
for (uint i = 0; i < 256; i++)
{
uint r = i;
for (int j = 0; j < 8; j++)
if ((r & 1) != 0)
r = (r >> 1) ^ kPoly;
else
r >>= 1;
Table[i] = r;
}
}
uint _value = 0xFFFFFFFF;
public void Init() { _value = 0xFFFFFFFF; }
public void UpdateByte(byte b)
{
_value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8);
}
public void Update(byte[] data, uint offset, uint size)
{
for (uint i = 0; i < size; i++)
_value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8);
}
public uint GetDigest() { return _value ^ 0xFFFFFFFF; }
static uint CalculateDigest(byte[] data, uint offset, uint size)
{
CRC crc = new CRC();
// crc.Init();
crc.Update(data, offset, size);
return crc.GetDigest();
}
static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
{
return (CalculateDigest(data, offset, size) == digest);
}
}
}
| AssetStudio/AssetStudio/7zip/Common/CRC.cs/0 | {
"file_path": "AssetStudio/AssetStudio/7zip/Common/CRC.cs",
"repo_id": "AssetStudio",
"token_count": 494
} | 58 |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using static AssetStudio.ImportHelper;
namespace AssetStudio
{
public class AssetsManager
{
public string SpecifyUnityVersion;
public List<SerializedFile> assetsFileList = new List<SerializedFile>();
internal Dictionary<string, int> assetsFileIndexCache = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
internal Dictionary<string, BinaryReader> resourceFileReaders = new Dictionary<string, BinaryReader>(StringComparer.OrdinalIgnoreCase);
private List<string> importFiles = new List<string>();
private HashSet<string> importFilesHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private HashSet<string> noexistFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private HashSet<string> assetsFileListHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
public void LoadFiles(params string[] files)
{
var path = Path.GetDirectoryName(Path.GetFullPath(files[0]));
MergeSplitAssets(path);
var toReadFile = ProcessingSplitFiles(files.ToList());
Load(toReadFile);
}
public void LoadFolder(string path)
{
MergeSplitAssets(path, true);
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();
var toReadFile = ProcessingSplitFiles(files);
Load(toReadFile);
}
private void Load(string[] files)
{
foreach (var file in files)
{
importFiles.Add(file);
importFilesHash.Add(Path.GetFileName(file));
}
Progress.Reset();
//use a for loop because list size can change
for (var i = 0; i < importFiles.Count; i++)
{
LoadFile(importFiles[i]);
Progress.Report(i + 1, importFiles.Count);
}
importFiles.Clear();
importFilesHash.Clear();
noexistFiles.Clear();
assetsFileListHash.Clear();
ReadAssets();
ProcessAssets();
}
private void LoadFile(string fullName)
{
var reader = new FileReader(fullName);
LoadFile(reader);
}
private void LoadFile(FileReader reader)
{
switch (reader.FileType)
{
case FileType.AssetsFile:
LoadAssetsFile(reader);
break;
case FileType.BundleFile:
LoadBundleFile(reader);
break;
case FileType.WebFile:
LoadWebFile(reader);
break;
case FileType.GZipFile:
LoadFile(DecompressGZip(reader));
break;
case FileType.BrotliFile:
LoadFile(DecompressBrotli(reader));
break;
case FileType.ZipFile:
LoadZipFile(reader);
break;
}
}
private void LoadAssetsFile(FileReader reader)
{
if (!assetsFileListHash.Contains(reader.FileName))
{
Logger.Info($"Loading {reader.FullPath}");
try
{
var assetsFile = new SerializedFile(reader, this);
CheckStrippedVersion(assetsFile);
assetsFileList.Add(assetsFile);
assetsFileListHash.Add(assetsFile.fileName);
foreach (var sharedFile in assetsFile.m_Externals)
{
var sharedFileName = sharedFile.fileName;
if (!importFilesHash.Contains(sharedFileName))
{
var sharedFilePath = Path.Combine(Path.GetDirectoryName(reader.FullPath), sharedFileName);
if (!noexistFiles.Contains(sharedFilePath))
{
if (!File.Exists(sharedFilePath))
{
var findFiles = Directory.GetFiles(Path.GetDirectoryName(reader.FullPath), sharedFileName, SearchOption.AllDirectories);
if (findFiles.Length > 0)
{
sharedFilePath = findFiles[0];
}
}
if (File.Exists(sharedFilePath))
{
importFiles.Add(sharedFilePath);
importFilesHash.Add(sharedFileName);
}
else
{
noexistFiles.Add(sharedFilePath);
}
}
}
}
}
catch (Exception e)
{
Logger.Error($"Error while reading assets file {reader.FullPath}", e);
reader.Dispose();
}
}
else
{
Logger.Info($"Skipping {reader.FullPath}");
reader.Dispose();
}
}
private void LoadAssetsFromMemory(FileReader reader, string originalPath, string unityVersion = null)
{
if (!assetsFileListHash.Contains(reader.FileName))
{
try
{
var assetsFile = new SerializedFile(reader, this);
assetsFile.originalPath = originalPath;
if (!string.IsNullOrEmpty(unityVersion) && assetsFile.header.m_Version < SerializedFileFormatVersion.Unknown_7)
{
assetsFile.SetVersion(unityVersion);
}
CheckStrippedVersion(assetsFile);
assetsFileList.Add(assetsFile);
assetsFileListHash.Add(assetsFile.fileName);
}
catch (Exception e)
{
Logger.Error($"Error while reading assets file {reader.FullPath} from {Path.GetFileName(originalPath)}", e);
resourceFileReaders.Add(reader.FileName, reader);
}
}
else
Logger.Info($"Skipping {originalPath} ({reader.FileName})");
}
private void LoadBundleFile(FileReader reader, string originalPath = null)
{
Logger.Info("Loading " + reader.FullPath);
try
{
var bundleFile = new BundleFile(reader);
foreach (var file in bundleFile.fileList)
{
var dummyPath = Path.Combine(Path.GetDirectoryName(reader.FullPath), file.fileName);
var subReader = new FileReader(dummyPath, file.stream);
if (subReader.FileType == FileType.AssetsFile)
{
LoadAssetsFromMemory(subReader, originalPath ?? reader.FullPath, bundleFile.m_Header.unityRevision);
}
else
{
resourceFileReaders[file.fileName] = subReader; //TODO
}
}
}
catch (Exception e)
{
var str = $"Error while reading bundle file {reader.FullPath}";
if (originalPath != null)
{
str += $" from {Path.GetFileName(originalPath)}";
}
Logger.Error(str, e);
}
finally
{
reader.Dispose();
}
}
private void LoadWebFile(FileReader reader)
{
Logger.Info("Loading " + reader.FullPath);
try
{
var webFile = new WebFile(reader);
foreach (var file in webFile.fileList)
{
var dummyPath = Path.Combine(Path.GetDirectoryName(reader.FullPath), file.fileName);
var subReader = new FileReader(dummyPath, file.stream);
switch (subReader.FileType)
{
case FileType.AssetsFile:
LoadAssetsFromMemory(subReader, reader.FullPath);
break;
case FileType.BundleFile:
LoadBundleFile(subReader, reader.FullPath);
break;
case FileType.WebFile:
LoadWebFile(subReader);
break;
case FileType.ResourceFile:
resourceFileReaders[file.fileName] = subReader; //TODO
break;
}
}
}
catch (Exception e)
{
Logger.Error($"Error while reading web file {reader.FullPath}", e);
}
finally
{
reader.Dispose();
}
}
private void LoadZipFile(FileReader reader)
{
Logger.Info("Loading " + reader.FileName);
try
{
using (ZipArchive archive = new ZipArchive(reader.BaseStream, ZipArchiveMode.Read))
{
List<string> splitFiles = new List<string>();
// register all files before parsing the assets so that the external references can be found
// and find split files
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.Name.Contains(".split"))
{
string baseName = Path.GetFileNameWithoutExtension(entry.Name);
string basePath = Path.Combine(Path.GetDirectoryName(entry.FullName), baseName);
if (!splitFiles.Contains(basePath))
{
splitFiles.Add(basePath);
importFilesHash.Add(baseName);
}
}
else
{
importFilesHash.Add(entry.Name);
}
}
// merge split files and load the result
foreach (string basePath in splitFiles)
{
try
{
Stream splitStream = new MemoryStream();
int i = 0;
while (true)
{
string path = $"{basePath}.split{i++}";
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry == null)
break;
using (Stream entryStream = entry.Open())
{
entryStream.CopyTo(splitStream);
}
}
splitStream.Seek(0, SeekOrigin.Begin);
FileReader entryReader = new FileReader(basePath, splitStream);
LoadFile(entryReader);
}
catch (Exception e)
{
Logger.Error($"Error while reading zip split file {basePath}", e);
}
}
// load all entries
foreach (ZipArchiveEntry entry in archive.Entries)
{
try
{
string dummyPath = Path.Combine(Path.GetDirectoryName(reader.FullPath), reader.FileName, entry.FullName);
// create a new stream
// - to store the deflated stream in
// - to keep the data for later extraction
Stream streamReader = new MemoryStream();
using (Stream entryStream = entry.Open())
{
entryStream.CopyTo(streamReader);
}
streamReader.Position = 0;
FileReader entryReader = new FileReader(dummyPath, streamReader);
LoadFile(entryReader);
if (entryReader.FileType == FileType.ResourceFile)
{
entryReader.Position = 0;
if (!resourceFileReaders.ContainsKey(entry.Name))
{
resourceFileReaders.Add(entry.Name, entryReader);
}
}
}
catch (Exception e)
{
Logger.Error($"Error while reading zip entry {entry.FullName}", e);
}
}
}
}
catch (Exception e)
{
Logger.Error($"Error while reading zip file {reader.FileName}", e);
}
finally
{
reader.Dispose();
}
}
public void CheckStrippedVersion(SerializedFile assetsFile)
{
if (assetsFile.IsVersionStripped && string.IsNullOrEmpty(SpecifyUnityVersion))
{
throw new Exception("The Unity version has been stripped, please set the version in the options");
}
if (!string.IsNullOrEmpty(SpecifyUnityVersion))
{
assetsFile.SetVersion(SpecifyUnityVersion);
}
}
public void Clear()
{
foreach (var assetsFile in assetsFileList)
{
assetsFile.Objects.Clear();
assetsFile.reader.Close();
}
assetsFileList.Clear();
foreach (var resourceFileReader in resourceFileReaders)
{
resourceFileReader.Value.Close();
}
resourceFileReaders.Clear();
assetsFileIndexCache.Clear();
}
private void ReadAssets()
{
Logger.Info("Read assets...");
var progressCount = assetsFileList.Sum(x => x.m_Objects.Count);
int i = 0;
Progress.Reset();
foreach (var assetsFile in assetsFileList)
{
foreach (var objectInfo in assetsFile.m_Objects)
{
var objectReader = new ObjectReader(assetsFile.reader, assetsFile, objectInfo);
try
{
Object obj;
switch (objectReader.type)
{
case ClassIDType.Animation:
obj = new Animation(objectReader);
break;
case ClassIDType.AnimationClip:
obj = new AnimationClip(objectReader);
break;
case ClassIDType.Animator:
obj = new Animator(objectReader);
break;
case ClassIDType.AnimatorController:
obj = new AnimatorController(objectReader);
break;
case ClassIDType.AnimatorOverrideController:
obj = new AnimatorOverrideController(objectReader);
break;
case ClassIDType.AssetBundle:
obj = new AssetBundle(objectReader);
break;
case ClassIDType.AudioClip:
obj = new AudioClip(objectReader);
break;
case ClassIDType.Avatar:
obj = new Avatar(objectReader);
break;
case ClassIDType.Font:
obj = new Font(objectReader);
break;
case ClassIDType.GameObject:
obj = new GameObject(objectReader);
break;
case ClassIDType.Material:
obj = new Material(objectReader);
break;
case ClassIDType.Mesh:
obj = new Mesh(objectReader);
break;
case ClassIDType.MeshFilter:
obj = new MeshFilter(objectReader);
break;
case ClassIDType.MeshRenderer:
obj = new MeshRenderer(objectReader);
break;
case ClassIDType.MonoBehaviour:
obj = new MonoBehaviour(objectReader);
break;
case ClassIDType.MonoScript:
obj = new MonoScript(objectReader);
break;
case ClassIDType.MovieTexture:
obj = new MovieTexture(objectReader);
break;
case ClassIDType.PlayerSettings:
obj = new PlayerSettings(objectReader);
break;
case ClassIDType.RectTransform:
obj = new RectTransform(objectReader);
break;
case ClassIDType.Shader:
obj = new Shader(objectReader);
break;
case ClassIDType.SkinnedMeshRenderer:
obj = new SkinnedMeshRenderer(objectReader);
break;
case ClassIDType.Sprite:
obj = new Sprite(objectReader);
break;
case ClassIDType.SpriteAtlas:
obj = new SpriteAtlas(objectReader);
break;
case ClassIDType.TextAsset:
obj = new TextAsset(objectReader);
break;
case ClassIDType.Texture2D:
obj = new Texture2D(objectReader);
break;
case ClassIDType.Transform:
obj = new Transform(objectReader);
break;
case ClassIDType.VideoClip:
obj = new VideoClip(objectReader);
break;
case ClassIDType.ResourceManager:
obj = new ResourceManager(objectReader);
break;
default:
obj = new Object(objectReader);
break;
}
assetsFile.AddObject(obj);
}
catch (Exception e)
{
var sb = new StringBuilder();
sb.AppendLine("Unable to load object")
.AppendLine($"Assets {assetsFile.fileName}")
.AppendLine($"Path {assetsFile.originalPath}")
.AppendLine($"Type {objectReader.type}")
.AppendLine($"PathID {objectInfo.m_PathID}")
.Append(e);
Logger.Error(sb.ToString());
}
Progress.Report(++i, progressCount);
}
}
}
private void ProcessAssets()
{
Logger.Info("Process Assets...");
foreach (var assetsFile in assetsFileList)
{
foreach (var obj in assetsFile.Objects)
{
if (obj is GameObject m_GameObject)
{
foreach (var pptr in m_GameObject.m_Components)
{
if (pptr.TryGet(out var m_Component))
{
switch (m_Component)
{
case Transform m_Transform:
m_GameObject.m_Transform = m_Transform;
break;
case MeshRenderer m_MeshRenderer:
m_GameObject.m_MeshRenderer = m_MeshRenderer;
break;
case MeshFilter m_MeshFilter:
m_GameObject.m_MeshFilter = m_MeshFilter;
break;
case SkinnedMeshRenderer m_SkinnedMeshRenderer:
m_GameObject.m_SkinnedMeshRenderer = m_SkinnedMeshRenderer;
break;
case Animator m_Animator:
m_GameObject.m_Animator = m_Animator;
break;
case Animation m_Animation:
m_GameObject.m_Animation = m_Animation;
break;
}
}
}
}
else if (obj is SpriteAtlas m_SpriteAtlas)
{
foreach (var m_PackedSprite in m_SpriteAtlas.m_PackedSprites)
{
if (m_PackedSprite.TryGet(out var m_Sprite))
{
if (m_Sprite.m_SpriteAtlas.IsNull)
{
m_Sprite.m_SpriteAtlas.Set(m_SpriteAtlas);
}
else
{
m_Sprite.m_SpriteAtlas.TryGet(out var m_SpriteAtlaOld);
if (m_SpriteAtlaOld.m_IsVariant)
{
m_Sprite.m_SpriteAtlas.Set(m_SpriteAtlas);
}
}
}
}
}
}
}
}
}
}
| AssetStudio/AssetStudio/AssetsManager.cs/0 | {
"file_path": "AssetStudio/AssetStudio/AssetsManager.cs",
"repo_id": "AssetStudio",
"token_count": 15082
} | 59 |
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
namespace Org.Brotli.Dec
{
/// <summary>Enumeration of all possible word transformations.</summary>
/// <remarks>
/// Enumeration of all possible word transformations.
/// <p>There are two simple types of transforms: omit X first/last symbols, two character-case
/// transforms and the identity transform.
/// </remarks>
internal sealed class WordTransformType
{
internal const int Identity = 0;
internal const int OmitLast1 = 1;
internal const int OmitLast2 = 2;
internal const int OmitLast3 = 3;
internal const int OmitLast4 = 4;
internal const int OmitLast5 = 5;
internal const int OmitLast6 = 6;
internal const int OmitLast7 = 7;
internal const int OmitLast8 = 8;
internal const int OmitLast9 = 9;
internal const int UppercaseFirst = 10;
internal const int UppercaseAll = 11;
internal const int OmitFirst1 = 12;
internal const int OmitFirst2 = 13;
internal const int OmitFirst3 = 14;
internal const int OmitFirst4 = 15;
internal const int OmitFirst5 = 16;
internal const int OmitFirst6 = 17;
internal const int OmitFirst7 = 18;
internal const int OmitFirst8 = 19;
internal const int OmitFirst9 = 20;
internal static int GetOmitFirst(int type)
{
return type >= OmitFirst1 ? (type - OmitFirst1 + 1) : 0;
}
internal static int GetOmitLast(int type)
{
return type <= OmitLast9 ? (type - OmitLast1 + 1) : 0;
}
}
}
| AssetStudio/AssetStudio/Brotli/WordTransformType.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Brotli/WordTransformType.cs",
"repo_id": "AssetStudio",
"token_count": 512
} | 60 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssetStudio
{
public abstract class EditorExtension : Object
{
protected EditorExtension(ObjectReader reader) : base(reader)
{
if (platform == BuildTarget.NoTarget)
{
var m_PrefabParentObject = new PPtr<EditorExtension>(reader);
var m_PrefabInternal = new PPtr<Object>(reader); //PPtr<Prefab>
}
}
}
}
| AssetStudio/AssetStudio/Classes/EditorExtension.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Classes/EditorExtension.cs",
"repo_id": "AssetStudio",
"token_count": 221
} | 61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.