From fe3d4ce758822d65a0a5d617b7b77df2dbc972d8 Mon Sep 17 00:00:00 2001 From: Ben Longbons Date: Sun, 16 Mar 2014 14:55:57 -0700 Subject: Implement new magic frontend using sexpr --- src/map/atcommand.cpp | 18 +- src/map/itemdb.cpp | 5 +- src/map/itemdb.hpp | 3 +- src/map/magic-expr-eval.cpp | 3 + src/map/magic-expr.cpp | 33 +- src/map/magic-interpreter-aux.cpp | 3 + src/map/magic-interpreter-lexer.hpp | 1 - src/map/magic-interpreter-lexer.lpp | 152 ---- src/map/magic-interpreter-parser.ypp | 1441 ---------------------------------- src/map/magic-interpreter.cpp | 3 + src/map/magic-interpreter.hpp | 3 - src/map/magic-interpreter.py | 224 ++++++ src/map/magic-v2.cpp | 1245 +++++++++++++++++++++++++++++ src/map/magic-v2.hpp | 28 + src/map/magic.cpp | 2 - src/map/main.cpp | 2 + src/map/map.cpp | 3 +- src/map/npc.cpp | 2 +- src/map/script.cpp | 14 +- 19 files changed, 1566 insertions(+), 1619 deletions(-) create mode 100644 src/map/magic-expr-eval.cpp create mode 100644 src/map/magic-interpreter-aux.cpp delete mode 100644 src/map/magic-interpreter-lexer.hpp delete mode 100644 src/map/magic-interpreter-lexer.lpp delete mode 100644 src/map/magic-interpreter-parser.ypp create mode 100644 src/map/magic-interpreter.cpp create mode 100644 src/map/magic-interpreter.py create mode 100644 src/map/magic-v2.cpp create mode 100644 src/map/magic-v2.hpp (limited to 'src/map') diff --git a/src/map/atcommand.cpp b/src/map/atcommand.cpp index 29bf0b1..5455671 100644 --- a/src/map/atcommand.cpp +++ b/src/map/atcommand.cpp @@ -1290,7 +1290,7 @@ static ATCE atcommand_item(Session *s, dumb_ptr sd, ZString message) { - ItemName item_name; + XString item_name; int number = 0, item_id; struct item_data *item_data = NULL; int get_count, i; @@ -1306,9 +1306,12 @@ ATCE atcommand_item(Session *s, dumb_ptr sd, number = 1; item_id = 0; - if ((item_data = itemdb_searchname(item_name)) != NULL || - (item_data = itemdb_exists(atoi(item_name.c_str()))) != NULL) + if ((item_data = itemdb_searchname(item_name)) != NULL) + item_id = item_data->nameid; + else if (extract(item_name, &item_id) && (item_data = itemdb_exists(item_id)) != NULL) item_id = item_data->nameid; + else + item_id = 0; if (item_id >= 500) { @@ -3635,7 +3638,7 @@ ATCE atcommand_chardelitem(Session *s, dumb_ptr sd, ZString message) { CharName character; - ItemName item_name; + XString item_name; int i, number = 0, item_id, item_position, count; struct item_data *item_data; @@ -3643,9 +3646,12 @@ ATCE atcommand_chardelitem(Session *s, dumb_ptr sd, return ATCE::USAGE; item_id = 0; - if ((item_data = itemdb_searchname(item_name)) != NULL || - (item_data = itemdb_exists(atoi(item_name.c_str()))) != NULL) + if ((item_data = itemdb_searchname(item_name)) != NULL) + item_id = item_data->nameid; + else if (extract(item_name, &item_id) && (item_data = itemdb_exists(item_id)) != NULL) item_id = item_data->nameid; + else + item_id = 0; if (item_id > 500) { diff --git a/src/map/itemdb.cpp b/src/map/itemdb.cpp index 528c81f..1822b8a 100644 --- a/src/map/itemdb.cpp +++ b/src/map/itemdb.cpp @@ -48,8 +48,11 @@ void itemdb_searchname_sub(struct item_data *item, ItemName str, struct item_dat * 名前で検索 *------------------------------------------ */ -struct item_data *itemdb_searchname(ItemName str) +struct item_data *itemdb_searchname(XString str_) { + ItemName str = stringish(str_); + if (XString(str) != str_) + return nullptr; struct item_data *item = NULL; for (auto& pair : item_db) itemdb_searchname_sub(&pair.second, str, &item); diff --git a/src/map/itemdb.hpp b/src/map/itemdb.hpp index 4c07303..624030e 100644 --- a/src/map/itemdb.hpp +++ b/src/map/itemdb.hpp @@ -33,7 +33,8 @@ struct random_item_data int per; }; -struct item_data *itemdb_searchname(ItemName name); +struct item_data *itemdb_searchname(ItemName name) = delete; +struct item_data *itemdb_searchname(XString name); struct item_data *itemdb_search(int nameid); struct item_data *itemdb_exists(int nameid); diff --git a/src/map/magic-expr-eval.cpp b/src/map/magic-expr-eval.cpp new file mode 100644 index 0000000..57f9c32 --- /dev/null +++ b/src/map/magic-expr-eval.cpp @@ -0,0 +1,3 @@ +#include "magic-expr-eval.hpp" + +#include "../poison.hpp" diff --git a/src/map/magic-expr.cpp b/src/map/magic-expr.cpp index 279ba56..1be1b0b 100644 --- a/src/map/magic-expr.cpp +++ b/src/map/magic-expr.cpp @@ -358,7 +358,7 @@ int fun_neg(dumb_ptr, val_t *result, const_array args) static int fun_gte(dumb_ptr, val_t *result, const_array args) { - if (ARG_TYPE(0) == TYPE::STRING || ARG_TYPE(1) == TYPE::STRING) + if (ARG_TYPE(0) == TYPE::STRING || ARG_TYPE(1) == TYPE::STRING) { stringify(&args[0], 1); stringify(&args[1], 1); @@ -373,6 +373,14 @@ int fun_gte(dumb_ptr, val_t *result, const_array args) return 0; } +static +int fun_lt(dumb_ptr env, val_t *result, const_array args) +{ + fun_gte(env, result, args); + RESULTINT = !RESULTINT; + return 0; +} + static int fun_gt(dumb_ptr, val_t *result, const_array args) { @@ -391,6 +399,14 @@ int fun_gt(dumb_ptr, val_t *result, const_array args) return 0; } +static +int fun_lte(dumb_ptr env, val_t *result, const_array args) +{ + fun_gt(env, result, args); + RESULTINT = !RESULTINT; + return 0; +} + static int fun_eq(dumb_ptr, val_t *result, const_array args) { @@ -423,6 +439,14 @@ int fun_eq(dumb_ptr, val_t *result, const_array args) return 0; } +static +int fun_ne(dumb_ptr env, val_t *result, const_array args) +{ + fun_eq(env, result, args); + RESULTINT = !RESULTINT; + return 0; +} + static int fun_bitand(dumb_ptr, val_t *result, const_array args) { @@ -753,7 +777,7 @@ magic_find_item(const_array args, int index, struct item *item_, int *sta if (ARG_TYPE(index) == TYPE::INT) item_data = itemdb_exists(ARGINT(index)); else if (ARG_TYPE(index) == TYPE::STRING) - item_data = itemdb_searchname(stringish(ARGSTR(index))); + item_data = itemdb_searchname(ARGSTR(index)); else return -1; @@ -1250,9 +1274,12 @@ std::map functions = MAGIC_FUNCTION("%", "ii", 'i', fun_mod), MAGIC_FUNCTION("||", "ii", 'i', fun_or), MAGIC_FUNCTION("&&", "ii", 'i', fun_and), + MAGIC_FUNCTION("<", "..", 'i', fun_lt), MAGIC_FUNCTION(">", "..", 'i', fun_gt), + MAGIC_FUNCTION("<=", "..", 'i', fun_lte), MAGIC_FUNCTION(">=", "..", 'i', fun_gte), - MAGIC_FUNCTION("=", "..", 'i', fun_eq), + MAGIC_FUNCTION("==", "..", 'i', fun_eq), + MAGIC_FUNCTION("!=", "..", 'i', fun_ne), MAGIC_FUNCTION("|", "..", 'i', fun_bitor), MAGIC_FUNCTION("&", "ii", 'i', fun_bitand), MAGIC_FUNCTION("^", "ii", 'i', fun_bitxor), diff --git a/src/map/magic-interpreter-aux.cpp b/src/map/magic-interpreter-aux.cpp new file mode 100644 index 0000000..e293e78 --- /dev/null +++ b/src/map/magic-interpreter-aux.cpp @@ -0,0 +1,3 @@ +#include "magic-interpreter-aux.hpp" + +#include "../poison.hpp" diff --git a/src/map/magic-interpreter-lexer.hpp b/src/map/magic-interpreter-lexer.hpp deleted file mode 100644 index 8c7e195..0000000 --- a/src/map/magic-interpreter-lexer.hpp +++ /dev/null @@ -1 +0,0 @@ -// dummy header to make Make dependencies work diff --git a/src/map/magic-interpreter-lexer.lpp b/src/map/magic-interpreter-lexer.lpp deleted file mode 100644 index 38b7b1e..0000000 --- a/src/map/magic-interpreter-lexer.lpp +++ /dev/null @@ -1,152 +0,0 @@ -%{ -#include "magic-interpreter-lexer.hpp" - -#include "magic-interpreter-parser.hpp" - -#include "../io/cxxstdio.hpp" - -#ifdef HEADING -# error "what platform is this? please tell me who #defined HEADING" -#endif - -#define FIXLOC magic_frontend_lloc.first_line = magic_frontend_lineno - -#define HEADING(dir) { magic_frontend_lval.i = dir; FIXLOC; return DIR; } -%} - -%option yylineno -%option noyywrap -%option prefix="magic_frontend_" -%option nounput -%option noinput - -%% - -"S" HEADING(0); -"SW" HEADING(1); -"W" HEADING(2); -"NW" HEADING(3); -"N" HEADING(4); -"NE" HEADING(5); -"E" HEADING(6); -"SE" HEADING(7); -"=" {FIXLOC; return '=';} -"==" {FIXLOC; return EQ;} -"<>" {FIXLOC; return NEQ;} -"!=" {FIXLOC; return NEQ;} -">" {FIXLOC; return '>';} -"<" {FIXLOC; return '<';} -">=" {FIXLOC; return GTE;} -"<=" {FIXLOC; return LTE;} -"(" {FIXLOC; return '(';} -")" {FIXLOC; return ')';} -"+" {FIXLOC; return '+';} -"-" {FIXLOC; return '-';} -"*" {FIXLOC; return '*';} -"/" {FIXLOC; return '/';} -"%" {FIXLOC; return '%';} -"&&" {FIXLOC; return ANDAND;} -"||" {FIXLOC; return OROR;} -";" {FIXLOC; return ';';} -":" {FIXLOC; return ':';} -"," {FIXLOC; return ',';} -"@" {FIXLOC; return '@';} -"|" {FIXLOC; return '|';} -"[" {FIXLOC; return '[';} -"]" {FIXLOC; return ']';} -"&" {FIXLOC; return '&';} -"^" {FIXLOC; return '^';} -"." {FIXLOC; return '.';} -"<<" {FIXLOC; return SHL;} -">>" {FIXLOC; return SHR;} -"PROCEDURE" {FIXLOC; return PROCEDURE;} -"CALL" {FIXLOC; return CALL;} -"OR" {FIXLOC; return OR;} -"TO" {FIXLOC; return TO;} -"TOWARDS" {FIXLOC; return TOWARDS;} -"TELEPORT-ANCHOR" {FIXLOC; return TELEPORT_ANCHOR;} -"SILENT" {FIXLOC; return SILENT;} -"LOCAL" {FIXLOC; return LOCAL;} -"NONMAGIC" {FIXLOC; return NONMAGIC;} -"SPELL" {FIXLOC; return SPELL;} -"LET" {FIXLOC; return LET;} -"IN" {FIXLOC; return IN;} -"END" {FIXLOC; return END;} -"=>" {FIXLOC; return DARROW;} -"STRING" {FIXLOC; return STRING_TY;} -"REQUIRE" {FIXLOC; return REQUIRE;} -"CATALYSTS" {FIXLOC; return CATALYSTS;} -"COMPONENTS" {FIXLOC; return COMPONENTS;} -"MANA" {FIXLOC; return MANA;} -"CASTTIME" {FIXLOC; return CASTTIME;} -"SKIP" {FIXLOC; return SKIP;} -"ABORT" {FIXLOC; return ABORT;} -"BREAK" {FIXLOC; return BREAK;} -"EFFECT" {FIXLOC; return EFFECT_;} -"ATEND" {FIXLOC; return ATEND;} -"ATTRIGGER" {FIXLOC; return ATTRIGGER;} -"CONST" {FIXLOC; return CONST;} -"PC" {FIXLOC; return PC_F;} -"NPC" {FIXLOC; return NPC_F;} -"MOB" {FIXLOC; return MOB_F;} -"ENTITY" {FIXLOC; return ENTITY_F;} -"TARGET" {FIXLOC; return TARGET_F;} -"IF" {FIXLOC; return IF;} -"THEN" {FIXLOC; return THEN;} -"ELSE" {FIXLOC; return ELSE;} -"FOREACH" {FIXLOC; return FOREACH;} -"FOR" {FIXLOC; return FOR;} -"DO" {FIXLOC; return DO;} -"WAIT" {FIXLOC; return SLEEP;} - -\{([^\}]|\\.)*\} { - magic_frontend_lval.s = dumb_string::copy(yytext); - FIXLOC; - return SCRIPT_DATA; -} - -\"([^\"]|\\.)*\" { - dumb_string string = dumb_string::copy(yytext + 1); - const char *src = string.c_str(); - char *dst = &string[0]; - while (*src && *src != '"') - { - if (*src == '\\') - { - *dst++ = src[1]; - src += 2; - } - else - *dst++ = *src++; - } - *dst = '\0'; /* terminate */ - magic_frontend_lval.s = string; - FIXLOC; - return STRING; -} - -"-"?[0-9]+ { - magic_frontend_lval.i = atoi(yytext); - FIXLOC; - return INT; - } - -"0x"[0-9a-fA-F]+ { - magic_frontend_lval.i = strtol(yytext + 2, NULL, 16); - FIXLOC; - return INT; - } - -[a-zA-Z][-_a-zA-Z0-9]* { - magic_frontend_lval.s = dumb_string::copy(yytext); - FIXLOC; - return ID; -} - -"#".*$ /* Ignore comments */ -"//".*$ /* Ignore comments */ -[ \n\t\r] /* ignore whitespace */ -. FPRINTF(stderr, "%s: Unexpected character in line %d\n", current_magic_filename, magic_frontend_lineno); - -%% -// nothing to see here, move along diff --git a/src/map/magic-interpreter-parser.ypp b/src/map/magic-interpreter-parser.ypp deleted file mode 100644 index ef8b159..0000000 --- a/src/map/magic-interpreter-parser.ypp +++ /dev/null @@ -1,1441 +0,0 @@ -%code requires -{ -#include "magic-interpreter.hpp" - -extern -AString current_magic_filename; -} // %code requires - -%code -{ -#include "magic-interpreter-parser.hpp" - -#include -#include // exception to "no va_list" rule, even after cxxstdio - -#include "../strings/rstring.hpp" -#include "../strings/astring.hpp" -#include "../strings/zstring.hpp" - -#include "../generic/const_array.hpp" - -#include "../io/cxxstdio.hpp" - -#include "itemdb.hpp" -#include "magic-expr.hpp" - -AString current_magic_filename; - -// can't use src/warnings.hpp in generated code -#pragma GCC diagnostic warning "-Wall" -#pragma GCC diagnostic warning "-Wextra" -#pragma GCC diagnostic warning "-Wformat" -#ifndef __clang__ -# pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif - -static -size_t intern_id(ZString id_name); - -static -dumb_ptr fun_expr(AString name, const_array> argv, int line, int column); - -static -dumb_ptr dot_expr(dumb_ptr lhs, int id); - -static -void BIN_EXPR(dumb_ptr& x, AString name, dumb_ptr arg1, dumb_ptr arg2, int line, int column) -{ - dumb_ptr e[2]; - e[0] = arg1; - e[1] = arg2; - x = fun_expr(name, const_array>(e, 2), line, column); -} - -static -int failed_flag = 0; - -static -void magic_frontend_error(const char *msg); - -static __attribute__((format(printf, 3, 4))) -void fail(int line, int column, const char *fmt, ...); - -static -dumb_ptr new_spell(dumb_ptr guard); - -static -dumb_ptr spellguard_implication(dumb_ptr a, dumb_ptr b); - -static -dumb_ptr new_spellguard(SPELLGUARD ty); - -static -dumb_ptr new_effect(EFFECT ty); - -static -dumb_ptr set_effect_continuation(dumb_ptr src, dumb_ptr continuation); - -static -void add_spell(dumb_ptr spell, int line_nr); - -static -void add_teleport_anchor(dumb_ptr anchor, int line_nr); - -static -dumb_ptr op_effect(AString name, const_array> argv, int line, int column); - -// in magic-interpreter-lexer.cpp -int magic_frontend_lex(void); - -static -void install_proc(dumb_ptr proc); - -static -dumb_ptr call_proc(ZString name, dumb_ptr>> argvp, int line_nr, int column); - -static -void bind_constant(RString name, val_t *val, int line_nr); - -static -val_t *find_constant(RString name); - -} // %code - -%name-prefix="magic_frontend_" - -%locations - -%union -{ - int i; - SPELL_FLAG spell_flags; - SPELLARG spell_arg; - FOREACH_FILTER foreach_filter; - dumb_string s; - int op; - // magic_conf_t *magic_conf; - val_t value; - dumb_ptr expr; - e_location_t location; - e_area_t area; - args_rec_t arg_list; - dumb_ptr> letdefvp; - dumb_ptr spell; - struct { int id; SPELLARG ty; } spellarg_def; - letdef_t vardef; - dumb_ptr spellguard; - dumb_ptr components; - struct { int id, count; } component; - dumb_ptr effect; - dumb_ptr proc; - - // evil hackery - YYSTYPE() { really_memzero_this(this); } - ~YYSTYPE() = default; - YYSTYPE(const YYSTYPE& rhs) = default; - YYSTYPE& operator = (const YYSTYPE& rhs) = default; -} // %union - -%expect 7 - -%token INT -%token STRING -%token ID -%token DIR - -%token '=' -%token '<' -%token '>' -%token '+' -%token '-' -%token '*' -%token '/' -%token '%' -%token '@' -%token ',' -%token '.' -%token ':' -%token ';' -%token '|' -%token '[' -%token ']' -%token '&' -%token '^' - -%token CONST -%token PROCEDURE -%token CALL -%token SILENT -%token LOCAL -%token NONMAGIC -%token SHL -%token SHR -%token EQ -%token NEQ -%token GTE -%token LTE -%token ANDAND -%token OROR -%token SCRIPT_DATA -%token TO -%token TOWARDS -%token TELEPORT_ANCHOR -%token SPELL -%token LET -%token IN -%token END -%token DARROW -%token STRING_TY -%token REQUIRE -%token CATALYSTS -%token COMPONENTS -%token MANA -%token CASTTIME -%token SKIP -%token ABORT -%token BREAK -%token EFFECT_ -%token ATEND -%token ATTRIGGER -%token PC_F -%token NPC_F -%token MOB_F -%token ENTITY_F -%token TARGET_F -%token IF -%token THEN -%token ELSE -%token FOREACH -%token FOR -%token DO -%token SLEEP - -%type value -%type location -%type area -%type arg_list -%type arg_list_ne -%type defs -%type spelldef -%type argopt -%type def -%type spellbody_list -%type spellbody -%type spellguard -%type spellguard_list -%type prereq -%type item -%type items -%type item_list -%type item_name -%type selection; -%type effect -%type effect_list -%type maybe_trigger -%type maybe_end -%type spell_flags; - -%type expr -%type arg_ty -%type proc_formals_list -%type proc_formals_list_ne - -%left OROR -%left ANDAND -%left '<' '>' GTE LTE NEQ EQ -%left '+' '-' -%left '*' '/' '%' -%left SHL SHR '&' '^' '|' -%right '=' -%left OR -%left DARROW -%left '.' - -%% - -spellconf - -: /* empty */ -{} - -| spellconf_option semicolons spellconf -{} - -; - - -semicolons - -: /* empty */ -{} - -| semicolons ';' -{} - -; - - -proc_formals_list - -: /* empty */ -{ - $$ = dumb_ptr::make(); -} - -| proc_formals_list_ne -{ - $$ = $1; -} - -; - - -proc_formals_list_ne - -: ID -{ - $$ = dumb_ptr::make(); - $$->argv.push_back(intern_id($1)); - $1.delete_(); -} - -| proc_formals_list_ne ',' ID -{ - $$ = $1; - $$->argv.push_back(intern_id($3)); - $3.delete_(); -} - -; - - -spellconf_option - -: ID '=' expr -{ - if (find_constant($1.str())) - { - fail(@1.first_line, 0, "Attempt to redefine constant `%s' as global\n", $1.c_str()); - } - else - { - int var_id = intern_id($1); - magic_eval(dumb_ptr(&magic_default_env), &magic_conf.varv[var_id].val, $3); - } - $1.delete_(); -} - -| CONST ID '=' expr -{ - val_t var; - magic_eval(dumb_ptr(&magic_default_env), &var, $4); - bind_constant($2.str(), &var, @1.first_line); - $2.delete_(); -} - -| TELEPORT_ANCHOR ID ':' expr '=' expr -{ - auto anchor = dumb_ptr::make(); - anchor->name = $2.str(); - $2.delete_(); - anchor->invocation = magic_eval_str(dumb_ptr(&magic_default_env), $4); - anchor->location = $6; - - if (!failed_flag) - add_teleport_anchor(anchor, @1.first_line); - else - anchor.delete_(); - failed_flag = 0; -} - -| PROCEDURE ID '(' proc_formals_list ')' '=' effect_list -{ - dumb_ptr proc = $4; - proc->name = $2.str(); - $2.delete_(); - proc->body = $7; - if (!failed_flag) - install_proc(proc); - proc.delete_(); - failed_flag = 0; -} - -| spell_flags SPELL ID argopt ':' expr '=' spelldef -{ - dumb_ptr spell = $8; - spell->name = $3.str(); - $3.delete_(); - spell->invocation = magic_eval_str(dumb_ptr(&magic_default_env), $6); - spell->arg = $4.id; - spell->spellarg_ty = $4.ty; - spell->flags = $1; - if (!failed_flag) - add_spell(spell, @1.first_line); - failed_flag = 0; -} - -; - - -spell_flags - -: /* empty */ -{ - $$ = SPELL_FLAG::ZERO; -} - -| LOCAL spell_flags -{ - if (bool($2 & SPELL_FLAG::LOCAL)) - fail(@1.first_line, @1.first_column, "`LOCAL' specified more than once"); - $$ = $2 | SPELL_FLAG::LOCAL; -} - -| NONMAGIC spell_flags -{ - if (bool($2 & SPELL_FLAG::NONMAGIC)) - fail(@1.first_line, @1.first_column, "`NONMAGIC' specified more than once"); - $$ = $2 | SPELL_FLAG::NONMAGIC; -} - -| SILENT spell_flags -{ - if (bool($2 & SPELL_FLAG::SILENT)) - fail(@1.first_line, @1.first_column, "`SILENT' specified more than once"); - $$ = $2 | SPELL_FLAG::SILENT; -} - -; - - -argopt - -: /* empty */ -{ - $$.ty = SPELLARG::NONE; -} - -| '(' ID ':' arg_ty ')' -{ - $$.id = intern_id($2); - $2.delete_(); - $$.ty = $4; -} - -; - - -arg_ty - -: PC_F -{ - $$ = SPELLARG::PC; -} - -| STRING_TY -{ - $$ = SPELLARG::STRING; -} - -; - - -value - -: DIR -{ - $$.ty = TYPE::DIR; - $$.v.v_int = $1; -} - -| INT -{ - $$.ty = TYPE::INT; - $$.v.v_int = $1; -} - -| STRING -{ - $$.ty = TYPE::STRING; - $$.v.v_string = $1; -} - -; - - -expr - -: value -{ - $$ = magic_new_expr(EXPR::VAL); - $$->e.e_val = $1; -} - -| ID -{ - val_t *val = find_constant($1.str()); - if (val) - { - $$ = magic_new_expr(EXPR::VAL); - $$->e.e_val = *val; - } - else - { - $$ = magic_new_expr(EXPR::ID); - $$->e.e_id = intern_id($1); - } - $1.delete_(); -} - -| area -{ - $$ = magic_new_expr(EXPR::AREA); - $$->e.e_area = $1; -} - -| expr '+' expr -{ - BIN_EXPR($$, "+", $1, $3, @1.first_line, @1.first_column); -} - -| expr '-' expr -{ - BIN_EXPR($$, "-", $1, $3, @1.first_line, @1.first_column); -} - -| expr '*' expr -{ - BIN_EXPR($$, "*", $1, $3, @1.first_line, @1.first_column); -} - -| expr '%' expr -{ - BIN_EXPR($$, "%", $1, $3, @1.first_line, @1.first_column); -} - -| expr '/' expr -{ - BIN_EXPR($$, "/", $1, $3, @1.first_line, @1.first_column); -} - -| expr '<' expr -{ - BIN_EXPR($$, ">", $3, $1, @1.first_line, @1.first_column); -} - -| expr '>' expr -{ - BIN_EXPR($$, ">", $1, $3, @1.first_line, @1.first_column); -} - -| expr '&' expr -{ - BIN_EXPR($$, "&", $1, $3, @1.first_line, @1.first_column); -} - -| expr '^' expr -{ - BIN_EXPR($$, "^", $1, $3, @1.first_line, @1.first_column); -} - -| expr '|' expr -{ - BIN_EXPR($$, "|", $1, $3, @1.first_line, @1.first_column); -} - -| expr SHL expr -{ - BIN_EXPR($$, "<<", $1, $3, @1.first_line, @1.first_column); -} - -| expr SHR expr -{ - BIN_EXPR($$, ">>", $1, $3, @1.first_line, @1.first_column); -} - -| expr LTE expr -{ - BIN_EXPR($$, ">=", $3, $1, @1.first_line, @1.first_column); -} - -| expr GTE expr -{ - BIN_EXPR($$, ">=", $1, $3, @1.first_line, @1.first_column); -} - -| expr ANDAND expr -{ - BIN_EXPR($$, "&&", $1, $3, @1.first_line, @1.first_column); -} - -| expr OROR expr -{ - BIN_EXPR($$, "||", $1, $3, @1.first_line, @1.first_column); -} - -| expr EQ expr -{ - BIN_EXPR($$, "=", $1, $3, @1.first_line, @1.first_column); -} - -| expr '=' expr -{ - BIN_EXPR($$, "=", $1, $3, @1.first_line, @1.first_column); -} - -| expr NEQ expr -{ - BIN_EXPR($$, "=", $1, $3, @1.first_line, @1.first_column); - $$ = fun_expr("not", const_array>(&$$, 1), @1.first_line, @1.first_column); -} - -| ID '(' arg_list ')' -{ - $$ = fun_expr($1.str(), *$3.argvp, @1.first_line, @1.first_column); - $3.argvp.delete_(); - $1.delete_(); // allocated from m-i-lexer.lpp -} - -| '(' expr ')' -{ - $$ = $2; -} - -| expr '.' ID -{ - $$ = dot_expr($1, intern_id($3)); - $3.delete_(); -} - -; - - -arg_list - -: /* empty */ -{ - $$.argvp.new_(); -} - -| arg_list_ne -{ - $$ = $1; -} - -; - - -arg_list_ne - -: expr -{ - $$.argvp.new_(); - $$.argvp->push_back($1); -} - -| arg_list_ne ',' expr -{ - // yikes! Fate is officially banned from ever touching my code again. - $$ = $1; - $$.argvp->push_back($3); -} - -; - - -location - -: '@' '(' expr ',' expr ',' expr ')' -{ - $$.m = $3; - $$.x = $5; - $$.y = $7; -} - -; - - -area - -: location -{ - $$.ty = AREA::LOCATION; - $$.a.a_loc = $1; -} - -| location '@' '+' '(' expr ',' expr ')' -{ - $$.ty = AREA::RECT; - $$.a.a_rect.loc = $1; - $$.a.a_rect.width = $5; - $$.a.a_rect.height = $7; -} - -| location TOWARDS expr ':' '(' expr ',' expr ')' -{ - $$.ty = AREA::BAR; - $$.a.a_bar.loc = $1; - $$.a.a_bar.width = $6; - $$.a.a_bar.depth = $8; - $$.a.a_bar.dir = $3; -} - -; - - -spelldef - -: spellbody_list -{ - $$ = new_spell($1); -} - -| LET defs IN spellbody_list -{ - $$ = new_spell($4); - $$->letdefv = std::move(*$2); - $2.delete_(); - $$->spellguard = $4; -} - -; - - -defs - -: semicolons -{ - $$.new_(); -} - -| defs def semicolons -{ - $$ = $1; - $$->push_back($2); -} - -; - - -def - -: ID '=' expr -{ - if (find_constant($1.str())) - { - fail(@1.first_line, @1.first_column, "Attempt to re-define constant `%s' as LET-bound variable.\n", $1.c_str()); - } - else - { - $$.id = intern_id($1); - $$.expr = $3; - } - $1.delete_(); -} - -; - - -spellbody_list - -: spellbody -{ - $$ = $1; -} - -| spellbody '|' spellbody_list -{ - dumb_ptr sg = new_spellguard(SPELLGUARD::CHOICE); - sg->next = $1; - sg->s.s_alt = $3; - $$ = sg; -} - -; - - -spellbody - -: spellguard DARROW spellbody -{ - $$ = spellguard_implication($1, $3); -} - -| '(' spellbody_list ')' -{ - $$ = $2; -} - -| EFFECT_ effect_list maybe_trigger maybe_end -{ - dumb_ptr sg = new_spellguard(SPELLGUARD::EFFECT); - sg->s.s_effect.effect = $2; - sg->s.s_effect.at_trigger = $3; - sg->s.s_effect.at_end = $4; - $$ = sg; -} - -; - - -maybe_trigger - -: /* empty */ -{ - $$ = NULL; -} - -| ATTRIGGER effect_list -{ - $$ = $2; -} - -; - - -maybe_end - -: /* empty */ -{ - $$ = NULL; -} - -| ATEND effect_list -{ - $$ = $2; -} - -; - - -spellguard - -: prereq -{ - $$ = $1; -} - -| spellguard OR spellguard -{ - dumb_ptr sg = new_spellguard(SPELLGUARD::CHOICE); - sg->next = $1; - sg->s.s_alt = $3; - $$ = sg; -} - -| '(' spellguard_list ')' -{ - $$ = $2; -} - -; - - -spellguard_list - -: spellguard -{ - $$ = $1; -} - -| spellguard ',' spellguard_list -{ - $$ = spellguard_implication($1, $3); -} - -; - - -prereq - -: REQUIRE expr -{ - $$ = new_spellguard(SPELLGUARD::CONDITION); - $$->s.s_condition = $2; -} - -| CATALYSTS items -{ - $$ = new_spellguard(SPELLGUARD::CATALYSTS); - $$->s.s_catalysts = $2; -} - -| COMPONENTS items -{ - $$ = new_spellguard(SPELLGUARD::COMPONENTS); - $$->s.s_components = $2; -} - -| MANA expr -{ - $$ = new_spellguard(SPELLGUARD::MANA); - $$->s.s_mana = $2; -} - -| CASTTIME expr -{ - $$ = new_spellguard(SPELLGUARD::CASTTIME); - $$->s.s_casttime = $2; -} - -; - - -items - -: '[' item_list ']' -{ - $$ = $2; -} - -; - - -item_list - -: item -{ - $$ = NULL; - magic_add_component(&$$, $1.id, $1.count); -} - -| item_list ',' item -{ - $$ = $1; - magic_add_component(&$$, $3.id, $3.count); -} - -; - - -item - -: INT '*' item_name -{ - $$.id = $3; - $$.count = $1; -} - -| item_name -{ - $$.id = $1; - $$.count = 1; -} - -; - - -item_name - -: STRING -{ - struct item_data *item = itemdb_searchname(stringish(ZString($1))); - if (!item) - { - fail(@1.first_line, @1.first_column, "Unknown item `%s'\n", $1.c_str()); - $$ = 0; - } - else - $$ = item->nameid; - $1.delete_(); -} - -| INT -{ - $$ = $1; -} - -; - - -selection - -: PC_F -{ - $$ = FOREACH_FILTER::PC; -} - -| MOB_F -{ - $$ = FOREACH_FILTER::MOB; -} - -| ENTITY_F -{ - $$ = FOREACH_FILTER::ENTITY; -} - -| SPELL -{ - $$ = FOREACH_FILTER::SPELL; -} - -| TARGET_F -{ - $$ = FOREACH_FILTER::TARGET; -} - -| NPC_F -{ - $$ = FOREACH_FILTER::NPC; -} - -; - - -effect - -: '(' effect_list ')' -{ - $$ = $2; -} - -| SKIP ';' -{ - $$ = new_effect(EFFECT::SKIP); -} - -| ABORT ';' -{ - $$ = new_effect(EFFECT::ABORT); -} - -| END ';' -{ - $$ = new_effect(EFFECT::END); -} - -| BREAK ';' -{ - $$ = new_effect(EFFECT::BREAK); -} - -| ID '=' expr ';' -{ - if (find_constant($1.str())) - { - fail(@1.first_line, @1.first_column, "Attempt to re-define constant `%s' in assignment.", $1.c_str()); - } - else - { - $$ = new_effect(EFFECT::ASSIGN); - $$->e.e_assign.id = intern_id($1); - $$->e.e_assign.expr = $3; - } - $1.delete_(); -} - -| FOREACH selection ID IN expr DO effect -{ - $$ = new_effect(EFFECT::FOREACH); - $$->e.e_foreach.id = intern_id($3); - $3.delete_(); - $$->e.e_foreach.area = $5; - $$->e.e_foreach.body = $7; - $$->e.e_foreach.filter = $2; -} - -| FOR ID '=' expr TO expr DO effect -{ - $$ = new_effect(EFFECT::FOR); - $$->e.e_for.id = intern_id($2); - $2.delete_(); - $$->e.e_for.start = $4; - $$->e.e_for.stop = $6; - $$->e.e_for.body = $8; -} - -| IF expr THEN effect ELSE effect -{ - $$ = new_effect(EFFECT::IF); - $$->e.e_if.cond = $2; - $$->e.e_if.true_branch = $4; - $$->e.e_if.false_branch = $6; -} - -| IF expr THEN effect -{ - $$ = new_effect(EFFECT::IF); - $$->e.e_if.cond = $2; - $$->e.e_if.true_branch = $4; - $$->e.e_if.false_branch = new_effect(EFFECT::SKIP); -} - -| SLEEP expr ';' -{ - $$ = new_effect(EFFECT::SLEEP); - $$->e.e_sleep = $2; -} - -| ID '(' arg_list ')' ';' -{ - $$ = op_effect($1.str(), *$3.argvp, @1.first_line, @1.first_column); - $1.delete_(); -} - -| SCRIPT_DATA -{ - $$ = new_effect(EFFECT::SCRIPT); - $$->e.e_script = dumb_ptr(parse_script(ZString($1), @1.first_line).release()); - $1.delete_(); - if ($$->e.e_script == NULL) - fail(@1.first_line, @1.first_column, "Failed to compile script\n"); -} - -| CALL ID '(' arg_list ')' ';' -{ - $$ = call_proc($2, $4.argvp, @1.first_line, @1.first_column); - $2.delete_(); -} - -; - - -effect_list - -: /* empty */ -{ - $$ = new_effect(EFFECT::SKIP); -} - -| effect semicolons effect_list -{ - $$ = set_effect_continuation($1, $3); -} - -; - - -%% - -size_t intern_id(ZString id_name) -{ - size_t i; - for (i = 0; i < magic_conf.varv.size(); i++) - if (id_name == magic_conf.varv[i].name) - return i; - - // i = magic_conf.varv.size(); - /* Must add new */ - magic_conf_t::mcvar new_var {}; - new_var.name = id_name; - new_var.val.ty = TYPE::UNDEF; - magic_conf.varv.push_back(new_var); - - return i; -} - -void add_spell(dumb_ptr spell, int line_nr) -{ - auto pair1 = magic_conf.spells_by_name.insert({spell->name, spell}); - if (!pair1.second) - { - fail(line_nr, 0, "Attempt to redefine spell `%s'\n", spell->name.c_str()); - return; - } - - auto pair2 = magic_conf.spells_by_invocation.insert({spell->invocation, spell}); - if (!pair2.second) - { - fail(line_nr, 0, "Attempt to redefine spell invocation `%s' between spells `%s' and `%s'\n", - spell->invocation.c_str(), pair1.first->second->name.c_str(), spell->name.c_str()); - magic_conf.spells_by_name.erase(pair1.first); - return; - } -} - -void add_teleport_anchor(dumb_ptr anchor, int line_nr) -{ - auto pair1 = magic_conf.anchors_by_name.insert({anchor->name, anchor}); - if (!pair1.second) - { - fail(line_nr, 0, "Attempt to redefine teleport anchor `%s'\n", anchor->name.c_str()); - return; - } - - auto pair2 = magic_conf.anchors_by_invocation.insert({anchor->name, anchor}); - if (!pair2.second) - { - fail(line_nr, 0, "Attempt to redefine anchor invocation `%s' between anchors `%s' and `%s'\n", - anchor->invocation.c_str(), pair1.first->second->name.c_str(), anchor->name.c_str()); - magic_conf.anchors_by_name.erase(pair1.first); - return; - } -} - - -void fail(int line, int column, const char *fmt, ...) -{ - va_list ap; - FPRINTF(stderr, "[magic-init] L%d:%d: ", line, column); - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - failed_flag = 1; -} - -dumb_ptr dot_expr(dumb_ptr expr, int id) -{ - dumb_ptr retval = magic_new_expr(EXPR::SPELLFIELD); - retval->e.e_field.id = id; - retval->e.e_field.expr = expr; - - return retval; -} - -dumb_ptr fun_expr(AString name, const_array> argv, int line, int column) -{ - dumb_ptr expr; - fun_t *fun = magic_get_fun(name); - - if (!fun) - fail(line, column, "Unknown function `%s'\n", name.c_str()); - else if (fun->signature.size() != argv.size()) - { - fail(line, column, "Incorrect number of arguments to function `%s': Expected %zu, found %zu\n", - name.c_str(), fun->signature.size(), argv.size()); - fun = NULL; - } - - if (fun) - { - expr = magic_new_expr(EXPR::FUNAPP); - expr->e.e_funapp.line_nr = line; - expr->e.e_funapp.column = column; - expr->e.e_funapp.funp = fun; - - assert (argv.size() <= MAX_ARGS); - expr->e.e_funapp.args_nr = argv.size(); - - std::copy(argv.begin(), argv.end(), expr->e.e_funapp.args); - } - else - { - /* failure */ - expr = magic_new_expr(EXPR::VAL); - expr->e.e_val.ty = TYPE::FAIL; - } - - return expr; -} - -dumb_ptr new_spell(dumb_ptr guard) -{ - auto retval = dumb_ptr::make(); - retval->spellguard = guard; - return retval; -} - -dumb_ptr new_spellguard(SPELLGUARD ty) -{ - dumb_ptr retval = dumb_ptr::make(); - retval->ty = ty; - return retval; -} - -dumb_ptr spellguard_implication(dumb_ptr a, dumb_ptr b) -{ - dumb_ptr retval = a; - - if (a == b) - { - /* This can happen due to reference sharing: - * e.g., - * (R0 -> (R1 | R2)) => (R3) - * yields - * (R0 -> (R1 -> R3 | R2 -> R3)) - * - * So if we now add => R4 to that, we want - * (R0 -> (R1 -> R3 -> R4 | R2 -> R3 -> R4)) - * - * but we only need to add it once, because the R3 reference is shared. - */ - return retval; - } - - /* If the premise is a disjunction, b is the continuation of _all_ branches */ - if (a->ty == SPELLGUARD::CHOICE) - spellguard_implication(a->s.s_alt, b); - if (a->next) - spellguard_implication(a->next, b); - else - a->next = b; - - return retval; -} - -dumb_ptr new_effect(EFFECT ty) -{ - auto effect = dumb_ptr::make(); - effect->ty = ty; - return effect; -} - -dumb_ptr set_effect_continuation(dumb_ptr src, dumb_ptr continuation) -{ - dumb_ptr retval = src; - /* This function is completely analogous to `spellguard_implication' above; read the control flow implications above first before pondering it. */ - - if (src == continuation) - return retval; - - /* For FOR and FOREACH, we use special stack handlers and thus don't have to set - * the continuation. It's only IF that we need to handle in this fashion. */ - if (src->ty == EFFECT::IF) - { - set_effect_continuation(src->e.e_if.true_branch, continuation); - set_effect_continuation(src->e.e_if.false_branch, continuation); - } - if (src->next) - set_effect_continuation(src->next, continuation); - else - src->next = continuation; - - return retval; -} - -dumb_ptr op_effect(AString name, const_array> argv, int line, int column) -{ - dumb_ptr effect; - op_t *op = magic_get_op(name); - - if (!op) - fail(line, column, "Unknown operation `%s'\n", name.c_str()); - else if (op->signature.size() != argv.size()) - { - fail(line, column, "Incorrect number of arguments to operation `%s': Expected %zu, found %zu\n", - name.c_str(), op->signature.size(), argv.size()); - op = NULL; - } - - if (op) - { - effect = new_effect(EFFECT::OP); - effect->e.e_op.line_nr = line; - effect->e.e_op.column = column; - effect->e.e_op.opp = op; - assert (argv.size() <= MAX_ARGS); - effect->e.e_op.args_nr = argv.size(); - - std::copy(argv.begin(), argv.end(), effect->e.e_op.args); - } - else /* failure */ - effect = new_effect(EFFECT::SKIP); - - return effect; -} - - -std::map procs; - -// I think this was a memory leak (or undefined behavior) -void install_proc(dumb_ptr proc) -{ - procs.insert({proc->name, std::move(*proc)}); -} - -dumb_ptr call_proc(ZString name, dumb_ptr>> argvp, int line_nr, int column) -{ - auto pi = procs.find(name); - if (pi == procs.end()) - { - fail(line_nr, column, "Unknown procedure `%s'\n", name.c_str()); - return new_effect(EFFECT::SKIP); - } - - proc_t *p = &pi->second; - - if (p->argv.size() != argvp->size()) - { - fail(line_nr, column, "Procedure %s/%zu invoked with %zu parameters\n", - name.c_str(), p->argv.size(), argvp->size()); - return new_effect(EFFECT::SKIP); - } - - dumb_ptr retval = new_effect(EFFECT::CALL); - retval->e.e_call.body = p->body; - retval->e.e_call.formalv = &p->argv; - retval->e.e_call.actualvp = argvp; - return retval; -} - -std::map const_defm; - -void bind_constant(RString name, val_t *val, int line_nr) -{ - if (!const_defm.insert({name, *val}).second) - { - fail(line_nr, 0, "Redefinition of constant `%s'\n", name.c_str()); - } -} - -val_t *find_constant(RString name) -{ - auto it = const_defm.find(name); - if (it != const_defm.end()) - return &it->second; - - return NULL; -} - - -static -int error_flag; - -inline -void INTERN_ASSERT(ZString name, int id) -{ - int zid = intern_id(name); - if (zid != id) - { - FPRINTF(stderr, - "[magic-conf] INTERNAL ERROR: Builtin special var %s interned to %d, not %d as it should be!\n", - name, zid, id); - error_flag = 1; - } -} - -extern FILE *magic_frontend_in; - -bool magic_init0() -{ - error_flag = 0; - - INTERN_ASSERT("min_casttime", VAR_MIN_CASTTIME); - INTERN_ASSERT("obscure_chance", VAR_OBSCURE_CHANCE); - INTERN_ASSERT("caster", VAR_CASTER); - INTERN_ASSERT("spellpower", VAR_SPELLPOWER); - INTERN_ASSERT("self_spell", VAR_SPELL); - INTERN_ASSERT("self_invocation", VAR_INVOCATION); - INTERN_ASSERT("target", VAR_TARGET); - INTERN_ASSERT("script_target", VAR_SCRIPTTARGET); - INTERN_ASSERT("location", VAR_LOCATION); - - return !error_flag; -} - -// must be called after itemdb initialisation -bool magic_init1(ZString conffile) -{ - current_magic_filename = conffile; - magic_frontend_in = fopen(conffile.c_str(), "r"); - if (!magic_frontend_in) - { - FPRINTF(stderr, "[magic-conf] Magic configuration file `%s' not found -> no magic.\n", conffile); - return false; - } - magic_frontend_parse(); - - PRINTF("[magic-conf] Magic initialised. %zu spells, %zu teleport anchors.\n", - magic_conf.spells_by_name.size(), magic_conf.anchors_by_name.size()); - - return !error_flag; -} - -extern int magic_frontend_lineno; - -void magic_frontend_error(const char *msg) -{ - FPRINTF(stderr, "[magic-conf] Parse error: %s at line %d\n", msg, magic_frontend_lineno); - failed_flag = 1; -} diff --git a/src/map/magic-interpreter.cpp b/src/map/magic-interpreter.cpp new file mode 100644 index 0000000..526d549 --- /dev/null +++ b/src/map/magic-interpreter.cpp @@ -0,0 +1,3 @@ +#include "magic-interpreter.hpp" + +#include "../poison.hpp" diff --git a/src/map/magic-interpreter.hpp b/src/map/magic-interpreter.hpp index 6864844..c6abb81 100644 --- a/src/map/magic-interpreter.hpp +++ b/src/map/magic-interpreter.hpp @@ -445,9 +445,6 @@ struct proc_t {} }; -bool magic_init0(); -// must be called after itemdb initialisation -bool magic_init1(ZString filename); void spell_update_location(dumb_ptr invocation); #endif // TMWA_MAP_MAGIC_INTERPRETER_HPP diff --git a/src/map/magic-interpreter.py b/src/map/magic-interpreter.py new file mode 100644 index 0000000..8170f27 --- /dev/null +++ b/src/map/magic-interpreter.py @@ -0,0 +1,224 @@ +class area_t(object): + ''' print an area_t + ''' + __slots__ = ('_value') + name = 'area_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + yield 'size', v['size'] + ty = v['ty'] + yield 'ty', ty + a = v['a'] + if ty == 0: + yield 'a.a_loc', a['a_loc'] + elif ty == 1: + yield 'a.a_union', a['a_union'] + elif ty == 2: + yield 'a.a_rect', a['a_rect'] + elif ty == 3: + yield 'a.a_bar', a['a_bar'] + + +class val_t(object): + ''' print a val_t + ''' + __slots__ = ('_value') + name = 'val_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + ty = v['ty'] + yield 'ty', ty + u = v['v'] + if ty == 1: + yield 'v.v_int', u['v_int'] + elif ty == 2: + yield 'v.v_dir', u['v_dir'] + elif ty == 3: + yield 'v.v_string', u['v_string'] + elif ty == 4: + yield 'v.v_int', u['v_int'] + yield 'v.v_entity', u['v_entity'] + elif ty == 5: + yield 'v.v_location', u['v_location'] + elif ty == 6: + yield 'v.v_area', u['v_area'] + elif ty == 7: + yield 'v.v_spell', u['v_spell'] + elif ty == 8: + yield 'v.v_int', u['v_int'] + yield 'v.v_invocation', u['v_invocation'] + + +class e_area_t(object): + ''' print an e_area_t + ''' + __slots__ = ('_value') + name = 'e_area_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + ty = v['ty'] + yield 'ty', ty + a = v['a'] + if ty == 0: + yield 'a.a_loc', a['a_loc'] + elif ty == 1: + yield 'a.a_union', a['a_union'] + elif ty == 2: + yield 'a.a_rect', a['a_rect'] + elif ty == 3: + yield 'a.a_bar', a['a_bar'] + + +class expr_t(object): + ''' print an expr_t + ''' + __slots__ = ('_value') + name = 'expr_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + ty = v['ty'] + yield 'ty', ty + u = v['e'] + if ty == 0: + yield 'e.e_val', u['e_val'] + elif ty == 1: + yield 'e.e_location', u['e_location'] + elif ty == 2: + yield 'e.e_area', u['e_area'] + elif ty == 3: + yield 'e.e_funapp', u['e_funapp'] + elif ty == 4: + yield 'e.e_id', u['e_id'] + elif ty == 5: + yield 'e.e_field', u['e_field'] + + +class effect_t(object): + ''' print an effect_t + ''' + __slots__ = ('_value') + name = 'effect_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + yield 'next', v['next'] + ty = v['ty'] + yield 'ty', ty + u = v['e'] + if ty == 2: + yield 'e.e_assign', u['e_assign'] + elif ty == 3: + yield 'e.e_foreach', u['e_foreach'] + elif ty == 4: + yield 'e.e_for', u['e_for'] + elif ty == 5: + yield 'e.e_if', u['e_if'] + elif ty == 6: + yield 'e.e_sleep', u['e_sleep'] + elif ty == 7: + yield 'e.e_script', u['e_script'] + elif ty == 9: + yield 'e.e_op', u['e_op'] + elif ty == 11: + yield 'e.e_call', u['e_call'] + + +class spellguard_t(object): + ''' print a spellguard_t + ''' + __slots__ = ('_value') + name = 'spellguard_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + yield 'next', v['next'] + ty = v['ty'] + yield 'ty', ty + u = v['s'] + if ty == 0: + yield 's.s_condition', u['s_condition'] + elif ty == 1: + yield 's.s_components', u['s_components'] + elif ty == 2: + yield 's.s_catalysts', u['s_catalysts'] + elif ty == 3: + yield 's.s_alt', u['s_alt'] + elif ty == 4: + yield 's.s_mana', u['s_mana'] + elif ty == 5: + yield 's.s_casttime', u['s_casttime'] + elif ty == 6: + yield 's.s_effect', u['s_effect'] + + +class cont_activation_record_t(object): + ''' print a cont_activation_record_t + ''' + __slots__ = ('_value') + name = 'cont_activation_record_t' + enabled = True + + def __init__(self, value): + self._value = value + + def to_string(self): + return None + + def children(self): + v = self._value + yield 'return_location', v['return_location'] + ty = v['ty'] + yield 'ty', ty + u = v['c'] + if ty == 0: + yield 'c.c_foreach', u['c_foreach'] + elif ty == 1: + yield 'c.c_for', u['c_for'] + elif ty == 2: + yield 'c.c_proc', u['c_proc'] diff --git a/src/map/magic-v2.cpp b/src/map/magic-v2.cpp new file mode 100644 index 0000000..b10df3f --- /dev/null +++ b/src/map/magic-v2.cpp @@ -0,0 +1,1245 @@ +#include "magic-v2.hpp" +// magic-v2.cpp - second generation magic parser +// +// Copyright © 2014 Ben Longbons +// +// This file is part of The Mana World (Athena server) +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +#include + +#include "../sexpr/parser.hpp" + +#include "../mmo/dumb_ptr.hpp" + +#include "itemdb.hpp" +#include "magic-expr.hpp" + +#include "../poison.hpp" + +namespace magic_v2 +{ + static + std::map procs; + static + std::map const_defm; + + static + size_t intern_id(ZString id_name) + { + // TODO use InternPool + size_t i; + for (i = 0; i < magic_conf.varv.size(); i++) + if (id_name == magic_conf.varv[i].name) + return i; + + // i = magic_conf.varv.size(); + /* Must add new */ + magic_conf_t::mcvar new_var {}; + new_var.name = id_name; + new_var.val.ty = TYPE::UNDEF; + magic_conf.varv.push_back(new_var); + + return i; + } + inline + bool INTERN_ASSERT(ZString name, int id) + { + int zid = intern_id(name); + if (zid != id) + { + FPRINTF(stderr, + "[magic-conf] INTERNAL ERROR: Builtin special var %s interned to %d, not %d as it should be!\n", + name, zid, id); + } + return zid == id; + } + + static + bool init0() + { + bool ok = true; + + ok &= INTERN_ASSERT("min_casttime", VAR_MIN_CASTTIME); + ok &= INTERN_ASSERT("obscure_chance", VAR_OBSCURE_CHANCE); + ok &= INTERN_ASSERT("caster", VAR_CASTER); + ok &= INTERN_ASSERT("spellpower", VAR_SPELLPOWER); + ok &= INTERN_ASSERT("self_spell", VAR_SPELL); + ok &= INTERN_ASSERT("self_invocation", VAR_INVOCATION); + ok &= INTERN_ASSERT("target", VAR_TARGET); + ok &= INTERN_ASSERT("script_target", VAR_SCRIPTTARGET); + ok &= INTERN_ASSERT("location", VAR_LOCATION); + + return ok; + } + + + static + bool bind_constant(io::LineSpan span, RString name, val_t *val) + { + if (!const_defm.insert({name, *val}).second) + { + span.error(STRPRINTF("Redefinition of constant '%s'", name)); + return false; + } + return true; + } + static + val_t *find_constant(RString name) + { + auto it = const_defm.find(name); + if (it != const_defm.end()) + return &it->second; + + return NULL; + } + static + dumb_ptr new_effect(EFFECT ty) + { + auto effect = dumb_ptr::make(); + effect->ty = ty; + return effect; + } + static + dumb_ptr set_effect_continuation(dumb_ptr src, dumb_ptr continuation) + { + dumb_ptr retval = src; + /* This function is completely analogous to `spellguard_implication' above; read the control flow implications above first before pondering it. */ + + if (src == continuation) + return retval; + + /* For FOR and FOREACH, we use special stack handlers and thus don't have to set + * the continuation. It's only IF that we need to handle in this fashion. */ + if (src->ty == EFFECT::IF) + { + set_effect_continuation(src->e.e_if.true_branch, continuation); + set_effect_continuation(src->e.e_if.false_branch, continuation); + } + + if (src->next) + set_effect_continuation(src->next, continuation); + else + src->next = continuation; + + return retval; + } + static + dumb_ptr new_spellguard(SPELLGUARD ty) + { + dumb_ptr retval = dumb_ptr::make(); + retval->ty = ty; + return retval; + } + static + dumb_ptr spellguard_implication(dumb_ptr a, dumb_ptr b) + { + dumb_ptr retval = a; + + if (a == b) + { + /* This can happen due to reference sharing: + * e.g., + * (R0 -> (R1 | R2)) => (R3) + * yields + * (R0 -> (R1 -> R3 | R2 -> R3)) + * + * So if we now add => R4 to that, we want + * (R0 -> (R1 -> R3 -> R4 | R2 -> R3 -> R4)) + * + * but we only need to add it once, because the R3 reference is shared. + */ + return retval; + } + + /* If the premise is a disjunction, b is the continuation of _all_ branches */ + if (a->ty == SPELLGUARD::CHOICE) + spellguard_implication(a->s.s_alt, b); + + if (a->next) + spellguard_implication(a->next, b); + else + // this is the important bit + a->next = b; + + return retval; + } + + + static + bool add_spell(io::LineSpan span, dumb_ptr spell) + { + auto pair1 = magic_conf.spells_by_name.insert({spell->name, spell}); + if (!pair1.second) + { + span.error(STRPRINTF("Attempt to redefine spell '%s'", spell->name)); + return false; + } + + auto pair2 = magic_conf.spells_by_invocation.insert({spell->invocation, spell}); + if (!pair2.second) + { + span.error(STRPRINTF("Attempt to redefine spell invocation '%s'", spell->invocation)); + magic_conf.spells_by_name.erase(pair1.first); + return false; + } + return true; + } + static + bool add_teleport_anchor(io::LineSpan span, dumb_ptr anchor) + { + auto pair1 = magic_conf.anchors_by_name.insert({anchor->name, anchor}); + if (!pair1.second) + { + span.error(STRPRINTF("Attempt to redefine teleport anchor '%s'", anchor->name)); + return false; + } + + auto pair2 = magic_conf.anchors_by_invocation.insert({anchor->name, anchor}); + if (!pair2.second) + { + span.error(STRPRINTF("Attempt to redefine anchor invocation '%s'", anchor->invocation)); + magic_conf.anchors_by_name.erase(pair1.first); + return false; + } + return true; + } + + static + bool install_proc(io::LineSpan span, dumb_ptr proc) + { + RString name = proc->name; + if (!procs.insert({name, std::move(*proc)}).second) + { + span.error("procedure already exists"); + return false; + } + return true; + } + static + bool call_proc(io::LineSpan span, ZString name, dumb_ptr>> argvp, dumb_ptr& retval) + { + auto pi = procs.find(name); + if (pi == procs.end()) + { + span.error(STRPRINTF("Unknown procedure '%s'", name)); + return false; + } + + proc_t *p = &pi->second; + + if (p->argv.size() != argvp->size()) + { + span.error(STRPRINTF("Procedure %s/%zu invoked with %zu parameters", + name, p->argv.size(), argvp->size())); + return false; + } + + retval = new_effect(EFFECT::CALL); + retval->e.e_call.body = p->body; + retval->e.e_call.formalv = &p->argv; + retval->e.e_call.actualvp = argvp; + return true; + } + static + bool op_effect(io::LineSpan span, ZString name, const_array> argv, dumb_ptr& effect) + { + op_t *op = magic_get_op(name); + if (!op) + { + span.error(STRPRINTF("Unknown operation '%s'", name)); + return false; + } + if (op->signature.size() != argv.size()) + { + span.error(STRPRINTF("Incorrect number of arguments to operation '%s': Expected %zu, found %zu", + name, op->signature.size(), argv.size())); + return false; + } + + effect = new_effect(EFFECT::OP); + effect->e.e_op.line_nr = span.begin.line; + effect->e.e_op.column = span.begin.column; + effect->e.e_op.opp = op; + assert (argv.size() <= MAX_ARGS); + effect->e.e_op.args_nr = argv.size(); + + std::copy(argv.begin(), argv.end(), effect->e.e_op.args); + return true; + } + + static + dumb_ptr dot_expr(dumb_ptr expr, int id) + { + dumb_ptr retval = magic_new_expr(EXPR::SPELLFIELD); + retval->e.e_field.id = id; + retval->e.e_field.expr = expr; + + return retval; + } + static + bool fun_expr(io::LineSpan span, ZString name, const_array> argv, dumb_ptr& expr) + { + fun_t *fun = magic_get_fun(name); + if (!fun) + { + span.error(STRPRINTF("Unknown function '%s'", name)); + return false; + } + if (fun->signature.size() != argv.size()) + { + span.error(STRPRINTF("Incorrect number of arguments to function '%s': Expected %zu, found %zu", + name, fun->signature.size(), argv.size())); + return false; + } + expr = magic_new_expr(EXPR::FUNAPP); + expr->e.e_funapp.line_nr = span.begin.line; + expr->e.e_funapp.column = span.begin.column; + expr->e.e_funapp.funp = fun; + + assert (argv.size() <= MAX_ARGS); + expr->e.e_funapp.args_nr = argv.size(); + + std::copy(argv.begin(), argv.end(), expr->e.e_funapp.args); + return true; + } + static + dumb_ptr BIN_EXPR(io::LineSpan span, ZString name, dumb_ptr left, dumb_ptr right) + { + dumb_ptr e[2]; + e[0] = left; + e[1] = right; + dumb_ptr rv; + if (!fun_expr(span, name, const_array>(e, 2), rv)) + abort(); + return rv; + } + + static + bool fail(const sexpr::SExpr& s, ZString msg) + { + s._span.error(msg); + return false; + } +} + +namespace magic_v2 +{ + using sexpr::SExpr; + + static + bool parse_expression(const SExpr& x, dumb_ptr& out); + static + bool parse_effect(const SExpr& s, dumb_ptr& out); + static + bool parse_spellguard(const SExpr& s, dumb_ptr& out); + static + bool parse_spellbody(const SExpr& s, dumb_ptr& out); + + // Note: anything with dumb_ptr leaks memory on failure + // once this is all done, we can convert it to unique_ptr + // (may require bimaps somewhere) + static + bool is_comment(const SExpr& s) + { + if (s._type == sexpr::STRING) + return true; + if (s._type != sexpr::LIST) + return false; + if (s._list.empty()) + return false; + if (s._list[0]._type != sexpr::TOKEN) + return false; + return s._list[0]._str == "DISABLED"; + } + + static + bool parse_loc(const SExpr& s, e_location_t& loc) + { + if (s._type != sexpr::LIST) + return fail(s, "loc not list"); + if (s._list.size() != 4) + return fail(s, "loc not 3 args"); + if (s._list[0]._type != sexpr::TOKEN) + return fail(s._list[0], "loc cmd not tok"); + if (s._list[0]._str != "@") + return fail(s._list[0], "loc cmd not cmd"); + return parse_expression(s._list[1], loc.m) + && parse_expression(s._list[2], loc.x) + && parse_expression(s._list[3], loc.y); + } + + static + bool parse_expression(const SExpr& x, dumb_ptr& out) + { + switch (x._type) + { + case sexpr::INT: + { + val_t val; + val.ty = TYPE::INT; + val.v.v_int = x._int; + if (val.v.v_int != x._int) + return fail(x, "integer too large"); + + out = magic_new_expr(EXPR::VAL); + out->e.e_val = val; + return true; + } + case sexpr::STRING: + { + val_t val; + val.ty = TYPE::STRING; + val.v.v_string = dumb_string::copys(x._str); + + out = magic_new_expr(EXPR::VAL); + out->e.e_val = val; + return true; + } + case sexpr::TOKEN: + { + ZString dirs[8] = { + "S", "SW", "W", "NW", "N", "NE", "E", "SE", + }; + auto begin = std::begin(dirs); + auto end = std::end(dirs); + auto it = std::find(begin, end, x._str); + if (it != end) + { + val_t val; + val.ty = TYPE::DIR; + val.v.v_dir = static_cast(it - begin); + + out = magic_new_expr(EXPR::VAL); + out->e.e_val = val; + return true; + } + } + { + if (val_t *val = find_constant(x._str)) + { + out = magic_new_expr(EXPR::VAL); + out->e.e_val = *val; + return true; + } + else + { + out = magic_new_expr(EXPR::ID); + out->e.e_id = intern_id(x._str); + return true; + } + } + break; + case sexpr::LIST: + if (x._list.empty()) + return fail(x, "empty list"); + { + if (x._list[0]._type != sexpr::TOKEN) + return fail(x._list[0], "op not token"); + ZString op = x._list[0]._str; + // area + if (op == "@") + { + e_location_t loc; + if (!parse_loc(x, loc)) + return false; + out = magic_new_expr(EXPR::AREA); + out->e.e_area.ty = AREA::LOCATION; + out->e.e_area.a.a_loc = loc; + return true; + } + if (op == "@+") + { + e_location_t loc; + dumb_ptr width; + dumb_ptr height; + if (!parse_loc(x._list[1], loc)) + return false; + if (!parse_expression(x._list[2], width)) + return false; + if (!parse_expression(x._list[3], height)) + return false; + out = magic_new_expr(EXPR::AREA); + out->e.e_area.ty = AREA::RECT; + out->e.e_area.a.a_rect.loc = loc; + out->e.e_area.a.a_rect.width = width; + out->e.e_area.a.a_rect.height = height; + return true; + } + if (op == "TOWARDS") + { + e_location_t loc; + dumb_ptr dir; + dumb_ptr width; + dumb_ptr depth; + if (!parse_loc(x._list[1], loc)) + return false; + if (!parse_expression(x._list[2], dir)) + return false; + if (!parse_expression(x._list[3], width)) + return false; + if (!parse_expression(x._list[4], depth)) + return false; + out = magic_new_expr(EXPR::AREA); + out->e.e_area.ty = AREA::BAR; + out->e.e_area.a.a_bar.loc = loc; + out->e.e_area.a.a_bar.dir = dir; + out->e.e_area.a.a_bar.width = width; + out->e.e_area.a.a_bar.depth = depth; + return true; + } + if (op == ".") + { + if (x._list.size() != 3) + return fail(x, ". not 2"); + dumb_ptr expr; + if (!parse_expression(x._list[1], expr)) + return false; + if (x._list[2]._type != sexpr::TOKEN) + return fail(x._list[2], ".elem not name"); + ZString elem = x._list[2]._str; + out = dot_expr(expr, intern_id(elem)); + return true; + } + static + std::set ops = + { + "<", ">", "<=", ">=", "==", "!=", + "+", "-", "*", "%", "/", + "&", "^", "|", "<<", ">>", + "&&", "||", + }; + // TODO implement unary operators + if (ops.count(op)) + { + // operators are n-ary and left-associative + if (x._list.size() < 3) + return fail(x, "operator not at least 2 args"); + auto begin = x._list.begin() + 1; + auto end = x._list.end(); + if (!parse_expression(*begin, out)) + return false; + ++begin; + for (; begin != end; ++begin) + { + dumb_ptr tmp; + if (!parse_expression(*begin, tmp)) + return false; + out = BIN_EXPR(x._span, op, out, tmp); + } + return true; + } + std::vector> argv; + for (auto it = x._list.begin() + 1, end = x._list.end(); it != end; ++it) + { + dumb_ptr expr; + if (!parse_expression(*it, expr)) + return false; + argv.push_back(expr); + } + return fun_expr(x._span, op, argv, out); + } + break; + } + abort(); + } + + static + bool parse_item(const SExpr& s, int& id, int& count) + { + if (s._type == sexpr::STRING) + { + count = 1; + + item_data *item = itemdb_searchname(s._str); + if (!item) + return fail(s, "no such item"); + id = item->nameid; + return true; + } + if (s._type != sexpr::LIST) + return fail(s, "item not string or list"); + if (s._list.size() != 2) + return fail(s, "item list is not pair"); + if (s._list[0]._type != sexpr::INT) + return fail(s._list[0], "item pair first not int"); + count = s._list[0]._int; + if (s._list[1]._type != sexpr::STRING) + return fail(s._list[1], "item pair second not name"); + + item_data *item = itemdb_searchname(s._list[1]._str); + if (!item) + return fail(s, "no such item"); + id = item->nameid; + return true; + } + + static + bool parse_spellguard(const SExpr& s, dumb_ptr& out) + { + if (s._type != sexpr::LIST) + return fail(s, "not list"); + if (s._list.empty()) + return fail(s, "empty list"); + if (s._list[0]._type != sexpr::TOKEN) + return fail(s._list[0], "not token"); + ZString cmd = s._list[0]._str; + if (cmd == "OR") + { + auto begin = s._list.begin() + 1; + auto end = s._list.end(); + if (begin == end) + return fail(s, "missing arguments"); + if (!parse_spellguard(*begin, out)) + return false; + ++begin; + for (; begin != end; ++begin) + { + dumb_ptr alt; + if (!parse_spellguard(*begin, alt)) + return false; + dumb_ptr choice = new_spellguard(SPELLGUARD::CHOICE); + choice->next = out; + choice->s.s_alt = alt; + out = choice; + } + return true; + } + if (cmd == "GUARD") + { + auto begin = s._list.begin() + 1; + auto end = s._list.end(); + while (is_comment(end[-1])) + --end; + if (begin == end) + return fail(s, "missing arguments"); + if (!parse_spellguard(end[-1], out)) + return false; + --end; + for (; begin != end; --end) + { + if (is_comment(end[-1])) + continue; + dumb_ptr implier; + if (!parse_spellguard(end[-1], implier)) + return false; + out = spellguard_implication(implier, out); + } + return true; + } + if (cmd == "REQUIRE") + { + if (s._list.size() != 2) + return fail(s, "not one argument"); + dumb_ptr condition; + if (!parse_expression(s._list[1], condition)) + return false; + out = new_spellguard(SPELLGUARD::CONDITION); + out->s.s_condition = condition; + return true; + } + if (cmd == "MANA") + { + if (s._list.size() != 2) + return fail(s, "not one argument"); + dumb_ptr mana; + if (!parse_expression(s._list[1], mana)) + return false; + out = new_spellguard(SPELLGUARD::MANA); + out->s.s_mana = mana; + return true; + } + if (cmd == "CASTTIME") + { + if (s._list.size() != 2) + return fail(s, "not one argument"); + dumb_ptr casttime; + if (!parse_expression(s._list[1], casttime)) + return false; + out = new_spellguard(SPELLGUARD::CASTTIME); + out->s.s_casttime = casttime; + return true; + } + if (cmd == "CATALYSTS") + { + dumb_ptr items = nullptr; + for (auto it = s._list.begin() + 1, end = s._list.end(); it != end; ++it) + { + int id, count; + if (!parse_item(*it, id, count)) + return false; + magic_add_component(&items, id, count); + } + out = new_spellguard(SPELLGUARD::CATALYSTS); + out->s.s_catalysts = items; + return true; + } + if (cmd == "COMPONENTS") + { + dumb_ptr items = nullptr; + for (auto it = s._list.begin() + 1, end = s._list.end(); it != end; ++it) + { + int id, count; + if (!parse_item(*it, id, count)) + return false; + magic_add_component(&items, id, count); + } + out = new_spellguard(SPELLGUARD::COMPONENTS); + out->s.s_components = items; + return true; + } + return fail(s._list[0], "unknown guard"); + } + + static + bool build_effect_list(std::vector::const_iterator begin, + std::vector::const_iterator end, dumb_ptr& out) + { + // these backward lists could be forward by keeping the reference + // I know this is true because Linus said so + out = new_effect(EFFECT::SKIP); + while (end != begin) + { + const SExpr& s = *--end; + if (is_comment(s)) + continue; + dumb_ptr chain; + if (!parse_effect(s, chain)) + return false; + out = set_effect_continuation(chain, out); + } + return true; + } + + static + bool parse_effect(const SExpr& s, dumb_ptr& out) + { + if (s._type != sexpr::LIST) + return fail(s, "not list"); + if (s._list.empty()) + return fail(s, "empty list"); + if (s._list[0]._type != sexpr::TOKEN) + return fail(s._list[0], "not token"); + ZString cmd = s._list[0]._str; + if (cmd == "BLOCK") + { + return build_effect_list(s._list.begin() + 1, s._list.end(), out); + } + if (cmd == "SET") + { + if (s._list.size() != 3) + return fail(s, "not 2 args"); + if (s._list[1]._type != sexpr::TOKEN) + return fail(s._list[1], "not token"); + ZString name = s._list[1]._str; + if (find_constant(name)) + return fail(s._list[1], "assigning to constant"); + dumb_ptr expr; + if (!parse_expression(s._list[2], expr)) + return false; + + out = new_effect(EFFECT::ASSIGN); + out->e.e_assign.id = intern_id(name); + out->e.e_assign.expr = expr; + return true; + } + if (cmd == "SCRIPT") + { + if (s._list.size() != 2) + return fail(s, "not 1 arg"); + if (s._list[1]._type != sexpr::STRING) + return fail(s._list[1], "not string"); + ZString body = s._list[1]._str; + std::unique_ptr script = parse_script(body, s._list[1]._span.begin.line); + if (!script) + return fail(s._list[1], "script does not compile"); + out = new_effect(EFFECT::SCRIPT); + out->e.e_script = dumb_ptr(script.release()); + return true; + } + if (cmd == "SKIP") + { + if (s._list.size() != 1) + return fail(s, "not 0 arg"); + out = new_effect(EFFECT::SKIP); + return true; + } + if (cmd == "ABORT") + { + if (s._list.size() != 1) + return fail(s, "not 0 arg"); + out = new_effect(EFFECT::ABORT); + return true; + } + if (cmd == "END") + { + if (s._list.size() != 1) + return fail(s, "not 0 arg"); + out = new_effect(EFFECT::END); + return true; + } + if (cmd == "BREAK") + { + if (s._list.size() != 1) + return fail(s, "not 0 arg"); + out = new_effect(EFFECT::BREAK); + return true; + } + if (cmd == "FOREACH") + { + if (s._list.size() != 5) + return fail(s, "not 4 arg"); + if (s._list[1]._type != sexpr::TOKEN) + return fail(s._list[1], "foreach type not token"); + ZString type = s._list[1]._str; + FOREACH_FILTER filter; + if (type == "PC") + filter = FOREACH_FILTER::PC; + else if (type == "MOB") + filter = FOREACH_FILTER::MOB; + else if (type == "ENTITY") + filter = FOREACH_FILTER::ENTITY; + else if (type == "SPELL") + filter = FOREACH_FILTER::SPELL; + else if (type == "TARGET") + filter = FOREACH_FILTER::TARGET; + else if (type == "NPC") + filter = FOREACH_FILTER::NPC; + else + return fail(s._list[1], "unknown foreach filter"); + if (s._list[2]._type != sexpr::TOKEN) + return fail(s._list[2], "foreach var not token"); + ZString var = s._list[2]._str; + dumb_ptr area; + dumb_ptr effect; + if (!parse_expression(s._list[3], area)) + return false; + if (!parse_effect(s._list[4], effect)) + return false; + out = new_effect(EFFECT::FOREACH); + out->e.e_foreach.id = intern_id(var); + out->e.e_foreach.area = area; + out->e.e_foreach.body = effect; + out->e.e_foreach.filter = filter; + return true; + } + if (cmd == "FOR") + { + if (s._list.size() != 5) + return fail(s, "not 4 arg"); + if (s._list[1]._type != sexpr::TOKEN) + return fail(s._list[1], "for var not token"); + ZString var = s._list[1]._str; + dumb_ptr low; + dumb_ptr high; + dumb_ptr effect; + if (!parse_expression(s._list[2], low)) + return false; + if (!parse_expression(s._list[3], high)) + return false; + if (!parse_effect(s._list[4], effect)) + return false; + out = new_effect(EFFECT::FOR); + out->e.e_for.id = intern_id(var); + out->e.e_for.start = low; + out->e.e_for.stop = high; + out->e.e_for.body = effect; + return true; + } + if (cmd == "IF") + { + if (s._list.size() != 3 && s._list.size() != 4) + return fail(s, "not 2 or 3 args"); + dumb_ptr cond; + dumb_ptr if_true; + dumb_ptr if_false; + if (!parse_expression(s._list[1], cond)) + return false; + if (!parse_effect(s._list[2], if_true)) + return false; + if (s._list.size() == 4) + { + if (!parse_effect(s._list[3], if_false)) + return false; + } + else + if_false = new_effect(EFFECT::SKIP); + out = new_effect(EFFECT::IF); + out->e.e_if.cond = cond; + out->e.e_if.true_branch = if_true; + out->e.e_if.false_branch = if_false; + return true; + } + if (cmd == "WAIT") + { + if (s._list.size() != 2) + return fail(s, "not 1 arg"); + dumb_ptr expr; + if (!parse_expression(s._list[1], expr)) + return false; + out = new_effect(EFFECT::SLEEP); + out->e.e_sleep = expr; + return true; + } + if (cmd == "CALL") + { + if (s._list.size() < 2) + return fail(s, "call what?"); + if (s._list[1]._type != sexpr::TOKEN) + return fail(s._list[1], "call token please"); + ZString func = s._list[1]._str; + auto argvp = dumb_ptr>>::make(); + for (auto it = s._list.begin() + 2, end = s._list.end(); it != end; ++it) + { + dumb_ptr expr; + if (!parse_expression(*it, expr)) + return false; + argvp->push_back(expr); + } + return call_proc(s._span, func, argvp, out); + } + auto argv = std::vector>(); + for (auto it = s._list.begin() + 1, end = s._list.end(); it != end; ++it) + { + dumb_ptr expr; + if (!parse_expression(*it, expr)) + return false; + argv.push_back(expr); + } + return op_effect(s._span, cmd, argv, out); + } + + static + bool parse_spellbody(const SExpr& s, dumb_ptr& out) + { + if (s._type != sexpr::LIST) + return fail(s, "not list"); + if (s._list.empty()) + return fail(s, "empty list"); + if (s._list[0]._type != sexpr::TOKEN) + return fail(s._list[0], "not token"); + ZString cmd = s._list[0]._str; + if (cmd == "=>") + { + if (s._list.size() != 3) + return fail(s, "list does not have exactly 2 arguments"); + dumb_ptr guard; + if (!parse_spellguard(s._list[1], guard)) + return false; + dumb_ptr body; + if (!parse_spellbody(s._list[2], body)) + return false; + out = spellguard_implication(guard, body); + return true; + } + if (cmd == "|") + { + if (s._list.size() == 1) + return fail(s, "spellbody choice empty"); + auto begin = s._list.begin() + 1; + auto end = s._list.end(); + if (!parse_spellbody(*begin, out)) + return false; + ++begin; + for (; begin != end; ++begin) + { + dumb_ptr alt; + if (!parse_spellbody(*begin, alt)) + return false; + auto tmp = out; + out = new_spellguard(SPELLGUARD::CHOICE); + out->next = tmp; + out->s.s_alt = alt; + } + return true; + } + if (cmd == "EFFECT") + { + auto begin = s._list.begin() + 1; + auto end = s._list.end(); + + dumb_ptr effect, attrig, atend; + + // decreasing end can never pass begin, since we know that + // begin[-1] is token EFFECT + while (is_comment(end[-1])) + --end; + if (end[-1]._type == sexpr::LIST && !end[-1]._list.empty() + && end[-1]._list[0]._type == sexpr::TOKEN + && end[-1]._list[0]._str == "ATEND") + { + auto atb = end[-1]._list.begin() + 1; + auto ate = end[-1]._list.end(); + if (!build_effect_list(atb, ate, atend)) + return false; + --end; + + while (is_comment(end[-1])) + --end; + } + else + { + atend = nullptr; + } + if (end[-1]._type == sexpr::LIST && !end[-1]._list.empty() + && end[-1]._list[0]._type == sexpr::TOKEN + && end[-1]._list[0]._str == "ATTRIGGER") + { + auto atb = end[-1]._list.begin() + 1; + auto ate = end[-1]._list.end(); + if (!build_effect_list(atb, ate, attrig)) + return false; + --end; + } + else + { + attrig = nullptr; + } + if (!build_effect_list(begin, end, effect)) + return false; + out = new_spellguard(SPELLGUARD::EFFECT); + out->s.s_effect.effect = effect; + out->s.s_effect.at_trigger = attrig; + out->s.s_effect.at_end = atend; + return true; + } + return fail(s._list[0], "unknown spellbody"); + } + + static + bool parse_top_set(const std::vector& in) + { + if (in.size() != 3) + return fail(in[0], "not 2 arguments"); + ZString name = in[1]._str; + dumb_ptr expr; + if (!parse_expression(in[2], expr)) + return false; + if (find_constant(name)) + return fail(in[1], "assign constant"); + size_t var_id = intern_id(name); + magic_eval(dumb_ptr(&magic_default_env), &magic_conf.varv[var_id].val, expr); + return true; + } + static + bool parse_const(io::LineSpan span, const std::vector& in) + { + if (in.size() != 3) + return fail(in[0], "not 2 arguments"); + if (in[1]._type != sexpr::TOKEN) + return fail(in[1], "not token"); + ZString name = in[1]._str; + dumb_ptr expr; + if (!parse_expression(in[2], expr)) + return false; + val_t tmp; + magic_eval(dumb_ptr(&magic_default_env), &tmp, expr); + return bind_constant(span, name, &tmp); + } + static + bool parse_anchor(io::LineSpan span, const std::vector& in) + { + if (in.size() != 4) + return fail(in[0], "not 3 arguments"); + auto anchor = dumb_ptr::make(); + if (in[1]._type != sexpr::TOKEN) + return fail(in[1], "not token"); + anchor->name = in[1]._str; + if (in[2]._type != sexpr::STRING) + return fail(in[2], "not string"); + anchor->invocation = in[2]._str; + dumb_ptr expr; + if (!parse_expression(in[3], expr)) + return false; + anchor->location = expr; + return add_teleport_anchor(span, anchor); + } + static + bool parse_proc(io::LineSpan span, const std::vector& in) + { + if (in.size() < 4) + return fail(in[0], "not at least 3 arguments"); + auto proc = dumb_ptr::make(); + if (in[1]._type != sexpr::TOKEN) + return fail(in[1], "name not token"); + proc->name = in[1]._str; + if (in[2]._type != sexpr::LIST) + return fail(in[2], "args not list"); + for (const SExpr& arg : in[2]._list) + { + if (arg._type != sexpr::TOKEN) + return fail(arg, "arg not token"); + proc->argv.push_back(intern_id(arg._str)); + } + if (!build_effect_list(in.begin() + 3, in.end(), proc->body)) + return false; + return install_proc(span, proc); + } + static + bool parse_spell(io::LineSpan span, const std::vector& in) + { + if (in.size() < 6) + return fail(in[0], "not at least 5 arguments"); + if (in[1]._type != sexpr::LIST) + return fail(in[1], "flags not list"); + + auto spell = dumb_ptr::make(); + + for (const SExpr& s : in[1]._list) + { + if (s._type != sexpr::TOKEN) + return fail(s, "flag not token"); + SPELL_FLAG flag = SPELL_FLAG::ZERO; + if (s._str == "LOCAL") + flag = SPELL_FLAG::LOCAL; + else if (s._str == "NONMAGIC") + flag = SPELL_FLAG::NONMAGIC; + else if (s._str == "SILENT") + flag = SPELL_FLAG::SILENT; + else + return fail(s, "unknown flag"); + if (bool(spell->flags & flag)) + return fail(s, "duplicate flag"); + spell->flags |= flag; + } + if (in[2]._type != sexpr::TOKEN) + return fail(in[2], "name not token"); + spell->name = in[2]._str; + if (in[3]._type != sexpr::STRING) + return fail(in[3], "invoc not string"); + spell->invocation = in[3]._str; + if (in[4]._type != sexpr::LIST) + return fail(in[4], "spellarg not list"); + if (in[4]._list.size() == 0) + { + spell->spellarg_ty = SPELLARG::NONE; + } + else + { + if (in[4]._list.size() != 2) + return fail(in[4], "spellarg not empty list or pair"); + if (in[4]._list[0]._type != sexpr::TOKEN) + return fail(in[4]._list[0], "spellarg type not token"); + if (in[4]._list[1]._type != sexpr::TOKEN) + return fail(in[4]._list[1], "spellarg name not token"); + ZString ty = in[4]._list[0]._str; + if (ty == "PC") + spell->spellarg_ty = SPELLARG::PC; + else if (ty == "STRING") + spell->spellarg_ty = SPELLARG::STRING; + else + return fail(in[4]._list[0], "unknown spellarg type"); + ZString an = in[4]._list[1]._str; + spell->arg = intern_id(an); + } + std::vector::const_iterator it = in.begin() + 5; + for (;; ++it) + { + if (it == in.end()) + return fail(it[-1], "end of list scanning LET defs"); + if (is_comment(*it)) + continue; + if (it->_type != sexpr::LIST || it->_list.empty()) + break; + if (it->_list[0]._type != sexpr::TOKEN || it->_list[0]._str != "LET") + break; + + if (it->_list[1]._type != sexpr::TOKEN) + return fail(it->_list[1], "let name not token"); + ZString name = it->_list[1]._str; + if (find_constant(name)) + return fail(it->_list[1], "constant exists"); + dumb_ptr expr; + if (!parse_expression(it->_list[2], expr)) + return false; + letdef_t let; + let.id = intern_id(name); + let.expr = expr; + spell->letdefv.push_back(let); + } + if (it + 1 != in.end()) + return fail(*it, "expected only one body entry besides LET"); + + // formally, 'guard' only refers to the first argument of '=>' + // but internally, spellbodies use the same thing + dumb_ptr guard; + if (!parse_spellbody(*it, guard)) + return false; + spell->spellguard = guard; + return add_spell(span, spell); + } + + static + bool parse_top(io::LineSpan span, const std::vector& vs) + { + if (vs.empty()) + { + span.error("Empty list at top"); + return false; + } + if (vs[0]._type != sexpr::TOKEN) + return fail(vs[0], "top not token"); + ZString cmd = vs[0]._str; + if (cmd == "CONST") + return parse_const(span, vs); + if (cmd == "PROCEDURE") + return parse_proc(span, vs); + if (cmd == "SET") + return parse_top_set(vs); + if (cmd == "SPELL") + return parse_spell(span, vs); + if (cmd == "TELEPORT-ANCHOR") + return parse_anchor(span, vs); + return fail(vs[0], "Unknown top-level command"); + } + + static + bool loop(sexpr::Lexer& in) + { + SExpr s; + while (sexpr::parse(in, s)) + { + if (is_comment(s)) + continue; + if (s._type != sexpr::LIST) + return fail(s, "top-level entity not a list or comment"); + if (!parse_top(s._span, s._list)) + return false; + } + // handle low-level errors + if (in.peek() != sexpr::TOK_EOF) + { + in.span().error("parser gave up before end of file"); + return false; + } + return true; + } +} // namespace magic_v2 + +bool magic_init0() +{ + return magic_v2::init0(); +} + +bool load_magic_file_v2(ZString filename) +{ + sexpr::Lexer in(filename); + bool rv = magic_v2::loop(in); + if (!rv) + { + in.span().error(STRPRINTF("next token: %s '%s'", sexpr::token_name(in.peek()), in.val_string())); + } + return rv; +} diff --git a/src/map/magic-v2.hpp b/src/map/magic-v2.hpp new file mode 100644 index 0000000..d9140dc --- /dev/null +++ b/src/map/magic-v2.hpp @@ -0,0 +1,28 @@ +#ifndef TMWA_MAP_MAGIC_V2_HPP +#define TMWA_MAP_MAGIC_V2_HPP +// magic-v2.hpp - second generation magic parser +// +// Copyright © 2014 Ben Longbons +// +// This file is part of The Mana World (Athena server) +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +# include "../strings/zstring.hpp" + +bool magic_init0(); +// must be called after itemdb initialization +bool load_magic_file_v2(ZString filename); + +#endif // TMWA_MAP_MAGIC_V2_HPP diff --git a/src/map/magic.cpp b/src/map/magic.cpp index 2e521b2..56705fe 100644 --- a/src/map/magic.cpp +++ b/src/map/magic.cpp @@ -10,8 +10,6 @@ #include "magic-expr.hpp" #include "magic-interpreter-base.hpp" -#include "magic-interpreter-lexer.hpp" -#include "src/map/magic-interpreter-parser.hpp" #include "magic-stmt.hpp" #include "magic.hpp" diff --git a/src/map/main.cpp b/src/map/main.cpp index f0e3517..de1ca3c 100644 --- a/src/map/main.cpp +++ b/src/map/main.cpp @@ -1,4 +1,6 @@ // dummy file to make Make dependencies work #include "map.hpp" +#include "magic-v2.hpp" + #include "../poison.hpp" diff --git a/src/map/map.cpp b/src/map/map.cpp index d9dd9cc..e5a3341 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -41,6 +41,7 @@ #include "itemdb.hpp" #include "magic.hpp" #include "magic-interpreter.hpp" +#include "magic-v2.hpp" #include "mob.hpp" #include "npc.hpp" #include "party.hpp" @@ -1654,7 +1655,7 @@ bool map_confs(XString key, ZString value) if (key == "skill_db") return skill_readdb(value); if (key == "magic_conf") - return magic_init1(value); + return load_magic_file_v2(value); if (key == "resnametable") return load_resnametable(value); diff --git a/src/map/npc.cpp b/src/map/npc.cpp index 1e164a5..bfba45f 100644 --- a/src/map/npc.cpp +++ b/src/map/npc.cpp @@ -1060,7 +1060,7 @@ bool extract(XString xs, npc_item_list *itv) if (extract(name_or_id, &itv->nameid) && itv->nameid > 0) goto return_true; - id = itemdb_searchname(stringish(name_or_id.rstrip())); + id = itemdb_searchname(name_or_id.rstrip()); if (id == NULL) return false; itv->nameid = id->nameid; diff --git a/src/map/script.cpp b/src/map/script.cpp index fe42e44..9884aae 100644 --- a/src/map/script.cpp +++ b/src/map/script.cpp @@ -1832,7 +1832,7 @@ void builtin_countitem(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); if (item_data != NULL) nameid = item_data->nameid; @@ -1872,7 +1872,7 @@ void builtin_checkweight(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); if (item_data) nameid = item_data->nameid; @@ -1916,7 +1916,7 @@ void builtin_getitem(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); nameid = 727; //Default to iten if (item_data != NULL) @@ -1969,7 +1969,7 @@ void builtin_makeitem(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); nameid = 512; //Apple Item ID if (item_data) @@ -2015,7 +2015,7 @@ void builtin_delitem(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); //nameid=512; if (item_data) @@ -2960,7 +2960,7 @@ void builtin_getareadropitem(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); struct item_data *item_data = itemdb_searchname(name); item = 512; if (item_data) @@ -3376,7 +3376,7 @@ void builtin_getitemname(ScriptState *st) get_val(st, data); if (data->type == ByteCode::STR || data->type == ByteCode::CONSTSTR) { - ItemName name = stringish(ZString(conv_str(st, data))); + ZString name = ZString(conv_str(st, data)); i_data = itemdb_searchname(name); } else -- cgit v1.2.3-70-g09d2