[lua source code] object system

版本號:Lua 5.3

Lua Type

lua 的類型定義在lobject.h這個文件里,主要的類型如下:

  • none
  • nil
  • light user data
  • boolean
  • number
    • integer
    • float
  • function type
    • light C function
    • closure (gc object)
      • lua closure
      • C closure
  • string (gc object)
  • user data (gcobject)
  • table (gc object)
  • thread ( gc object)

Lua Value

lua使用一個union來統(tǒng)一表示上述類型:

union Value {
  GCObject *gc;    /* collectable objects */
  void *p;         /* light userdata */      
  int b;           /* booleans */            
  lua_CFunction f; /* light C functions */ 
  lua_Integer i;   /* integer numbers */    
  lua_Number n;    /* float numbers */   
};

同時,添加一個額外的byte來標記具體的類型:

#define TValuefields    Value value_; int tt_  //<值,類型標記>
struct lua_TValue {
  TValuefields; // Value value_; int tt_;
};
typedef struct lua_TValue TValue;

如果展開上述代碼,則為:

typedef struct lua_TValue{
   Value value_;
   int tt_;      
}TValue;

其中,tt_是一個8 bits 的類型標記字段,被分成3個部分:

  • 0-3位,表示大類型
  • 4-5位,表示子類型
  • 6位,表示是否可以垃圾回收

綜合使用上面三點,就可以完整標記所有的lua類型,每種類型標記的值如下(這些定義在lua.h和lobject.h里,此處把它們合在一起,更直觀):

#define LUA_TNONE            (-1)
#define LUA_TNIL              0
#define LUA_TBOOLEAN          1
#define LUA_TLIGHTUSERDATA  2
#define LUA_TNUMBER        3
  #define LUA_TNUMFLT        (LUA_TNUMBER | (0 << 4))  /* float numbers */
  #define LUA_TNUMINT        (LUA_TNUMBER | (1 << 4))  /* integer numbers */
#define LUA_TSTRING        4
  #define LUA_TSHRSTR       (LUA_TSTRING | (0 << 4))  /* short strings */
  #define LUA_TLNGSTR       (LUA_TSTRING | (1 << 4))  /* long strings */
#define LUA_TTABLE          5
#define LUA_TFUNCTION        6
  #define LUA_TLCL          (LUA_TFUNCTION | (0 << 4))  /* Lua closure */
  #define LUA_TLCF          (LUA_TFUNCTION | (1 << 4))  /* light C function */
  #define LUA_TCCL          (LUA_TFUNCTION | (2 << 4))  /* C closure */
#define LUA_TUSERDATA        7
#define LUA_TTHREAD        8
#define LUA_NUMTAGS        9
#define LUA_TPROTO          LUA_NUMTAGS
#define LUA_TDEADKEY          (LUA_NUMTAGS+1)
#define LUA_TOTALTAGS        (LUA_TPROTO + 2)
#define BIT_ISCOLLECTABLE    (1 << 6)

Value是一個聯(lián)合體,第一個字段是GCObject,包括:closure(lua closure+C closure), string, userdata, table, thread,其他幾個則是非垃圾回收類型:light user data, boolean, light C function, number(integer+float).非垃圾回收字段被直接展開在聯(lián)合體里,GCObject則是可垃圾回收類型的公共類:

#define CommonHeader GCObject* next;lua_byte tt; lua_byte marked
typedef struct GCObject{
  CommonHeader; // GCObject* next;lua_byte tt; lua_byte marked;
};

GC Object

展開上述GCObject代碼,則為:

typedef struct GCObject{
  GCObject* next;
  lua_byte tt; 
  lua_byte marked;
};

可見,GCObject是以鏈表的形式串在一起。其中,tt字段是類型標記字段,既然TValue里已經(jīng)標記了類型,此處為什么重復(fù)標記呢?我的理解是因為在使用的過程中,GCObject未必是作為一個TValue傳入,如果只有GCObject指針的時候,重復(fù)的tt即可使用上。而marked則是在垃圾回收過程中用以標記對象存活狀態(tài)的。

所有的GC類型,都有公共的CommonHeader頭部,這是在C這種語言里的一種“繼承”用法。

TString

typedef struct TString{
  CommonHeader; // GCObject* next;lua_byte tt; lua_byte marked;
  lua_byte extra;
  unsigned int hash;
  size_t len;
  struct TString* hnext;
}TString;

