The Battle for Wesnoth  1.15.11+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 "game_board.hpp"
18 #include "scripting/lua_unit.hpp"
19 #include "scripting/lua_common.hpp"
20 #include "lua/lauxlib.h"
21 #include "lua/lua.h"
22 #include "formula/callable_objects.hpp"
23 #include "formula/formula.hpp"
24 #include "variable.hpp"
25 
26 #include "resources.hpp"
27 #include "units/map.hpp"
28 #include "units/unit.hpp"
29 
30 static const char formulaKey[] = "formula";
31 
32 using namespace wfl;
33 
36 
39  int table_i;
40 public:
41  lua_callable(lua_State* L, int i) : mState(L), table_i(lua_absindex(L,i)) {}
42  variant get_value(const std::string& key) const {
43  if(key == "__list") {
44  std::vector<variant> values;
45  std::size_t n = lua_rawlen(mState, table_i);
46  if(n == 0) {
47  return variant();
48  }
49  for(std::size_t i = 1; i <= n; i++) {
50  lua_pushinteger(mState, i);
51  lua_gettable(mState, table_i);
52  values.push_back(luaW_tofaivariant(mState, -1));
53  }
54  return variant(values);
55  } else if(key == "__map") {
56  std::map<variant,variant> values;
57  for(lua_pushnil(mState); lua_next(mState, table_i); lua_pop(mState, 1)) {
58  values[luaW_tofaivariant(mState, -2)] = luaW_tofaivariant(mState, -1);
59  }
60  return variant(values);
61  }
62  lua_pushlstring(mState, key.c_str(), key.size());
63  lua_gettable(mState, table_i);
64  variant result = luaW_tofaivariant(mState, -1);
65  lua_pop(mState, 1);
66  return result;
67  }
68  void get_inputs(formula_input_vector& inputs) const {
69  add_input(inputs, "__list");
70  add_input(inputs, "__map");
71  for(lua_pushnil(mState); lua_next(mState, table_i); lua_pop(mState,1)) {
72  lua_pushvalue(mState, -2);
73  bool is_valid_key = (lua_type(mState, -1) == LUA_TSTRING) && !lua_isnumber(mState, -1);
74  lua_pop(mState, 1);
75  if(is_valid_key) {
76  std::string key = lua_tostring(mState, -2);
77  if(key.find_first_not_of(formula::id_chars) != std::string::npos) {
78  add_input(inputs, key);
79  }
80  }
81  }
82  }
83  int do_compare(const formula_callable* other) const {
84  const lua_callable* lua = dynamic_cast<const lua_callable*>(other);
85  if(lua == nullptr) {
86  return formula_callable::do_compare(other);
87  }
88  if(mState == lua->mState) { // Which should always be the case, but let's be safe here
89  if(lua_compare(mState, table_i, lua->table_i, LUA_OPEQ)) {
90  return 0;
91  }
92  int top = lua_gettop(mState);
93  if(lua_getmetatable(mState, table_i)) {
94  lua_getfield(mState, -1, "__lt");
95  if(!lua_isnoneornil(mState, -1)) {
96  if(lua_getmetatable(mState, lua->table_i)) {
97  lua_getfield(mState, -1, "__lt");
98  if(!lua_isnoneornil(mState, -1)) {
99  lua_settop(mState, top);
100  return lua_compare(mState, table_i, lua->table_i, LUA_OPLT) ? -1 : 1;
101  }
102  if(lua_compare(mState, -4, -2, LUA_OPEQ)) {
103  lua_settop(mState, top);
104  return 0;
105  }
106  const void* lhs = lua_topointer(mState, -4);
107  const void* rhs = lua_topointer(mState, -2);
108  lua_settop(mState, top);
109  return lhs < rhs ? -1 : (lhs > rhs ? 1 : 0);
110  }
111  }
112  }
113  lua_settop(mState, top);
114  return lua_topointer(mState, -2) < lua_topointer(mState, -1) ? -1 : 1;
115  }
116  return mState < lua->mState ? -1 : 1;
117  }
118 };
119 
121  if(val.is_int()) {
122  lua_pushinteger(L, val.as_int());
123  } else if(val.is_decimal()) {
124  lua_pushnumber(L, val.as_decimal() / 1000.0);
125  } else if(val.is_string()) {
126  const std::string result_string = val.as_string();
127  lua_pushlstring(L, result_string.c_str(), result_string.size());
128  } else if(val.is_list()) {
129  lua_newtable(L);
130  for(const variant& v : val.as_list()) {
131  lua_pushinteger(L, lua_rawlen(L, -1) + 1);
132  luaW_pushfaivariant(L, v);
133  lua_settable(L, -3);
134  }
135  } else if(val.is_map()) {
136  typedef std::map<variant,variant>::value_type kv_type;
137  lua_newtable(L);
138  for(const kv_type& v : val.as_map()) {
139  luaW_pushfaivariant(L, v.first);
140  luaW_pushfaivariant(L, v.second);
141  lua_settable(L, -3);
142  }
143  } else if(val.is_callable()) {
144  // First try a few special cases
145  if(auto u_ref = val.try_convert<unit_callable>()) {
146  const unit& u = u_ref->get_unit();
148  if(&*un_it == &u) {
150  } else {
151  luaW_pushunit(L, u.side(), u.underlying_id());
152  }
153  } else if(auto loc_ref = val.try_convert<location_callable>()) {
154  luaW_pushlocation(L, loc_ref->loc());
155  } else {
156  // If those fail, convert generically to a map
157  auto obj = val.as_callable();
158  formula_input_vector inputs;
159  obj->get_inputs(inputs);
160  lua_newtable(L);
161  for(const formula_input& attr : inputs) {
162  if(attr.access == FORMULA_WRITE_ONLY) {
163  continue;
164  }
165  lua_pushstring(L, attr.name.c_str());
166  luaW_pushfaivariant(L, obj->query_value(attr.name));
167  lua_settable(L, -3);
168  }
169  }
170  } else if(val.is_null()) {
171  lua_pushnil(L);
172  }
173 }
174 
176  switch(lua_type(L, i)) {
177  case LUA_TBOOLEAN:
178  return variant(lua_tointeger(L, i));
179  case LUA_TNUMBER:
181  case LUA_TSTRING:
182  return variant(lua_tostring(L, i));
183  case LUA_TTABLE:
184  return variant(std::make_shared<lua_callable>(L, i));
185  case LUA_TUSERDATA:
186  static t_string tstr;
187  static vconfig vcfg = vconfig::unconstructed_vconfig();
188  static map_location loc;
189  if(luaW_totstring(L, i, tstr)) {
190  return variant(tstr.str());
191  } else if(luaW_tovconfig(L, i, vcfg)) {
192  return variant(std::make_shared<config_callable>(vcfg.get_parsed_config()));
193  } else if(unit* u = luaW_tounit(L, i)) {
194  return variant(std::make_shared<unit_callable>(*u));
195  } else if(luaW_tolocation(L, i, loc)) {
196  return variant(std::make_shared<location_callable>(loc));
197  }
198  break;
199  }
200  return variant();
201 }
202 
203 /**
204  * Evaluates a formula in the formula engine.
205  * - Arg 1: Formula string.
206  * - Arg 2: optional context; can be a unit or a Lua table.
207  * - Ret 1: Result of the formula.
208  */
210 {
211  bool need_delete = false;
212  fwrapper* form;
213  if(void* ud = luaL_testudata(L, 1, formulaKey)) {
214  form = static_cast<fwrapper*>(ud);
215  } else {
216  need_delete = true;
217  form = new fwrapper(luaL_checkstring(L, 1));
218  }
219  std::shared_ptr<formula_callable> context, fallback;
220  if(unit* u = luaW_tounit(L, 2)) {
221  context.reset(new unit_callable(*u));
222  } else if(lua_istable(L, 2)) {
223  context.reset(new lua_callable(L, 2));
224  } else {
225  context.reset(new map_formula_callable);
226  }
227  variant result = form->evaluate(*context);
228  luaW_pushfaivariant(L, result);
229  if(need_delete) {
230  delete form;
231  }
232  return 1;
233 }
234 
236 {
237  if(!lua_isstring(L, 1)) {
238  luaW_type_error(L, 1, "string");
239  }
240  new(L) fwrapper(lua_tostring(L, 1));
242  return 1;
243 }
244 
246  : formula_ptr(new formula(code, functions))
247 {
248 }
249 
251 {
252  if(formula_ptr) {
253  return formula_ptr->str();
254  }
255  return "";
256 }
257 
259 {
260  if(formula_ptr) {
261  return formula_ptr->evaluate(variables, fdb);
262  }
263  return variant();
264 }
265 
267 {
269  form->~fwrapper();
270  return 0;
271 }
272 
274 {
276  const std::string str = form->str();
277  lua_pushlstring(L, str.c_str(), str.size());
278  return 1;
279 }
280 
282 {
285  lua_setfield(L, -2, "__gc");
287  lua_setfield(L, -2, "__tostring");
289  lua_setfield(L, -2, "__call");
290  lua_pushstring(L, "formula");
291  lua_setfield(L, -2, "__metatable");
292 
293  return "Adding formula metatable...\n";
294 }
#define lua_isnoneornil(L, n)
Definition: lua.h:379
#define lua_pushcfunction(L, f)
Definition: lua.h:370
lua_unit * luaW_pushunit(lua_State *L, Args... args)
Definition: lua_unit.hpp:115
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:839
virtual const unit_map & units() const override
Definition: game_board.hpp:111
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.cpp:173
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.cpp:260
bool is_map() const
Definition: variant.hpp:67
This class represents a single unit of a specific type.
Definition: unit.hpp:120
#define LUA_TUSERDATA
Definition: lua.h:72
int luaW_type_error(lua_State *L, int narg, const char *tname)
int as_int() const
Definition: variant.cpp:294
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:168
bool is_callable() const
Definition: variant.hpp:64
LUA_API int lua_gettable(lua_State *L, int idx)
Definition: lapi.cpp:640
LUA_API void lua_settable(lua_State *L, int idx)
Definition: lapi.cpp:821
void get_inputs(formula_input_vector &inputs) const
#define lua_tointeger(L, i)
Definition: lua.h:362
std::vector< formula_input > formula_input_vector
const std::map< variant, variant > & as_map() const
Definition: variant.cpp:333
#define lua_tonumber(L, i)
Definition: lua.h:361
LUALIB_API void luaL_setmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:324
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:161
bool is_list() const
Definition: variant.hpp:65
#define lua_pop(L, n)
Definition: lua.h:364
const std::vector< variant > & as_list() const
Definition: variant.cpp:327
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:321
#define LUA_OPLT
Definition: lua.h:223
int intf_eval_formula(lua_State *)
Evaluates a formula in the formula engine.
#define LUA_TSTRING
Definition: lua.h:69
LUA_API int lua_compare(lua_State *L, int index1, int index2, int op)
Definition: lapi.cpp:327
int as_decimal() const
Returns variant&#39;s internal representation of decimal number: ie, 1.234 is represented as 1234...
Definition: variant.cpp:303
fwrapper(const std::string &code, wfl::function_symbol_table *functions=nullptr)
LUA_API int lua_isstring(lua_State *L, int idx)
Definition: lapi.cpp:292
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:142
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:502
#define LUA_TNUMBER
Definition: lua.h:68
LUA_API int lua_getmetatable(lua_State *L, int objindex)
Definition: lapi.cpp:741
config get_parsed_config() const
Definition: variable.cpp:176
LUALIB_API void * luaL_testudata(lua_State *L, int ud, const char *tname)
Definition: lauxlib.cpp:330
int intf_compile_formula(lua_State *)
#define lua_newtable(L)
Definition: lua.h:366
LUA_API void lua_pushnil(lua_State *L)
Definition: lapi.cpp:473
lua_State * mState
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
Definition: lapi.cpp:481
Encapsulates the map of the game.
Definition: location.hpp:37
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:309
bool luaW_totstring(lua_State *L, int index, t_string &str)
Converts a scalar to a translatable string.
Definition: lua_common.cpp:598
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:311
LUA_API void * lua_touserdata(lua_State *L, int idx)
Definition: lapi.cpp:432
std::size_t i
Definition: function.cpp:940
std::string register_metatables(lua_State *)
#define lua_tostring(L, i)
Definition: lua.h:386
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:246
LUA_API int lua_isnumber(lua_State *L, int idx)
Definition: lapi.cpp:285
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:152
lua_callable(lua_State *L, int i)
static const char *const id_chars
Definition: formula.hpp:74
LUA_API lua_Unsigned lua_rawlen(lua_State *L, int idx)
Definition: lapi.cpp:402
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:451
#define lua_istable(L, n)
Definition: lua.h:373
Definition: contexts.hpp:43
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:665
const map_location & get_location() const
The current map location this unit is at.
Definition: unit.hpp:1348
A variable-expanding proxy for the config class.
Definition: variable.hpp:44
int side() const
The side this unit belongs to.
Definition: unit.hpp:333
virtual int do_compare(const formula_callable *callable) const
Definition: callable.hpp:145
const std::string & str() const
Definition: tstring.hpp:190
LUA_API int lua_getfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:655
#define LUA_TTABLE
Definition: lua.h:70
static map_location::DIRECTION n
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:489
LUA_API const char * lua_pushstring(lua_State *L, const char *s)
Definition: lapi.cpp:514
LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:837
std::size_t underlying_id() const
This unit&#39;s unique internal ID.
Definition: unit.hpp:382
#define LUA_TBOOLEAN
Definition: lua.h:66
LUA_API int lua_next(lua_State *L, int idx)
Definition: lapi.cpp:1220
int do_compare(const formula_callable *other) const
#define LUA_OPEQ
Definition: lua.h:222
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:676
#define luaL_checkstring(L, n)
Definition: lauxlib.h:138
std::shared_ptr< formula > formula_ptr
Definition: formula_fwd.hpp:21