huangcm
2025-07-01 676035278781360996553c427a12bf358249ebf7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
#ifndef LIBTEXTCLASSIFIER_UTILS_LUA_UTILS_H_
#define LIBTEXTCLASSIFIER_UTILS_LUA_UTILS_H_
 
#include <functional>
#include <vector>
 
#include "utils/flatbuffers.h"
#include "utils/strings/stringpiece.h"
#include "utils/variant.h"
#include "flatbuffers/reflection_generated.h"
 
#ifdef __cplusplus
extern "C" {
#endif
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
#ifdef __cplusplus
}
#endif
 
namespace libtextclassifier3 {
 
static constexpr const char *kLengthKey = "__len";
static constexpr const char *kPairsKey = "__pairs";
static constexpr const char *kIndexKey = "__index";
 
// Casts to the lua user data type.
template <typename T>
void *AsUserData(const T *value) {
  return static_cast<void *>(const_cast<T *>(value));
}
template <typename T>
void *AsUserData(const T value) {
  return reinterpret_cast<void *>(value);
}
 
// Retrieves up-values.
template <typename T>
T FromUpValue(const int index, lua_State *state) {
  return static_cast<T>(lua_touserdata(state, lua_upvalueindex(index)));
}
 
class LuaEnvironment {
 public:
  // Wrapper for handling an iterator.
  class Iterator {
   public:
    virtual ~Iterator() {}
    static int NextCallback(lua_State *state);
    static int LengthCallback(lua_State *state);
    static int ItemCallback(lua_State *state);
    static int IteritemsCallback(lua_State *state);
 
    // Called when the next element of an iterator is fetched.
    virtual int Next(lua_State *state) const = 0;
 
    // Called when the length of the iterator is queried.
    virtual int Length(lua_State *state) const = 0;
 
    // Called when an item is queried.
    virtual int Item(lua_State *state) const = 0;
 
    // Called when a new iterator is started.
    virtual int Iteritems(lua_State *state) const = 0;
 
   protected:
    static constexpr int kIteratorArgId = 1;
  };
 
  template <typename T>
  class ItemIterator : public Iterator {
   public:
    void NewIterator(StringPiece name, const T *items, lua_State *state) const {
      lua_newtable(state);
      luaL_newmetatable(state, name.data());
      lua_pushlightuserdata(state, AsUserData(this));
      lua_pushlightuserdata(state, AsUserData(items));
      lua_pushcclosure(state, &Iterator::ItemCallback, 2);
      lua_setfield(state, -2, kIndexKey);
      lua_pushlightuserdata(state, AsUserData(this));
      lua_pushlightuserdata(state, AsUserData(items));
      lua_pushcclosure(state, &Iterator::LengthCallback, 2);
      lua_setfield(state, -2, kLengthKey);
      lua_pushlightuserdata(state, AsUserData(this));
      lua_pushlightuserdata(state, AsUserData(items));
      lua_pushcclosure(state, &Iterator::IteritemsCallback, 2);
      lua_setfield(state, -2, kPairsKey);
      lua_setmetatable(state, -2);
    }
 
    int Iteritems(lua_State *state) const override {
      lua_pushlightuserdata(state, AsUserData(this));
      lua_pushlightuserdata(
          state, lua_touserdata(state, lua_upvalueindex(kItemsArgId)));
      lua_pushnumber(state, 0);
      lua_pushcclosure(state, &Iterator::NextCallback, 3);
      return /*num results=*/1;
    }
 
    int Length(lua_State *state) const override {
      lua_pushinteger(state, FromUpValue<T *>(kItemsArgId, state)->size());
      return /*num results=*/1;
    }
 
    int Next(lua_State *state) const override {
      return Next(FromUpValue<T *>(kItemsArgId, state),
                  lua_tointeger(state, lua_upvalueindex(kIterValueArgId)),
                  state);
    }
 
    int Next(const T *items, const int64 pos, lua_State *state) const {
      if (pos >= items->size()) {
        return 0;
      }
 
      // Update iterator value.
      lua_pushnumber(state, pos + 1);
      lua_replace(state, lua_upvalueindex(3));
 
      // Push key.
      lua_pushinteger(state, pos + 1);
 
      // Push item.
      return 1 + Item(items, pos, state);
    }
 