由于lua的string有兩個子類型:short stringlong string。其中,extra字段用來標記是否是long string,hash字段則是用存儲在全局字符串池里的哈希值;len表示長度,lua的字符串并不以\0結(jié)尾,所以需要存儲長度信息。hnext是用來把全局TString串起來,整個鏈表就是字符串池。而真正的字符串的內(nèi)容,直接存儲在結(jié)構(gòu)體后面的內(nèi)存里,為了保證內(nèi)存的對齊,對上述TString和基本類型合并做一個字節(jié)對齊:

typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign;
typedef union UTString{
  L_Umaxalign dummy;
  TString tsv; 
}UTString;

從而,真正的字符串內(nèi)容的內(nèi)存地址獲取如下:

/*
** Get the actual string (array of bytes) from a 'TString'.
** (Access to 'extra' ensures that value is really a 'TString'.)
*/
#define getaddrstr(ts)  (cast(char *, (ts)) + sizeof(UTString))
#define getstr(ts)  \
  check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))

/* get the actual string (array of bytes) from a Lua value */
#define svalue(o)       getstr(tsvalue(o))

UData

typedef struct Udata{
  CommonHeader;
  lua_byte ttuv_;// user value's tag
  struct Table* metatable;
  size_t len;
  union Value user_; //user value
}Udata;

User Data和String的布局基本一樣。首先是共同的CommonHeader,然后是一個類型標記字段: ttuv_,此處標記的是該UserData里實際存儲的值(user_字段)的類型;其次最明顯的區(qū)別是有一個Table類型的metatable,所有對User Data的操作都會去這個metatable里查找是否有對應(yīng)的屬性或者方法定義,這也是lua的所有魔法所在。len字段則定義了實際的數(shù)據(jù)長度,同時還有一個附加的用戶定義值字段:user_

User Data和String一樣把額外的數(shù)據(jù)塊存在結(jié)構(gòu)體后面的內(nèi)存里,同樣地對起始地址做了對齊:

typedef union UUdata{
  L_Umaxalign dummy;
  Udata uv;
}UUdata;

從而,User Data的額外數(shù)據(jù)塊的地址如下,注意:

/*
**  Get the address of memory block inside 'Udata'.
** (Access to 'ttuv_' ensures that value is really a 'Udata'.)
*/
#define getudatamem(u)  \
  check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))

另外,對于User Data來說,metatable是每個實例一個,user_ttuv_兩個字段則是值部分。所以設(shè)置和獲取UserData的接口如下:

#define setuservalue(L,u,o) \
    { const TValue *io=(o); Udata *iu = (u); \
      iu->user_ = io->value_; iu->ttuv_ = io->tt_; \
      checkliveness(G(L),io); }

#define getuservalue(L,u,o) \
    { TValue *io=(o); const Udata *iu = (u); \
      io->value_ = iu->user_; io->tt_ = iu->ttuv_; \
      checkliveness(G(L),io); }

總之,UserData=tag+value+metatable=data+metatable;

Table

typedef struct Table {
  CommonHeader;
  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */
  lu_byte lsizenode;  /* log2 of size of 'node' array */
  unsigned int sizearray;  /* size of 'array' array */
  TValue *array;  /* array part */
  Node *node;
  Node *lastfree;  /* any free position is before this position */
  struct Table *metatable;
  GCObject *gclist;
} Table;

首先,類似User Data,Table也包括data和metatable,其中metatable的構(gòu)成如下:

  lu_byte flags; // 1<<p means tagmethod(p) is not present
  struct Table* metatable;

如果要判斷某個預(yù)定義下標的元方法是否存在,可以通過1<<p來判斷,如果有,則從metatable里獲取。

其次,Table包括array部分和hash table部分,array部分如下:

// array 
  unsigned int sizearray;
  TValue* array;

而hash table部分如下:

// hash table
  lu_byte lsizenode;
  Node* node;
  Node* lastfree;

Node就是一個key-value,通過key部分的鏈表串在一起:

typedef struct Node {
  TValue i_val;
  TKey i_key;
} Node;

typedef union TKey {
  struct {
    TValuefields;
    int next;  /* for chaining (offset for next node) */
  } nk;
  TValue tvk;
} TKey;

最后,gclist是用以垃圾回收的,按下不表。從而,我們可以重新調(diào)整下Table的聲明順序,使得更利于閱讀:

typedef struct Table{
  CommonHeader;
  
  lu_byte flags; // 1<<p means tagmethod(p) is not present
  struct Table* metatable;

  lu_byte lsizenode;
  Node* node;
  Node* lastfree;

  unsigned int sizearray;
  TValue* array;

  GCObject* gclist;
}Table;

Closure

