The Battle for Wesnoth  1.15.1+dev
lua_formula_bridge.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2017-2018 by the Battle for Wesnoth Project https://www.wesnoth.org/
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY.
10 
11  See the COPYING file for more details.
12 */
13 
15 
16 #include "boost/variant/static_visitor.hpp"
17 
18 #include "game_board.hpp"
20 #include "scripting/lua_unit.hpp"
21 #include "scripting/lua_common.hpp"
22 #include "lua/lauxlib.h"
23 #include "lua/lua.h"
24 #include "formula/callable_objects.hpp"
25 #include "formula/formula.hpp"
26 #include "variable.hpp"
27 
28 #include "resources.hpp"
29 #include "units/map.hpp"
30 #include "units/unit.hpp"
31 
32 static const char formulaKey[] = "formula";
33 
34 using namespace wfl;
35 
38 
41  int table_i;
42 public:
43  lua_callable(lua_State* L, int i) : mState(L), table_i(lua_absindex(L,i)) {}
44  variant get_value(const std::string& key) const {
45  if(key == "__list") {
46  std::vector<variant> values;
47  std::size_t n = lua_rawlen(mState, table_i);
48  if(n == 0) {
49  return variant();
50  }
51  for(std::size_t i = 1; i <= n; i++) {
52  lua_pushinteger(mState, i);
53  lua_gettable(mState, table_i);
54  values.push_back(luaW_tofaivariant(mState, -1));
55  }
56  return variant(values);
57  } else if(key == "__map") {
58  std::map<variant,variant> values;
59  for(lua_pushnil(mState); lua_next(mState, table_i); lua_pop(mState, 1)) {
60  values[luaW_tofaivariant(mState, -2)] = luaW_tofaivariant(mState, -1);
61  }
62  return variant(values);
63  }
64  lua_pushlstring(mState, key.c_str(), key.size());
65  lua_gettable(mState, table_i);
66  variant result = luaW_tofaivariant(mState, -1);
67  lua_pop(mState, 1);
68  return result;
69  }
70  void get_inputs(formula_input_vector& inputs) const {
71  add_input(inputs, "__list");
72  add_input(inputs, "__map");
73  for(lua_pushnil(mState); lua_next(mState, table_i); lua_pop(mState,1)) {
74  lua_pushvalue(mState, -2);
75  bool is_valid_key = (lua_type(mState, -1) == LUA_TSTRING) && !lua_isnumber(mState, -1);
76  lua_pop(mState, 1);
77  if(is_valid_key) {
78  std::string key = lua_tostring(mState, -2);
79  if(key.find_first_not_of(formula::id_chars) != std::string::npos) {
80  add_input(inputs, key);
81  }
82  }
83  }
84  }
85  int do_compare(const formula_callable* other) const {
86  const lua_callable* lua = dynamic_cast<const lua_callable*>(other);
87  if(lua == nullptr) {
88  return formula_callable::do_compare(other);
89  }
90  if(mState == lua->mState) { // Which should always be the case, but let's be safe here
91  if(lua_compare(mState, table_i, lua->table_i, LUA_OPEQ)) {
92  return 0;
93  }
94  int top = lua_gettop(mState);
95  if(lua_getmetatable(mState, table_i)) {
96  lua_getfield(mState, -1, "__lt");
97  if(!lua_isnoneornil(mState, -1)) {
98  if(lua_getmetatable(mState, lua->table_i)) {
99  lua_getfield(mState, -1, "__lt");
100  if(!lua_isnoneornil(mState, -1)) {
101  lua_settop(mState, top);
102  return lua_compare(mState, table_i, lua->table_i, LUA_OPLT) ? -1 : 1;
103  }
104  if(lua_compare(mState, -4, -2, LUA_OPEQ)) {
105  lua_settop(mState, top);
106  return 0;
107  }
108  const void* lhs = lua_topointer(mState, -4);
109  const void* rhs = lua_topointer(mState, -2);
110  lua_settop(mState, top);
111  return lhs < rhs ? -1 : (lhs > rhs ? 1 : 0);
112  }
113  }
114  }
115  lua_settop(mState, top);
116  return lua_topointer(mState, -2) < lua_topointer(mState, -1) ? -1 : 1;
117  }
118  return mState < lua->mState ? -1 : 1;
119  }
120 };
121 
123  if(val.is_int()) {
124  lua_pushinteger(L, val.as_int());
125  } else if(val.is_decimal()) {
126  lua_pushnumber(L, val.as_decimal() / 1000.0);
127  } else if(val.is_string()) {
128  const std::string result_string = val.as_string();
129  lua_pushlstring(L, result_string.c_str(), result_string.size());
130  } else if(val.is_list()) {
131  lua_newtable(L);
132  for(const variant& v : val.as_list()) {
133  lua_pushinteger(L, lua_rawlen(L, -1) + 1);
134  luaW_pushfaivariant(L, v);
135  lua_settable(L, -3);
136  }
137  } else if(val.is_map()) {
138  typedef std::map<variant,variant>::value_type kv_type;
139  lua_newtable(L);
140  for(const kv_type& v : val.as_map()) {
141  luaW_pushfaivariant(L, v.first);
142  luaW_pushfaivariant(L, v.second);
143  lua_settable(L, -3);
144  }
145  } else if(val.is_callable()) {
146  // First try a few special cases
147  if(auto u_ref = val.try_convert<unit_callable>()) {
148  const unit& u = u_ref->get_unit();
150  if(&*un_it == &u) {
152  } else {
153  luaW_pushunit(L, u.side(), u.underlying_id());
154  }
155  } else if(auto loc_ref = val.try_convert<location_callable>()) {
156  luaW_pushlocation(L, loc_ref->loc());
157  } else {
158  // If those fail, convert generically to a map
159  auto obj = val.as_callable();
160  formula_input_vector inputs;
161  obj->get_inputs(inputs);
162  lua_newtable(L);
163  for(const formula_input& attr : inputs) {
164  if(attr.access == FORMULA_WRITE_ONLY) {
165  continue;
166  }
167  lua_pushstring(L, attr.name.c_str());
168  luaW_pushfaivariant(L, obj->query_value(attr.name));
169  lua_settable(L, -3);
170  }
171  }
172  } else if(val.is_null()) {
173  lua_pushnil(L);
174  }
175 }
176 
178  switch(lua_type(L, i)) {
179  case LUA_TBOOLEAN:
180  return variant(lua_tointeger(L, i));
181  case LUA_TNUMBER:
183  case LUA_TSTRING:
184  return variant(lua_tostring(L, i));
185  case LUA_TTABLE:
186  return variant(std::make_shared<lua_callable>(L, i));
187  case LUA_TUSERDATA:
188  static t_string tstr;
189  static vconfig vcfg = vconfig::unconstructed_vconfig();
190  static map_location loc;
191  if(luaW_totstring(L, i, tstr)) {
192  return variant(tstr.str());
193  } else if(luaW_tovconfig(L, i, vcfg)) {
194  return variant(std::make_shared<config_callable>(vcfg.get_parsed_config()));
195  } else if(unit* u = luaW_tounit(L, i)) {
196  return variant(std::make_shared<unit_callable>(*u));
197  } else if(luaW_tolocation(L, i, loc)) {
198  return variant(std::make_shared<location_callable>(loc));
199  }
200  break;
201  }
202  return variant();
203 }
204 
205 /**
206  * Evaluates a formula in the formula engine.
207  * - Arg 1: Formula string.
208  * - Arg 2: optional context; can be a unit or a Lua table.
209  * - Ret 1: Result of the formula.
210  */
212 {
213  bool need_delete = false;
214  fwrapper* form;
215  if(void* ud = luaL_testudata(L, 1, formulaKey)) {
216  form = static_cast<fwrapper*>(ud);
217  } else {
218  need_delete = true;
219  form = new fwrapper(luaL_checkstring(L, 1));
220  }
221  std::shared_ptr<formula_callable> context, fallback;
222  if(unit* u = luaW_tounit(L, 2)) {
223  context.reset(new unit_callable(*u));
224  } else if(lua_istable(L, 2)) {
225  context.reset(new lua_callable(L, 2));
226  } else {
227  context.reset(new map_formula_callable);
228  }
229  variant result = form->evaluate(*context);
230  luaW_pushfaivariant(L, result);
231  if(need_delete) {
232  delete form;
233  }
234  return 1;
235 }
236 
238 {
239  if(!lua_isstring(L, 1)) {
240  luaW_type_error(L, 1, "string");
241  }
242  new(L) fwrapper(lua_tostring(L, 1));
244  return 1;
245 }
246 
248  : formula_ptr(new formula(code, functions))
249 {
250 }
251 
253 {
254  if(formula_ptr) {
255  return formula_ptr->str();
256  }
257  return "";
258 }
259 
261 {
262  if(formula_ptr) {
263  return formula_ptr->evaluate(variables, fdb);
264  }
265  return variant();
266 }
267 
269 {
271  form->~fwrapper();
272  return 0;
273 }
274 
276 {
278  const std::string str = form->str();
279  lua_pushlstring(L, str.c_str(), str.size());
280  return 1;
281 }
282 
284 {
287  lua_setfield(L, -2, "__gc");
289  lua_setfield(L, -2, "__tostring");
291  lua_setfield(L, -2, "__call");
292  lua_pushstring(L, "formula");
293  lua_setfield(L, -2, "__metatable");
294 
295  return "Adding formula metatable...\n";
296 }
#define lua_isnoneornil(L, n)
Definition: lua.h:359
#define lua_pushcfunction(L, f)
Definition: lua.h:350
lua_unit * luaW_pushunit(lua_State *L, Args... args)
Definition: lua_unit.hpp:114
bool luaW_tovconfig(lua_State *L, int index, vconfig &vcfg)
Gets an optional vconfig from either a table or a userdata.
Definition: lua_common.cpp:816
virtual const unit_map & units() const override
Definition: game_board.hpp:114
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.cpp:172
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.cpp:251
bool is_map() const
Definition: variant.hpp:67
This class represents a single unit of a specific type.
Definition: unit.hpp:99
#define LUA_TUSERDATA
Definition: lua.h:71
int luaW_type_error(lua_State *L, int narg, const char *tname)
int as_int() const
Definition: variant.cpp:292
static int impl_formula_tostring(lua_State *L)
bool is_string() const
Definition: variant.hpp:66
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.cpp:167
bool is_callable() const
Definition: variant.hpp:64
LUA_API int lua_gettable(lua_State *L, int idx)
Definition: lapi.cpp:612
LUA_API void lua_settable(lua_State *L, int idx)
Definition: lapi.cpp:766
void get_inputs(formula_input_vector &inputs) const
#define lua_tointeger(L, i)
Definition: lua.h:342
std::vector< formula_input > formula_input_vector
const std::map< variant, variant > & as_map() const
Definition: variant.cpp:331
#define lua_tonumber(L, i)
Definition: lua.h:341
LUALIB_API void luaL_setmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:312
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:160
bool is_list() const
Definition: variant.hpp:65
#define lua_pop(L, n)
Definition: lua.h:344
const std::vector< variant > & as_list() const
Definition: variant.cpp:325
bool is_decimal() const
Definition: variant.hpp:63
bool is_int() const
Definition: variant.hpp:62
const std::string & as_string() const
Definition: variant.cpp:319
#define LUA_OPLT
Definition: lua.h:214
int intf_eval_formula(lua_State *)
Evaluates a formula in the formula engine.
#define LUA_TSTRING
Definition: lua.h:68
LUA_API int lua_compare(lua_State *L, int index1, int index2, int op)
Definition: lapi.cpp:318
int as_decimal() const
Returns variant&#39;s internal representation of decimal number: ie, 1.234 is represented as 1234...
Definition: variant.cpp:301
fwrapper(const std::string &code, wfl::function_symbol_table *functions=nullptr)
LUA_API int lua_isstring(lua_State *L, int idx)
Definition: lapi.cpp:283
variant luaW_tofaivariant(lua_State *L, int i)
unit * luaW_tounit(lua_State *L, int index, bool only_on_map)
Converts a Lua value to a unit pointer.
Definition: lua_unit.cpp:143
variant get_value(const std::string &key) const
game_board * gameboard
Definition: resources.cpp:20
wfl::variant evaluate(const wfl::formula_callable &variables, wfl::formula_debugger *fdb=nullptr) const
LUA_API const char * lua_pushlstring(lua_State *L, const char *s, size_t len)
Definition: lapi.cpp:479
#define LUA_TNUMBER
Definition: lua.h:67
LUA_API int lua_getmetatable(lua_State *L, int objindex)
Definition: lapi.cpp:697
config get_parsed_config() const
Definition: variable.cpp:140
LUALIB_API void * luaL_testudata(lua_State *L, int ud, const char *tname)
Definition: lauxlib.cpp:318
int intf_compile_formula(lua_State *)
#define lua_newtable(L)
Definition: lua.h:346
LUA_API void lua_pushnil(lua_State *L)
Definition: lapi.cpp:450
lua_State * mState
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
Definition: lapi.cpp:458
Encapsulates the map of the game.
Definition: location.hpp:42
static int impl_formula_collect(lua_State *L)
const_formula_callable_ptr as_callable() const
Definition: variant.hpp:82
unit_iterator find(std::size_t id)
Definition: map.cpp:311
bool luaW_totstring(lua_State *L, int index, t_string &str)
Converts a scalar to a translatable string.
Definition: lua_common.cpp:577
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:299
LUA_API void * lua_touserdata(lua_State *L, int idx)
Definition: lapi.cpp:413
std::size_t i
Definition: function.cpp:933
std::string register_metatables(lua_State *)
#define lua_tostring(L, i)
Definition: lua.h:366
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:237
LUA_API int lua_isnumber(lua_State *L, int idx)
Definition: lapi.cpp:276
static vconfig unconstructed_vconfig()
This is just a wrapper for the default constructor; it exists for historical reasons and to make it c...
Definition: variable.cpp:116
lua_callable(lua_State *L, int i)
LUA_API size_t lua_rawlen(lua_State *L, int idx)
Definition: lapi.cpp:392
static const char *const id_chars
Definition: formula.hpp:74
bool is_null() const
Functions to test the type of the internal value.
Definition: variant.hpp:61
std::shared_ptr< T > try_convert() const
Definition: variant.hpp:89
LUA_API const void * lua_topointer(lua_State *L, int idx)
Definition: lapi.cpp:429
#define lua_istable(L, n)
Definition: lua.h:353
Definition: contexts.hpp:42
static const char formulaKey[]
void luaW_pushlocation(lua_State *L, const map_location &ml)
Converts a map location object to a Lua table pushed at the top of the stack.
Definition: lua_common.cpp:644
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1258
A variable-expanding proxy for the config class.
Definition: variable.hpp:42
int side() const
The side this unit belongs to.
Definition: unit.hpp:303
virtual int do_compare(const formula_callable *callable) const
Definition: callable.hpp:145
const std::string & str() const
Definition: tstring.hpp:186
LUA_API int lua_getfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:622
#define LUA_TTABLE
Definition: lua.h:69
static map_location::DIRECTION n
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:466
LUA_API const char * lua_pushstring(lua_State *L, const char *s)
Definition: lapi.cpp:491
LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:777
std::size_t underlying_id() const
This unit&#39;s unique internal ID.
Definition: unit.hpp:355
#define LUA_TBOOLEAN
Definition: lua.h:65
LUA_API int lua_next(lua_State *L, int idx)
Definition: lapi.cpp:1123
int do_compare(const formula_callable *other) const
#define LUA_OPEQ
Definition: lua.h:213
void luaW_pushfaivariant(lua_State *L, variant val)
bool luaW_tolocation(lua_State *L, int index, map_location &loc)
Converts an optional table or pair of integers to a map location object.
Definition: lua_common.cpp:655
#define luaL_checkstring(L, n)
Definition: lauxlib.h:124
std::shared_ptr< formula > formula_ptr
Definition: formula_fwd.hpp:21