    int Item(lua_State *state) const override {
      const T *items = FromUpValue<T *>(kItemsArgId, state);
      switch (lua_type(state, -1)) {
        case LUA_TNUMBER: {
          // Lua is one based, so adjust the index here.
          const int64 index =
              static_cast<int64>(lua_tonumber(state, /*idx=*/-1)) - 1;
          if (index < 0 || index >= items->size()) {
            TC3_LOG(ERROR) << "Invalid index: " << index;
            lua_error(state);
            return 0;
          }
          return Item(items, index, state);
        }
        case LUA_TSTRING: {
          size_t key_length = 0;
          const char *key = lua_tolstring(state, /*idx=*/-1, &key_length);
          return Item(items, StringPiece(key, key_length), state);
        }
        default:
          TC3_LOG(ERROR) << "Unexpected access type: " << lua_type(state, -1);
          lua_error(state);
          return 0;
      }
    }
 
    virtual int Item(const T *items, const int64 pos,
                     lua_State *state) const = 0;
 
    virtual int Item(const T *items, StringPiece key, lua_State *state) const {
      TC3_LOG(ERROR) << "Unexpected key access: " << key.ToString();
      lua_error(state);
      return 0;
    }
 
   protected:
    static constexpr int kItemsArgId = 2;
    static constexpr int kIterValueArgId = 3;
  };
 
  virtual ~LuaEnvironment();
  LuaEnvironment();
 
  // Compile a lua snippet into binary bytecode.
  // NOTE: The compiled bytecode might not be compatible across Lua versions
  // and platforms.
  bool Compile(StringPiece snippet, std::string *bytecode);
 
  typedef int (*CallbackHandler)(lua_State *);
 
  // Loads default libraries.
  void LoadDefaultLibraries();
 
  // Provides a callback to Lua.
  template <typename T, int (T::*handler)()>
  void Bind() {
    lua_pushlightuserdata(state_, static_cast<void *>(this));
    lua_pushcclosure(state_, &Dispatch<T, handler>, 1);
  }
 
  // Setup a named table that callsback whenever a member is accessed.
  // This allows to lazily provide required information to the script.
  template <typename T, int (T::*handler)()>
  void BindTable(const char *name) {
    lua_newtable(state_);
    luaL_newmetatable(state_, name);
    lua_pushlightuserdata(state_, static_cast<void *>(this));
    lua_pushcclosure(state_, &Dispatch<T, handler>, 1);
    lua_setfield(state_, -2, kIndexKey);
    lua_setmetatable(state_, -2);
  }
 
  void PushValue(const Variant &value);
 
  // Reads a string from the stack.
  StringPiece ReadString(const int index) const;
 
  // Pushes a string to the stack.
  void PushString(const StringPiece str);
 
  // Pushes a flatbuffer to the stack.
  void PushFlatbuffer(const reflection::Schema *schema,
                      const flatbuffers::Table *table);
 
  // Reads a flatbuffer from the stack.
  int ReadFlatbuffer(ReflectiveFlatbuffer *buffer);
 
  // Runs a closure in protected mode.
  // `func`: closure to run in protected mode.
  // `num_lua_args`: number of arguments from the lua stack to process.
  // `num_results`: number of result values pushed on the stack.
  int RunProtected(const std::function<int()> &func, const int num_args = 0,
                   const int num_results = 0);
 
  lua_State *state() const { return state_; }
 
 protected:
  lua_State *state_;
 
 private:
  // Auxiliary methods to expose (reflective) flatbuffer based data to Lua.
  static void PushFlatbuffer(const char *name, const reflection::Schema *schema,
                             const reflection::Object *type,
                             const flatbuffers::Table *table, lua_State *state);
  static int GetFieldCallback(lua_State *state);
  static int GetField(const reflection::Schema *schema,
                      const reflection::Object *type,
                      const flatbuffers::Table *table, lua_State *state);
 
  template <typename T, int (T::*handler)()>
  static int Dispatch(lua_State *state) {
    T *env = FromUpValue<T *>(1, state);
    return ((*env).*handler)();
  }
};
 
bool Compile(StringPiece snippet, std::string *bytecode);
 
}  // namespace libtextclassifier3
 
#endif  // LIBTEXTCLASSIFIER_UTILS_LUA_UTILS_H_