到了最復(fù)雜的Closure部分。根據(jù)前面的鋪墊,我們知道Lua的函數(shù)包括Lua Closure, light C function以及 C Closure三種小類型,其中l(wèi)ight C function就是純c函數(shù),在Value的定義里直接用一個lua_CFunction函數(shù)指針指向,從而剩下兩個Closure類型。

lua的源碼里把Lua Closure和 C Closure作為一個聯(lián)合體,構(gòu)成了Closure類型:

typedef union Closure{
  CClosure c;
  LClosure l;
}Closure;

Closure作為一個GC Object,自然需要包含CommonHeader,由于是一個聯(lián)合體,所以這個CommonHeader就分別拆到了CClosure和LClosure里去了:

#define ClosureHeader \
    CommonHeader; lu_byte nupvalues; GCObject *gclist

typedef struct CClosure {
  ClosureHeader;
  lua_CFunction f;
  TValue upvalue[1];  /* list of upvalues */
} CClosure;


typedef struct LClosure {
  ClosureHeader;
  struct Proto *p;
  UpVal *upvals[1];  /* list of upvalues */
} LClosure;

注意,這里CommonHeader+nupvalues+gclist共同構(gòu)成了ClosureHeader,這是因為兩種Closure都有公共的部分:nupvalues說明閉包變量的個數(shù),gclist則用以垃圾回收。

我們先看比較簡單的CClosure,就是直接把lua_CFunction加上被閉包的c變量upvalue[1]數(shù)組,此處利用數(shù)組在結(jié)構(gòu)的末尾,則只需聲明為一個元素的數(shù)組即可。

比較復(fù)雜的是LClosure,中間的關(guān)鍵結(jié)構(gòu)是Proto* p; 這個字段代表了一個Lua 閉包。我們一步步展開:

/*
** Function Prototypes
*/
typedef struct Proto {
  CommonHeader;
  lu_byte numparams;  /* number of fixed parameters */
  lu_byte is_vararg;
  lu_byte maxstacksize;  /* maximum stack used by this function */
  int sizeupvalues;  /* size of 'upvalues' */
  int sizek;  /* size of 'k' */
  int sizecode;
  int sizelineinfo;
  int sizep;  /* size of 'p' */
  int sizelocvars;
  int linedefined;
  int lastlinedefined;
  TValue *k;  /* constants used by the function */
  Instruction *code;
  struct Proto **p;  /* functions defined inside the function */
  int *lineinfo;  /* map from opcodes to source lines (debug information) */
  LocVar *locvars;  /* information about local variables (debug information) */
  Upvaldesc *upvalues;  /* upvalue information */
  struct LClosure *cache;  /* last created closure with this prototype */
  TString  *source;  /* used for debug information */
  GCObject *gclist;
} Proto;

調(diào)整字節(jié)對齊后的結(jié)構(gòu)體并不利于閱讀,我們不妨重新排版下:

typedef struct Proto{
  CommonHeader;
  
  // 1
  lu_byte numparams;
  lu_byte is_vararg;
  lu_byte maxstacksize;

  // 2
  int sizek;
  TValue* k;
  
  // 3
  int sizelocalvars;
  LocVar* locvars;

  // 4
  int sizeupvalues;
  Upvaldesc* upvalues;

  // 5
  int sizep;
  struct Proto** p;
  struct LClosure* cache;

  // 6
  int sizecode;
  Instruction* code;

  // 7
  int sizelineinfo;
  int* lineinfo;

  // 8
  int linedefined;
  int lastlinedefined;
  TString* source;

  // 9
  GCObject* gclist;
}Proto;
  1. 函數(shù)原型信息
  • num params: 函數(shù)參數(shù)個數(shù)
  • is_vararg: 是否是有變長參數(shù)
  • maxstacksize: 最大的函數(shù)棧長度
  1. 常量
  • sizek: 常量數(shù)組長度
  • k: 常量數(shù)組
  1. 局部變量
  • sizelocalvars:局部變量數(shù)組長度
  • localvars: 局部變量數(shù)組
  1. 閉包變量
  • sizeupvalues: 閉包變量數(shù)組長度
  • upvalus: 閉包變量數(shù)組
  1. 嵌套的Proto:
  • sizep:嵌套的Proto數(shù)組長度
  • p:嵌套的Proto數(shù)組
  • cache: 緩存嵌套的Proto的閉包。
  1. Proto代表一個可執(zhí)行函數(shù),前面的信息都是數(shù)據(jù)部分(參數(shù)、常量、局部變量、閉包變量),此處是指令:
  • sizecode:指令數(shù)組的長度
  • code:三地址指令數(shù)組,后面單獨講解。
  1. 行信息,用以debug,每行指令都有對應(yīng)的行信息。
  • sizelineinfo:行信息數(shù)組長度
  • lineinfo:行信息數(shù)組
  1. 源碼
  • linedefinedlastlinedefined:函數(shù)的起始定義行號
  • source:源碼字符串。
  1. gclist,垃圾回收專用,后面講解。

到此為止,我們把Proto的字段分拆一個閉包函數(shù)所需要的每個部分,更易于理解。但還有幾個小模塊。

LocVar

/*
** Description of a local variable for function prototypes
** (used for debug information)
*/
typedef struct LocVar {
  TString *varname;
  int startpc;  /* first point where variable is active */
  int endpc;    /* first point where variable is dead */
} LocVar;

LocVar的定義,包括變量名+作用域。

Upvaldesc

/*
** Description of an upvalue for function prototypes
*/
typedef struct Upvaldesc {
  TString *name;  /* upvalue name (for debug information) */
  lu_byte instack;  /* whether it is in stack */
  lu_byte idx;  /* index of upvalue (in stack or in outer function's list) */
} Upvaldesc;

Upvaldesc只是描述了閉包變量的信息:是否在棧上+在棧上的Index。這里只有描述信息,那么閉包變量的值存儲在哪里呢?

我們回頭看下LClosure的定義:

typedef struct LClosure {
  ClosureHeader;
  struct Proto *p;
  UpVal *upvals[1];  /* list of upvalues */
} LClosure;

注意看,這里和CClosure不同的是,CClosure直接用TValue數(shù)組存儲閉包變量,但LClosure則是用UpVal數(shù)組。我們看下UpVal。

UpVal

/*
** Upvalues for Lua closures
*/
struct UpVal {
  TValue *v;  /* points to stack or to its own value */
  lu_mem refcount;  /* reference counter */
  union {
    struct {  /* (when open) */
      UpVal *next;  /* linked list */
      int touched;  /* mark to avoid cycles with dead threads */
    } open;
    TValue value;  /* the value (when closed) */
  } u;
};

UpVal定義在lfunc.h文件里,這里第一個字段v就是指向了閉包變量的真正的值的指針。refcount是被閉包的引用計數(shù),按下不談。單說后面的聯(lián)合體:

  union {
    struct {  /* (when open) */
      UpVal *next;  /* linked list */
      int touched;  /* mark to avoid cycles with dead threads */
    } open;
    TValue value;  /* the value (when closed) */
  } u;

注意看,聯(lián)合體內(nèi)部有一個open結(jié)構(gòu)和一個value字段。一個Proto在外層函數(shù)沒有返回之前,處于open狀態(tài),閉包的變量,直接通過UpVal ->v這個指針引用。此時open結(jié)構(gòu)用來把當前作用域內(nèi)的所有閉包變量都串起來做成一個鏈表,方便查找。此時u->value并沒有用到。

但是,如果外層函數(shù)返回,則Proto需要把閉包變量的值拷貝出來,保證對象安全。這個拷貝就放在u->value里。此時,UpVal ->v也直接指向內(nèi)部的u->value。

從而,我們也可以通過判斷UpVal ->v和u->value是否相等來判斷UpVal處于open還是clsoed狀態(tài):

#define upisopen(up)    ((up)->v != &(up)->u.value)

待續(xù)

對象系統(tǒng)的定義部分就到這里,下次分解下對象系統(tǒng)基本屬性讀寫的util。
......

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Lua 是單線程的,但是Lua卻有thread類型,顯然直覺上Lua的thread并非通常意義上的線程,實際上它是...
    ffl閱讀 4,845評論 2 5
  • 1.1程序塊:Lua執(zhí)行的每段代碼,例如一個源代碼文件或者交互模式中輸入的一行代碼,都稱為一個程序塊 1.2注釋:...
    c_xiaoqiang閱讀 2,699評論 0 9
  • Nginx API for Lua Introduction ngx.arg ngx.var.VARIABLE C...
    吃瓜的東閱讀 6,109評論 0 5
  • 1. 寫在前面 很多時候我們都需要借助一些腳本語言來為我們實現(xiàn)一些動態(tài)的配置,那么就會涉及到如何讓腳本語言跟原生語...
    杰嗒嗒的阿杰閱讀 3,508評論 9 31
  • 鹿 過草地 海 在翻騰 鯨 遨游
    斐狐閱讀 219評論 0 0

友情鏈接更多精彩內(nèi)容