diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2017-03-05 16:44:50 +0100 |
commit | 5dbf1809c6e3e905b94b8764e99491e608122261 (patch) | |
tree | 5e5a5360db15d86d59ec8c6e4f7eb511388c5a9a /modules/gdscript | |
parent | 45438e9918d421b244bfd7776a30e67dc7f2d3e3 (diff) |
A Whole New World (clang-format edition)
I can show you the code
Pretty, with proper whitespace
Tell me, coder, now when did
You last write readable code?
I can open your eyes
Make you see your bad indent
Force you to respect the style
The core devs agreed upon
A whole new world
A new fantastic code format
A de facto standard
With some sugar
Enforced with clang-format
A whole new world
A dazzling style we all dreamed of
And when we read it through
It's crystal clear
That now we're in a whole new world of code
Diffstat (limited to 'modules/gdscript')
-rw-r--r-- | modules/gdscript/gd_compiler.cpp | 1303 | ||||
-rw-r--r-- | modules/gdscript/gd_compiler.h | 144 | ||||
-rw-r--r-- | modules/gdscript/gd_editor.cpp | 2016 | ||||
-rw-r--r-- | modules/gdscript/gd_function.cpp | 991 | ||||
-rw-r--r-- | modules/gdscript/gd_function.h | 84 | ||||
-rw-r--r-- | modules/gdscript/gd_functions.cpp | 1044 | ||||
-rw-r--r-- | modules/gdscript/gd_functions.h | 4 | ||||
-rw-r--r-- | modules/gdscript/gd_parser.cpp | 2682 | ||||
-rw-r--r-- | modules/gdscript/gd_parser.h | 164 | ||||
-rw-r--r-- | modules/gdscript/gd_script.cpp | 1069 | ||||
-rw-r--r-- | modules/gdscript/gd_script.h | 270 | ||||
-rw-r--r-- | modules/gdscript/gd_tokenizer.cpp | 1163 | ||||
-rw-r--r-- | modules/gdscript/gd_tokenizer.h | 122 | ||||
-rw-r--r-- | modules/gdscript/register_types.cpp | 28 |
14 files changed, 5221 insertions, 5863 deletions
diff --git a/modules/gdscript/gd_compiler.cpp b/modules/gdscript/gd_compiler.cpp index 398c2cf82a..9591740438 100644 --- a/modules/gdscript/gd_compiler.cpp +++ b/modules/gdscript/gd_compiler.cpp @@ -29,53 +29,51 @@ #include "gd_compiler.h" #include "gd_script.h" -bool GDCompiler::_is_class_member_property(CodeGen & codegen, const StringName & p_name) { +bool GDCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) { if (!codegen.function_node || codegen.function_node->_static) return false; - return _is_class_member_property(codegen.script,p_name); + return _is_class_member_property(codegen.script, p_name); } -bool GDCompiler::_is_class_member_property(GDScript *owner, const StringName & p_name) { - +bool GDCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) { GDScript *scr = owner; - GDNativeClass *nc=NULL; - while(scr) { + GDNativeClass *nc = NULL; + while (scr) { if (scr->native.is_valid()) - nc=scr->native.ptr(); - scr=scr->_base; + nc = scr->native.ptr(); + scr = scr->_base; } - ERR_FAIL_COND_V(!nc,false); + ERR_FAIL_COND_V(!nc, false); - return ClassDB::has_property(nc->get_name(),p_name); + return ClassDB::has_property(nc->get_name(), p_name); } +void GDCompiler::_set_error(const String &p_error, const GDParser::Node *p_node) { -void GDCompiler::_set_error(const String& p_error,const GDParser::Node *p_node) { - - if (error!="") + if (error != "") return; - error=p_error; + error = p_error; if (p_node) { - err_line=p_node->line; - err_column=p_node->column; + err_line = p_node->line; + err_column = p_node->column; } else { - err_line=0; - err_column=0; + err_line = 0; + err_column = 0; } } -bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level) { +bool GDCompiler::_create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level) { - ERR_FAIL_COND_V(on->arguments.size()!=1,false); + ERR_FAIL_COND_V(on->arguments.size() != 1, false); - int src_address_a = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (src_address_a < 0) return false; codegen.opcodes.push_back(GDFunction::OPCODE_OPERATOR); // perform operator @@ -86,22 +84,20 @@ bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::Operato return true; } -bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer) { - - ERR_FAIL_COND_V(on->arguments.size()!=2,false); +bool GDCompiler::_create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer) { + ERR_FAIL_COND_V(on->arguments.size() != 2, false); - int src_address_a = _parse_expression(codegen,on->arguments[0],p_stack_level,false,p_initializer); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level, false, p_initializer); + if (src_address_a < 0) return false; - if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) + if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) p_stack_level++; //uses stack for return, increase stack - int src_address_b = _parse_expression(codegen,on->arguments[1],p_stack_level,false,p_initializer); - if (src_address_b<0) + int src_address_b = _parse_expression(codegen, on->arguments[1], p_stack_level, false, p_initializer); + if (src_address_b < 0) return false; - codegen.opcodes.push_back(GDFunction::OPCODE_OPERATOR); // perform operator codegen.opcodes.push_back(op); //which operator codegen.opcodes.push_back(src_address_a); // argument 1 @@ -109,7 +105,6 @@ bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::Operat return true; } - /* int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_expression) { @@ -128,55 +123,52 @@ int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_ex } */ -int GDCompiler::_parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level) { +int GDCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level) { - Variant::Operator var_op=Variant::OP_MAX; + Variant::Operator var_op = Variant::OP_MAX; + switch (p_expression->op) { - switch(p_expression->op) { - - case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op=Variant::OP_ADD; break; - case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op=Variant::OP_SUBSTRACT; break; - case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op=Variant::OP_MULTIPLY; break; - case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op=Variant::OP_DIVIDE; break; - case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op=Variant::OP_MODULE; break; - case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op=Variant::OP_SHIFT_LEFT; break; - case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op=Variant::OP_SHIFT_RIGHT; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op=Variant::OP_BIT_AND; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op=Variant::OP_BIT_OR; break; - case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op=Variant::OP_BIT_XOR; break; + case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op = Variant::OP_ADD; break; + case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op = Variant::OP_SUBSTRACT; break; + case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op = Variant::OP_MULTIPLY; break; + case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op = Variant::OP_DIVIDE; break; + case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op = Variant::OP_MODULE; break; + case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op = Variant::OP_SHIFT_LEFT; break; + case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op = Variant::OP_SHIFT_RIGHT; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op = Variant::OP_BIT_AND; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op = Variant::OP_BIT_OR; break; + case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op = Variant::OP_BIT_XOR; break; case GDParser::OperatorNode::OP_INIT_ASSIGN: case GDParser::OperatorNode::OP_ASSIGN: { //none } break; - default: { + default: { ERR_FAIL_V(-1); } } - bool initializer = p_expression->op==GDParser::OperatorNode::OP_INIT_ASSIGN; + bool initializer = p_expression->op == GDParser::OperatorNode::OP_INIT_ASSIGN; - if (var_op==Variant::OP_MAX) { + if (var_op == Variant::OP_MAX) { - return _parse_expression(codegen,p_expression->arguments[1],p_stack_level,false,initializer); + return _parse_expression(codegen, p_expression->arguments[1], p_stack_level, false, initializer); } - if (!_create_binary_operator(codegen,p_expression,var_op,p_stack_level,initializer)) + if (!_create_binary_operator(codegen, p_expression, var_op, p_stack_level, initializer)) return -1; - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; - } -int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root,bool p_initializer) { +int GDCompiler::_parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root, bool p_initializer) { - - switch(p_expression->type) { + switch (p_expression->type) { //should parse variable declaration and adjust stack accordingly... case GDParser::Node::TYPE_IDENTIFIER: { //return identifier @@ -185,16 +177,15 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre //This could be made much simpler by just indexing "self", but done this way (with custom self-addressing modes) increases peformance a lot. - const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode*>(p_expression); + const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode *>(p_expression); StringName identifier = in->name; - - if (_is_class_member_property(codegen,identifier)) { + if (_is_class_member_property(codegen, identifier)) { //get property codegen.opcodes.push_back(GDFunction::OPCODE_GET_MEMBER); // perform operator codegen.opcodes.push_back(codegen.get_name_map_pos(identifier)); // argument 2 (unary only takes one parameter) - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -204,8 +195,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (!p_initializer && codegen.stack_identifiers.has(identifier)) { int pos = codegen.stack_identifiers[identifier]; - return pos|(GDFunction::ADDR_TYPE_STACK_VARIABLE<<GDFunction::ADDR_BITS); - + return pos | (GDFunction::ADDR_TYPE_STACK_VARIABLE << GDFunction::ADDR_BITS); } //TRY MEMBERS! if (!codegen.function_node || !codegen.function_node->_static) { @@ -215,7 +205,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (codegen.script->member_indices.has(identifier)) { int idx = codegen.script->member_indices[identifier].index; - return idx|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS); //argument (stack root) } } @@ -225,45 +215,44 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre while (owner) { GDScript *scr = owner; - GDNativeClass *nc=NULL; - while(scr) { + GDNativeClass *nc = NULL; + while (scr) { if (scr->constants.has(identifier)) { //int idx=scr->constants[identifier]; int idx = codegen.get_name_map_pos(identifier); - return idx|(GDFunction::ADDR_TYPE_CLASS_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_CLASS_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root) } if (scr->native.is_valid()) - nc=scr->native.ptr(); - scr=scr->_base; + nc = scr->native.ptr(); + scr = scr->_base; } // CLASS C++ Integer Constant if (nc) { - bool success=false; - int constant = ClassDB::get_integer_constant(nc->get_name(),identifier,&success); + bool success = false; + int constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success); if (success) { - Variant key=constant; + Variant key = constant; int idx; if (!codegen.constant_map.has(key)) { - idx=codegen.constant_map.size(); - codegen.constant_map[key]=idx; + idx = codegen.constant_map.size(); + codegen.constant_map[key] = idx; } else { - idx=codegen.constant_map[key]; + idx = codegen.constant_map[key]; } - return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //make it a local constant (faster access) + return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //make it a local constant (faster access) } - } - owner=owner->_owner; + owner = owner->_owner; } /* @@ -278,58 +267,55 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier]; - return idx|(GDFunction::ADDR_TYPE_GLOBAL<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_GLOBAL << GDFunction::ADDR_BITS); //argument (stack root) } //not found, error - _set_error("Identifier not found: "+String(identifier),p_expression); + _set_error("Identifier not found: " + String(identifier), p_expression); return -1; - } break; case GDParser::Node::TYPE_CONSTANT: { //return constant - const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode*>(p_expression); - + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_expression); int idx; if (!codegen.constant_map.has(cn->value)) { - idx=codegen.constant_map.size(); - codegen.constant_map[cn->value]=idx; + idx = codegen.constant_map.size(); + codegen.constant_map[cn->value] = idx; } else { - idx=codegen.constant_map[cn->value]; + idx = codegen.constant_map[cn->value]; } - - return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root) + return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root) } break; case GDParser::Node::TYPE_SELF: { //return constant if (codegen.function_node && codegen.function_node->_static) { - _set_error("'self' not present in static function!",p_expression); + _set_error("'self' not present in static function!", p_expression); return -1; } - return (GDFunction::ADDR_TYPE_SELF<<GDFunction::ADDR_BITS); + return (GDFunction::ADDR_TYPE_SELF << GDFunction::ADDR_BITS); } break; case GDParser::Node::TYPE_ARRAY: { - const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode*>(p_expression); + const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_expression); Vector<int> values; - int slevel=p_stack_level; + int slevel = p_stack_level; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { - int ret = _parse_expression(codegen,an->elements[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, an->elements[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -339,10 +325,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_ARRAY); codegen.opcodes.push_back(values.size()); - for(int i=0;i<values.size();i++) + for (int i = 0; i < values.size(); i++) codegen.opcodes.push_back(values[i]); - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -350,27 +336,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } break; case GDParser::Node::TYPE_DICTIONARY: { - const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode*>(p_expression); + const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(p_expression); Vector<int> values; - int slevel=p_stack_level; + int slevel = p_stack_level; - for(int i=0;i<dn->elements.size();i++) { + for (int i = 0; i < dn->elements.size(); i++) { - int ret = _parse_expression(codegen,dn->elements[i].key,slevel); - if (ret<0) + int ret = _parse_expression(codegen, dn->elements[i].key, slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } values.push_back(ret); - ret = _parse_expression(codegen,dn->elements[i].value,slevel); - if (ret<0) + ret = _parse_expression(codegen, dn->elements[i].value, slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -380,10 +366,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_DICTIONARY); codegen.opcodes.push_back(dn->elements.size()); - for(int i=0;i<values.size();i++) + for (int i = 0; i < values.size(); i++) codegen.opcodes.push_back(values[i]); - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -392,27 +378,24 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::Node::TYPE_OPERATOR: { //hell breaks loose - const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode*>(p_expression); - switch(on->op) { - + const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode *>(p_expression); + switch (on->op) { //call/constructor operator case GDParser::OperatorNode::OP_PARENT_CALL: { - - ERR_FAIL_COND_V(on->arguments.size()<1,-1); + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); const GDParser::IdentifierNode *in = (const GDParser::IdentifierNode *)on->arguments[0]; - Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -425,27 +408,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(codegen.get_name_map_pos(in->name)); //instance codegen.opcodes.push_back(arguments.size()); //argument count codegen.alloc_call(arguments.size()); - for(int i=0;i<arguments.size();i++) + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments } break; case GDParser::OperatorNode::OP_CALL: { - if (on->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + if (on->arguments[0]->type == GDParser::Node::TYPE_TYPE) { //construct a basic type - ERR_FAIL_COND_V(on->arguments.size()<1,-1); + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); const GDParser::TypeNode *tn = (const GDParser::TypeNode *)on->arguments[0]; int vtype = tn->vtype; Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -457,24 +440,23 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(vtype); //instance codegen.opcodes.push_back(arguments.size()); //argument count codegen.alloc_call(arguments.size()); - for(int i=0;i<arguments.size();i++) + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments - } else if (on->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + } else if (on->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { //built in function - ERR_FAIL_COND_V(on->arguments.size()<1,-1); - + ERR_FAIL_COND_V(on->arguments.size() < 1, -1); Vector<int> arguments; int slevel = p_stack_level; - for(int i=1;i<on->arguments.size();i++) { + for (int i = 1; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } @@ -482,79 +464,74 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre arguments.push_back(ret); } - codegen.opcodes.push_back(GDFunction::OPCODE_CALL_BUILT_IN); - codegen.opcodes.push_back(static_cast<const GDParser::BuiltInFunctionNode*>(on->arguments[0])->function); - codegen.opcodes.push_back(on->arguments.size()-1); - codegen.alloc_call(on->arguments.size()-1); - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(static_cast<const GDParser::BuiltInFunctionNode *>(on->arguments[0])->function); + codegen.opcodes.push_back(on->arguments.size() - 1); + codegen.alloc_call(on->arguments.size() - 1); + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); } else { //regular function - ERR_FAIL_COND_V(on->arguments.size()<2,-1); + ERR_FAIL_COND_V(on->arguments.size() < 2, -1); const GDParser::Node *instance = on->arguments[0]; - if (instance->type==GDParser::Node::TYPE_SELF) { + if (instance->type == GDParser::Node::TYPE_SELF) { //room for optimization - } - Vector<int> arguments; int slevel = p_stack_level; - for(int i=0;i<on->arguments.size();i++) { + for (int i = 0; i < on->arguments.size(); i++) { int ret; - if (i==0 && on->arguments[i]->type==GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) { + if (i == 0 && on->arguments[i]->type == GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) { //static call to self - ret=(GDFunction::ADDR_TYPE_CLASS<<GDFunction::ADDR_BITS); - } else if (i==1) { + ret = (GDFunction::ADDR_TYPE_CLASS << GDFunction::ADDR_BITS); + } else if (i == 1) { - if (on->arguments[i]->type!=GDParser::Node::TYPE_IDENTIFIER) { - _set_error("Attempt to call a non-identifier.",on); + if (on->arguments[i]->type != GDParser::Node::TYPE_IDENTIFIER) { + _set_error("Attempt to call a non-identifier.", on); return -1; } - GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode*>(on->arguments[i]); - ret=codegen.get_name_map_pos(id->name); + GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode *>(on->arguments[i]); + ret = codegen.get_name_map_pos(id->name); } else { - ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } } arguments.push_back(ret); - } - codegen.opcodes.push_back(p_root?GDFunction::OPCODE_CALL:GDFunction::OPCODE_CALL_RETURN); // perform operator - codegen.opcodes.push_back(on->arguments.size()-2); - codegen.alloc_call(on->arguments.size()-2); - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(p_root ? GDFunction::OPCODE_CALL : GDFunction::OPCODE_CALL_RETURN); // perform operator + codegen.opcodes.push_back(on->arguments.size() - 2); + codegen.alloc_call(on->arguments.size() - 2); + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); } } break; case GDParser::OperatorNode::OP_YIELD: { - - ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size()!=2,-1); + ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size() != 2, -1); Vector<int> arguments; int slevel = p_stack_level; - for(int i=0;i<on->arguments.size();i++) { + for (int i = 0; i < on->arguments.size(); i++) { - int ret = _parse_expression(codegen,on->arguments[i],slevel); - if (ret<0) + int ret = _parse_expression(codegen, on->arguments[i], slevel); + if (ret < 0) return ret; - if (ret&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) { + if (ret & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) { slevel++; codegen.alloc_stack(slevel); } @@ -562,8 +539,8 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } //push call bytecode - codegen.opcodes.push_back(arguments.size()==0?GDFunction::OPCODE_YIELD:GDFunction::OPCODE_YIELD_SIGNAL); // basic type constructor - for(int i=0;i<arguments.size();i++) + codegen.opcodes.push_back(arguments.size() == 0 ? GDFunction::OPCODE_YIELD : GDFunction::OPCODE_YIELD_SIGNAL); // basic type constructor + for (int i = 0; i < arguments.size(); i++) codegen.opcodes.push_back(arguments[i]); //arguments codegen.opcodes.push_back(GDFunction::OPCODE_YIELD_RESUME); //next will be where to place the result :) @@ -574,60 +551,60 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::OperatorNode::OP_INDEX: case GDParser::OperatorNode::OP_INDEX_NAMED: { - ERR_FAIL_COND_V(on->arguments.size()!=2,-1); + ERR_FAIL_COND_V(on->arguments.size() != 2, -1); int slevel = p_stack_level; - bool named=(on->op==GDParser::OperatorNode::OP_INDEX_NAMED); + bool named = (on->op == GDParser::OperatorNode::OP_INDEX_NAMED); - int from = _parse_expression(codegen,on->arguments[0],slevel); - if (from<0) + int from = _parse_expression(codegen, on->arguments[0], slevel); + if (from < 0) return from; int index; if (named) { - if (on->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { + if (on->arguments[0]->type == GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { - GDParser::IdentifierNode* identifier = static_cast<GDParser::IdentifierNode*>(on->arguments[1]); - const Map<StringName,GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name); + GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode *>(on->arguments[1]); + const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name); #ifdef DEBUG_ENABLED - if (MI && MI->get().getter==codegen.function_node->name) { - String n = static_cast<GDParser::IdentifierNode*>(on->arguments[1])->name; - _set_error("Must use '"+n+"' instead of 'self."+n+"' in getter.",on); + if (MI && MI->get().getter == codegen.function_node->name) { + String n = static_cast<GDParser::IdentifierNode *>(on->arguments[1])->name; + _set_error("Must use '" + n + "' instead of 'self." + n + "' in getter.", on); return -1; } #endif - if (MI && MI->get().getter=="") { + if (MI && MI->get().getter == "") { // Faster than indexing self (as if no self. had been used) - return (MI->get().index)|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS); + return (MI->get().index) | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS); } } - index=codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode*>(on->arguments[1])->name); + index = codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode *>(on->arguments[1])->name); } else { - if (on->arguments[1]->type==GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value.get_type()==Variant::STRING) { + if (on->arguments[1]->type == GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value.get_type() == Variant::STRING) { //also, somehow, named (speed up anyway) - StringName name = static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value; - index=codegen.get_name_map_pos(name); - named=true; + StringName name = static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value; + index = codegen.get_name_map_pos(name); + named = true; } else { //regular indexing - if (from&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (from & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - index = _parse_expression(codegen,on->arguments[1],slevel); - if (index<0) + index = _parse_expression(codegen, on->arguments[1], slevel); + if (index < 0) return index; } } - codegen.opcodes.push_back(named?GDFunction::OPCODE_GET_NAMED:GDFunction::OPCODE_GET); // perform operator + codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET); // perform operator codegen.opcodes.push_back(from); // argument 1 codegen.opcodes.push_back(index); // argument 2 (unary only takes one parameter) @@ -636,66 +613,66 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre // AND operator with early out on failure - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos=codegen.opcodes.size(); + int jump_fail_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos2=codegen.opcodes.size(); + int jump_fail_pos2 = codegen.opcodes.size(); codegen.opcodes.push_back(0); codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_TRUE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - codegen.opcodes[jump_fail_pos]=codegen.opcodes.size(); - codegen.opcodes[jump_fail_pos2]=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + codegen.opcodes[jump_fail_pos] = codegen.opcodes.size(); + codegen.opcodes[jump_fail_pos2] = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_FALSE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; case GDParser::OperatorNode::OP_OR: { // OR operator with early out on success - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF); codegen.opcodes.push_back(res); - int jump_success_pos=codegen.opcodes.size(); + int jump_success_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF); codegen.opcodes.push_back(res); - int jump_success_pos2=codegen.opcodes.size(); + int jump_success_pos2 = codegen.opcodes.size(); codegen.opcodes.push_back(0); codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_FALSE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - codegen.opcodes[jump_success_pos]=codegen.opcodes.size(); - codegen.opcodes[jump_success_pos2]=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + codegen.opcodes[jump_success_pos] = codegen.opcodes.size(); + codegen.opcodes[jump_success_pos2] = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_TRUE); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; // ternary operators @@ -703,70 +680,113 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre // x IF a ELSE y operator with early out on failure - int res = _parse_expression(codegen,on->arguments[0],p_stack_level); - if (res<0) + int res = _parse_expression(codegen, on->arguments[0], p_stack_level); + if (res < 0) return res; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(res); - int jump_fail_pos=codegen.opcodes.size(); + int jump_fail_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - - res = _parse_expression(codegen,on->arguments[1],p_stack_level); - if (res<0) + res = _parse_expression(codegen, on->arguments[1], p_stack_level); + if (res < 0) return res; - + codegen.alloc_stack(p_stack_level); //it will be used.. codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(res); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - int jump_past_pos=codegen.opcodes.size(); + int jump_past_pos = codegen.opcodes.size(); codegen.opcodes.push_back(0); - - codegen.opcodes[jump_fail_pos]=codegen.opcodes.size(); - res = _parse_expression(codegen,on->arguments[2],p_stack_level); - if (res<0) + + codegen.opcodes[jump_fail_pos] = codegen.opcodes.size(); + res = _parse_expression(codegen, on->arguments[2], p_stack_level); + if (res < 0) return res; - + codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); - codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(res); - - codegen.opcodes[jump_past_pos]=codegen.opcodes.size(); - - return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS; + + codegen.opcodes[jump_past_pos] = codegen.opcodes.size(); + + return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS; } break; //unary operators - case GDParser::OperatorNode::OP_NEG: { if (!_create_unary_operator(codegen,on,Variant::OP_NEGATE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_NOT: { if (!_create_unary_operator(codegen,on,Variant::OP_NOT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_INVERT: { if (!_create_unary_operator(codegen,on,Variant::OP_BIT_NEGATE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_PREINC: { } break; //? - case GDParser::OperatorNode::OP_PREDEC: { } break; - case GDParser::OperatorNode::OP_INC: { } break; - case GDParser::OperatorNode::OP_DEC: { } break; + case GDParser::OperatorNode::OP_NEG: { + if (!_create_unary_operator(codegen, on, Variant::OP_NEGATE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_NOT: { + if (!_create_unary_operator(codegen, on, Variant::OP_NOT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_INVERT: { + if (!_create_unary_operator(codegen, on, Variant::OP_BIT_NEGATE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_PREINC: { + } break; //? + case GDParser::OperatorNode::OP_PREDEC: { + } break; + case GDParser::OperatorNode::OP_INC: { + } break; + case GDParser::OperatorNode::OP_DEC: { + } break; //binary operators (in precedence order) - case GDParser::OperatorNode::OP_IN: { if (!_create_binary_operator(codegen,on,Variant::OP_IN,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_NOT_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_NOT_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_LESS: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_LESS_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_GREATER: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_GREATER_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER_EQUAL,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_ADD: { if (!_create_binary_operator(codegen,on,Variant::OP_ADD,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_SUB: { if (!_create_binary_operator(codegen,on,Variant::OP_SUBSTRACT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_MUL: { if (!_create_binary_operator(codegen,on,Variant::OP_MULTIPLY,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_DIV: { if (!_create_binary_operator(codegen,on,Variant::OP_DIVIDE,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_MOD: { if (!_create_binary_operator(codegen,on,Variant::OP_MODULE,p_stack_level)) return -1;} break; + case GDParser::OperatorNode::OP_IN: { + if (!_create_binary_operator(codegen, on, Variant::OP_IN, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_NOT_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_NOT_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_LESS: { + if (!_create_binary_operator(codegen, on, Variant::OP_LESS, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_LESS_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_LESS_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_GREATER: { + if (!_create_binary_operator(codegen, on, Variant::OP_GREATER, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_GREATER_EQUAL: { + if (!_create_binary_operator(codegen, on, Variant::OP_GREATER_EQUAL, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_ADD: { + if (!_create_binary_operator(codegen, on, Variant::OP_ADD, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_SUB: { + if (!_create_binary_operator(codegen, on, Variant::OP_SUBSTRACT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_MUL: { + if (!_create_binary_operator(codegen, on, Variant::OP_MULTIPLY, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_DIV: { + if (!_create_binary_operator(codegen, on, Variant::OP_DIVIDE, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_MOD: { + if (!_create_binary_operator(codegen, on, Variant::OP_MODULE, p_stack_level)) return -1; + } break; //case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break; //case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_AND: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_AND,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_OR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_OR,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_BIT_XOR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_XOR,p_stack_level)) return -1;} break; - //shift - case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break; - case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break; + case GDParser::OperatorNode::OP_BIT_AND: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_AND, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_OR: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_OR, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_BIT_XOR: { + if (!_create_binary_operator(codegen, on, Variant::OP_BIT_XOR, p_stack_level)) return -1; + } break; + //shift + case GDParser::OperatorNode::OP_SHIFT_LEFT: { + if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_LEFT, p_stack_level)) return -1; + } break; + case GDParser::OperatorNode::OP_SHIFT_RIGHT: { + if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_RIGHT, p_stack_level)) return -1; + } break; //assignment operators case GDParser::OperatorNode::OP_ASSIGN_ADD: case GDParser::OperatorNode::OP_ASSIGN_SUB: @@ -781,63 +801,57 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre case GDParser::OperatorNode::OP_INIT_ASSIGN: case GDParser::OperatorNode::OP_ASSIGN: { - ERR_FAIL_COND_V(on->arguments.size()!=2,-1); - - - if (on->arguments[0]->type==GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED)) { - //SET (chained) MODE!! + ERR_FAIL_COND_V(on->arguments.size() != 2, -1); + if (on->arguments[0]->type == GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED)) { +//SET (chained) MODE!! #ifdef DEBUG_ENABLED - if (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - const GDParser::OperatorNode* inon = static_cast<GDParser::OperatorNode*>(on->arguments[0]); - + if (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED) { + const GDParser::OperatorNode *inon = static_cast<GDParser::OperatorNode *>(on->arguments[0]); - if (inon->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { + if (inon->arguments[0]->type == GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) { - const Map<StringName,GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDParser::IdentifierNode*>(inon->arguments[1])->name); - if (MI && MI->get().setter==codegen.function_node->name) { - String n = static_cast<GDParser::IdentifierNode*>(inon->arguments[1])->name; - _set_error("Must use '"+n+"' instead of 'self."+n+"' in setter.",inon); + const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name); + if (MI && MI->get().setter == codegen.function_node->name) { + String n = static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name; + _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", inon); return -1; } } } #endif + int slevel = p_stack_level; - int slevel=p_stack_level; - - GDParser::OperatorNode* op = static_cast<GDParser::OperatorNode*>(on->arguments[0]); + GDParser::OperatorNode *op = static_cast<GDParser::OperatorNode *>(on->arguments[0]); /* Find chain of sets */ StringName assign_property; - List<GDParser::OperatorNode*> chain; + List<GDParser::OperatorNode *> chain; { //create get/set chain - GDParser::OperatorNode* n=op; - while(true) { + GDParser::OperatorNode *n = op; + while (true) { chain.push_back(n); - if (n->arguments[0]->type!=GDParser::Node::TYPE_OPERATOR) { + if (n->arguments[0]->type != GDParser::Node::TYPE_OPERATOR) { //check for a built-in property - if (n->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) { + if (n->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) { - GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode*>(n->arguments[0]); - if (_is_class_member_property(codegen,identifier->name)) { + GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode *>(n->arguments[0]); + if (_is_class_member_property(codegen, identifier->name)) { assign_property = identifier->name; - } - } break; } - n = static_cast<GDParser::OperatorNode*>(n->arguments[0]); - if (n->op!=GDParser::OperatorNode::OP_INDEX && n->op!=GDParser::OperatorNode::OP_INDEX_NAMED) + n = static_cast<GDParser::OperatorNode *>(n->arguments[0]); + if (n->op != GDParser::OperatorNode::OP_INDEX && n->op != GDParser::OperatorNode::OP_INDEX_NAMED) break; } } @@ -845,23 +859,21 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre /* Chain of gets */ //get at (potential) root stack pos, so it can be returned - int prev_pos = _parse_expression(codegen,chain.back()->get()->arguments[0],slevel); - if (prev_pos<0) + int prev_pos = _parse_expression(codegen, chain.back()->get()->arguments[0], slevel); + if (prev_pos < 0) return prev_pos; - int retval=prev_pos; + int retval = prev_pos; //print_line("retval: "+itos(retval)); - if (retval&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (retval & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - Vector<int> setchain; - - if (assign_property!=StringName()) { + if (assign_property != StringName()) { // recover and assign at the end, this allows stuff like // position.x+=2.0 @@ -871,37 +883,34 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre setchain.push_back(GDFunction::OPCODE_SET_MEMBER); } - for(List<GDParser::OperatorNode*>::Element *E=chain.back();E;E=E->prev()) { + for (List<GDParser::OperatorNode *>::Element *E = chain.back(); E; E = E->prev()) { - - if (E==chain.front()) //ignore first + if (E == chain.front()) //ignore first break; - bool named = E->get()->op==GDParser::OperatorNode::OP_INDEX_NAMED; + bool named = E->get()->op == GDParser::OperatorNode::OP_INDEX_NAMED; int key_idx; if (named) { - key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(E->get()->arguments[1])->name); + key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(E->get()->arguments[1])->name); //printf("named key %x\n",key_idx); } else { - if (prev_pos&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) { + if (prev_pos & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) { slevel++; codegen.alloc_stack(slevel); } GDParser::Node *key = E->get()->arguments[1]; - key_idx = _parse_expression(codegen,key,slevel); + key_idx = _parse_expression(codegen, key, slevel); //printf("expr key %x\n",key_idx); - //stack was raised here if retval was stack but.. - } - if (key_idx<0) //error + if (key_idx < 0) //error return key_idx; codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET); @@ -909,134 +918,116 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre codegen.opcodes.push_back(key_idx); slevel++; codegen.alloc_stack(slevel); - int dst_pos = (GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|slevel; + int dst_pos = (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | slevel; codegen.opcodes.push_back(dst_pos); - //add in reverse order, since it will be reverted - setchain.push_back(dst_pos); setchain.push_back(key_idx); setchain.push_back(prev_pos); setchain.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET); - prev_pos=dst_pos; - + prev_pos = dst_pos; } setchain.invert(); - int set_index; - bool named=false; + bool named = false; + if (static_cast<const GDParser::OperatorNode *>(op)->op == GDParser::OperatorNode::OP_INDEX_NAMED) { - if (static_cast<const GDParser::OperatorNode*>(op)->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - - - set_index=codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name); - named=true; + set_index = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name); + named = true; } else { - set_index = _parse_expression(codegen,op->arguments[1],slevel+1); - named=false; + set_index = _parse_expression(codegen, op->arguments[1], slevel + 1); + named = false; } - - if (set_index<0) //error + if (set_index < 0) //error return set_index; - if (set_index&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (set_index & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - - int set_value = _parse_assign_right_expression(codegen,on,slevel+1); - if (set_value<0) //error + int set_value = _parse_assign_right_expression(codegen, on, slevel + 1); + if (set_value < 0) //error return set_value; - codegen.opcodes.push_back(named?GDFunction::OPCODE_SET_NAMED:GDFunction::OPCODE_SET); + codegen.opcodes.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET); codegen.opcodes.push_back(prev_pos); codegen.opcodes.push_back(set_index); codegen.opcodes.push_back(set_value); - for(int i=0;i<setchain.size();i++) { - + for (int i = 0; i < setchain.size(); i++) { codegen.opcodes.push_back(setchain[i]); } return retval; - - } else if (on->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER && _is_class_member_property(codegen,static_cast<GDParser::IdentifierNode*>(on->arguments[0])->name)) { + } else if (on->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER && _is_class_member_property(codegen, static_cast<GDParser::IdentifierNode *>(on->arguments[0])->name)) { //assignment to member property int slevel = p_stack_level; - int src_address = _parse_assign_right_expression(codegen,on,slevel); - if (src_address<0) + int src_address = _parse_assign_right_expression(codegen, on, slevel); + if (src_address < 0) return -1; - StringName name = static_cast<GDParser::IdentifierNode*>(on->arguments[0])->name; + StringName name = static_cast<GDParser::IdentifierNode *>(on->arguments[0])->name; codegen.opcodes.push_back(GDFunction::OPCODE_SET_MEMBER); codegen.opcodes.push_back(codegen.get_name_map_pos(name)); codegen.opcodes.push_back(src_address); - return GDFunction::ADDR_TYPE_NIL<<GDFunction::ADDR_BITS; + return GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS; } else { - - //REGULAR ASSIGNMENT MODE!! int slevel = p_stack_level; - int dst_address_a = _parse_expression(codegen,on->arguments[0],slevel,false,on->op==GDParser::OperatorNode::OP_INIT_ASSIGN); - if (dst_address_a<0) + int dst_address_a = _parse_expression(codegen, on->arguments[0], slevel, false, on->op == GDParser::OperatorNode::OP_INIT_ASSIGN); + if (dst_address_a < 0) return -1; - if (dst_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) { + if (dst_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) { slevel++; codegen.alloc_stack(slevel); } - int src_address_b = _parse_assign_right_expression(codegen,on,slevel); - if (src_address_b<0) + int src_address_b = _parse_assign_right_expression(codegen, on, slevel); + if (src_address_b < 0) return -1; - - - codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN); // perform operator codegen.opcodes.push_back(dst_address_a); // argument 1 codegen.opcodes.push_back(src_address_b); // argument 2 (unary only takes one parameter) return dst_address_a; //if anything, returns wathever was assigned or correct stack position - } - } break; case GDParser::OperatorNode::OP_EXTENDS: { - ERR_FAIL_COND_V(on->arguments.size()!=2,false); - + ERR_FAIL_COND_V(on->arguments.size() != 2, false); int slevel = p_stack_level; - int src_address_a = _parse_expression(codegen,on->arguments[0],slevel); - if (src_address_a<0) + int src_address_a = _parse_expression(codegen, on->arguments[0], slevel); + if (src_address_a < 0) return -1; - if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) + if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) slevel++; //uses stack for return, increase stack - int src_address_b = _parse_expression(codegen,on->arguments[1],slevel); - if (src_address_b<0) + int src_address_b = _parse_expression(codegen, on->arguments[1], slevel); + if (src_address_b < 0) return -1; codegen.opcodes.push_back(GDFunction::OPCODE_EXTENDS_TEST); // perform operator @@ -1046,14 +1037,13 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre } break; default: { - - ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #"+itos(on->op)+" in parse tree while parsing expression."); + ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression."); ERR_FAIL_V(0); //unreachable code } break; } - int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.opcodes.push_back(dst_addr); // append the stack level as destination address of the opcode codegen.alloc_stack(p_stack_level); return dst_addr; @@ -1064,47 +1054,43 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre ERR_EXPLAIN("Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); ERR_FAIL_V(-1); //unreachable code } break; - - } ERR_FAIL_V(-1); //unreachable code } - -Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level,int p_break_addr,int p_continue_addr) { +Error GDCompiler::_parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) { codegen.push_stack_identifiers(); - int new_identifiers=0; - codegen.current_line=p_block->line; + int new_identifiers = 0; + codegen.current_line = p_block->line; - for(int i=0;i<p_block->statements.size();i++) { + for (int i = 0; i < p_block->statements.size(); i++) { const GDParser::Node *s = p_block->statements[i]; - - switch(s->type) { + switch (s->type) { case GDParser::Node::TYPE_NEWLINE: { #ifdef DEBUG_ENABLED - const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode*>(s); + const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode *>(s); codegen.opcodes.push_back(GDFunction::OPCODE_LINE); codegen.opcodes.push_back(nl->line); - codegen.current_line=nl->line; + codegen.current_line = nl->line; #endif } break; case GDParser::Node::TYPE_CONTROL_FLOW: { // try subblocks - const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode*>(s); + const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode *>(s); - switch(cf->cf_type) { + switch (cf->cf_type) { case GDParser::ControlFlowNode::CF_MATCH: { GDParser::MatchNode *match = cf->match; - + GDParser::IdentifierNode *id = memnew(GDParser::IdentifierNode); id->name = "#match_value"; - + // var #match_value // copied because there is no _parse_statement :( codegen.add_stack_identifier(id->name, p_stack_level++); @@ -1112,25 +1098,25 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo new_identifiers++; GDParser::OperatorNode *op = memnew(GDParser::OperatorNode); - op->op=GDParser::OperatorNode::OP_ASSIGN; + op->op = GDParser::OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(match->val_to_match); - + int ret = _parse_expression(codegen, op, p_stack_level); if (ret < 0) { return ERR_PARSE_ERROR; } - + // break address codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(codegen.opcodes.size() + 3); int break_addr = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(0); // break addr - + for (int j = 0; j < match->compiled_pattern_branches.size(); j++) { GDParser::MatchNode::CompiledPatternBranch branch = match->compiled_pattern_branches[j]; - + // jump over continue // jump unconditionally // continue address @@ -1139,87 +1125,81 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo if (ret < 0) { return ERR_PARSE_ERROR; } - + codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF); codegen.opcodes.push_back(ret); codegen.opcodes.push_back(codegen.opcodes.size() + 3); int continue_addr = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(0); - - - + Error err = _parse_block(codegen, branch.body, p_stack_level, p_break_addr, continue_addr); if (err) { return ERR_PARSE_ERROR; } - + codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(break_addr); - + codegen.opcodes[continue_addr + 1] = codegen.opcodes.size(); } - + codegen.opcodes[break_addr + 1] = codegen.opcodes.size(); - - + } break; - + case GDParser::ControlFlowNode::CF_IF: { #ifdef DEBUG_ENABLED codegen.opcodes.push_back(GDFunction::OPCODE_LINE); codegen.opcodes.push_back(cf->line); - codegen.current_line=cf->line; + codegen.current_line = cf->line; #endif - int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(ret); - int else_addr=codegen.opcodes.size(); + int else_addr = codegen.opcodes.size(); codegen.opcodes.push_back(0); //temporary - Error err = _parse_block(codegen,cf->body,p_stack_level,p_break_addr,p_continue_addr); + Error err = _parse_block(codegen, cf->body, p_stack_level, p_break_addr, p_continue_addr); if (err) return err; if (cf->body_else) { codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - int end_addr=codegen.opcodes.size(); + int end_addr = codegen.opcodes.size(); codegen.opcodes.push_back(0); - codegen.opcodes[else_addr]=codegen.opcodes.size(); + codegen.opcodes[else_addr] = codegen.opcodes.size(); - Error err = _parse_block(codegen,cf->body_else,p_stack_level,p_break_addr,p_continue_addr); + Error err = _parse_block(codegen, cf->body_else, p_stack_level, p_break_addr, p_continue_addr); if (err) return err; - codegen.opcodes[end_addr]=codegen.opcodes.size(); + codegen.opcodes[end_addr] = codegen.opcodes.size(); } else { //end without else - codegen.opcodes[else_addr]=codegen.opcodes.size(); - + codegen.opcodes[else_addr] = codegen.opcodes.size(); } } break; case GDParser::ControlFlowNode::CF_FOR: { - - - int slevel=p_stack_level; - int iter_stack_pos=slevel; - int iterator_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - int counter_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); - int container_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS); + int slevel = p_stack_level; + int iter_stack_pos = slevel; + int iterator_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + int counter_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); + int container_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS); codegen.alloc_stack(slevel); - codegen.push_stack_identifiers(); - codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode*>(cf->arguments[0])->name,iter_stack_pos); + codegen.push_stack_identifiers(); + codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode *>(cf->arguments[0])->name, iter_stack_pos); - int ret = _parse_expression(codegen,cf->arguments[1],slevel,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[1], slevel, false); + if (ret < 0) return ERR_COMPILATION_FAILED; //assign container @@ -1231,32 +1211,29 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo codegen.opcodes.push_back(GDFunction::OPCODE_ITERATE_BEGIN); codegen.opcodes.push_back(counter_pos); codegen.opcodes.push_back(container_pos); - codegen.opcodes.push_back(codegen.opcodes.size()+4); + codegen.opcodes.push_back(codegen.opcodes.size() + 4); codegen.opcodes.push_back(iterator_pos); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next - codegen.opcodes.push_back(codegen.opcodes.size()+8); + codegen.opcodes.push_back(codegen.opcodes.size() + 8); //break loop - int break_pos=codegen.opcodes.size(); + int break_pos = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next codegen.opcodes.push_back(0); //skip code for next //next loop - int continue_pos=codegen.opcodes.size(); + int continue_pos = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_ITERATE); codegen.opcodes.push_back(counter_pos); codegen.opcodes.push_back(container_pos); codegen.opcodes.push_back(break_pos); codegen.opcodes.push_back(iterator_pos); - - Error err = _parse_block(codegen,cf->body,slevel,break_pos,continue_pos); + Error err = _parse_block(codegen, cf->body, slevel, break_pos, continue_pos); if (err) return err; - codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(continue_pos); - codegen.opcodes[break_pos+1]=codegen.opcodes.size(); - + codegen.opcodes[break_pos + 1] = codegen.opcodes.size(); codegen.pop_stack_identifiers(); @@ -1264,25 +1241,25 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo case GDParser::ControlFlowNode::CF_WHILE: { codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); - codegen.opcodes.push_back(codegen.opcodes.size()+3); - int break_addr=codegen.opcodes.size(); + codegen.opcodes.push_back(codegen.opcodes.size() + 3); + int break_addr = codegen.opcodes.size(); codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(0); - int continue_addr=codegen.opcodes.size(); + int continue_addr = codegen.opcodes.size(); - int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT); codegen.opcodes.push_back(ret); codegen.opcodes.push_back(break_addr); - Error err = _parse_block(codegen,cf->body,p_stack_level,break_addr,continue_addr); + Error err = _parse_block(codegen, cf->body, p_stack_level, break_addr, continue_addr); if (err) return err; codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); codegen.opcodes.push_back(continue_addr); - codegen.opcodes[break_addr+1]=codegen.opcodes.size(); + codegen.opcodes[break_addr + 1] = codegen.opcodes.size(); } break; case GDParser::ControlFlowNode::CF_SWITCH: { @@ -1290,9 +1267,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::ControlFlowNode::CF_BREAK: { - if (p_break_addr<0) { + if (p_break_addr < 0) { - _set_error("'break'' not within loop",cf); + _set_error("'break'' not within loop", cf); return ERR_COMPILATION_FAILED; } codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); @@ -1301,9 +1278,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::ControlFlowNode::CF_CONTINUE: { - if (p_continue_addr<0) { + if (p_continue_addr < 0) { - _set_error("'continue' not within loop",cf); + _set_error("'continue' not within loop", cf); return ERR_COMPILATION_FAILED; } @@ -1317,29 +1294,28 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo if (cf->arguments.size()) { - ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false); - if (ret<0) + ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; } else { - ret=GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS; + ret = GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS; } codegen.opcodes.push_back(GDFunction::OPCODE_RETURN); codegen.opcodes.push_back(ret); } break; - } } break; case GDParser::Node::TYPE_ASSERT: { // try subblocks - const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode*>(s); + const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode *>(s); - int ret = _parse_expression(codegen,as->condition,p_stack_level,false); - if (ret<0) + int ret = _parse_expression(codegen, as->condition, p_stack_level, false); + if (ret < 0) return ERR_PARSE_ERROR; codegen.opcodes.push_back(GDFunction::OPCODE_ASSERT); @@ -1353,99 +1329,91 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo } break; case GDParser::Node::TYPE_LOCAL_VAR: { + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(s); - const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode*>(s); - - if (_is_class_member_property(codegen,lv->name)) { - _set_error("Name for local variable '"+String(lv->name)+"' can't shadow class property of the same name.",lv); + if (_is_class_member_property(codegen, lv->name)) { + _set_error("Name for local variable '" + String(lv->name) + "' can't shadow class property of the same name.", lv); return ERR_ALREADY_EXISTS; } - codegen.add_stack_identifier(lv->name,p_stack_level++); + codegen.add_stack_identifier(lv->name, p_stack_level++); codegen.alloc_stack(p_stack_level); new_identifiers++; } break; default: { //expression - int ret = _parse_expression(codegen,s,p_stack_level,true); - if (ret<0) + int ret = _parse_expression(codegen, s, p_stack_level, true); + if (ret < 0) return ERR_PARSE_ERROR; } break; - } - } codegen.pop_stack_identifiers(); return OK; } - -Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready) { +Error GDCompiler::_parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready) { Vector<int> bytecode; CodeGen codegen; - codegen.class_node=p_class; - codegen.script=p_script; - codegen.function_node=p_func; - codegen.stack_max=0; - codegen.current_line=0; - codegen.call_max=0; - codegen.debug_stack=ScriptDebugger::get_singleton()!=NULL; + codegen.class_node = p_class; + codegen.script = p_script; + codegen.function_node = p_func; + codegen.stack_max = 0; + codegen.current_line = 0; + codegen.call_max = 0; + codegen.debug_stack = ScriptDebugger::get_singleton() != NULL; Vector<StringName> argnames; - int stack_level=0; + int stack_level = 0; if (p_func) { - for(int i=0;i<p_func->arguments.size();i++) { - if (_is_class_member_property(p_script,p_func->arguments[i])) { - _set_error("Name for argument '"+String(p_func->arguments[i])+"' can't shadow class property of the same name.",p_func); + for (int i = 0; i < p_func->arguments.size(); i++) { + if (_is_class_member_property(p_script, p_func->arguments[i])) { + _set_error("Name for argument '" + String(p_func->arguments[i]) + "' can't shadow class property of the same name.", p_func); return ERR_ALREADY_EXISTS; } - codegen.add_stack_identifier(p_func->arguments[i],i); + codegen.add_stack_identifier(p_func->arguments[i], i); #ifdef TOOLS_ENABLED argnames.push_back(p_func->arguments[i]); #endif } - stack_level=p_func->arguments.size(); + stack_level = p_func->arguments.size(); } codegen.alloc_stack(stack_level); /* Parse initializer -if applies- */ - bool is_initializer=!p_for_ready && !p_func; + bool is_initializer = !p_for_ready && !p_func; - if (is_initializer || (p_func && String(p_func->name)=="_init")) { + if (is_initializer || (p_func && String(p_func->name) == "_init")) { //parse initializer for class members - if (!p_func && p_class->extends_used && p_script->native.is_null()){ + if (!p_func && p_class->extends_used && p_script->native.is_null()) { //call implicit parent constructor codegen.opcodes.push_back(GDFunction::OPCODE_CALL_SELF_BASE); codegen.opcodes.push_back(codegen.get_name_map_pos("_init")); codegen.opcodes.push_back(0); - codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|0); - + codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | 0); } - Error err = _parse_block(codegen,p_class->initializer,stack_level); + Error err = _parse_block(codegen, p_class->initializer, stack_level); if (err) return err; - is_initializer=true; - + is_initializer = true; } - if (p_for_ready || (p_func && String(p_func->name)=="_ready")) { + if (p_for_ready || (p_func && String(p_func->name) == "_ready")) { //parse initializer for class members if (p_class->ready->statements.size()) { - Error err = _parse_block(codegen,p_class->ready,stack_level); + Error err = _parse_block(codegen, p_class->ready, stack_level); if (err) return err; } - } - /* Parse default argument code -if applies- */ Vector<int> defarg_addr; @@ -1457,196 +1425,185 @@ Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode * codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_TO_DEF_ARGUMENT); defarg_addr.push_back(codegen.opcodes.size()); - for(int i=0;i<p_func->default_values.size();i++) { + for (int i = 0; i < p_func->default_values.size(); i++) { - _parse_expression(codegen,p_func->default_values[i],stack_level,true); + _parse_expression(codegen, p_func->default_values[i], stack_level, true); defarg_addr.push_back(codegen.opcodes.size()); } - defarg_addr.invert(); } - - - Error err = _parse_block(codegen,p_func->body,stack_level); + Error err = _parse_block(codegen, p_func->body, stack_level); if (err) return err; - func_name=p_func->name; + func_name = p_func->name; } else { if (p_for_ready) - func_name="_ready"; + func_name = "_ready"; else - func_name="_init"; + func_name = "_init"; } codegen.opcodes.push_back(GDFunction::OPCODE_END); - GDFunction *gdfunc=NULL; + GDFunction *gdfunc = NULL; /* if (String(p_func->name)=="") { //initializer func gdfunc = &p_script->initializer; */ //} else { //regular func - p_script->member_functions[func_name]=memnew(GDFunction); - gdfunc = p_script->member_functions[func_name]; + p_script->member_functions[func_name] = memnew(GDFunction); + gdfunc = p_script->member_functions[func_name]; //} if (p_func) { - gdfunc->_static=p_func->_static; - gdfunc->rpc_mode=p_func->rpc_mode; + gdfunc->_static = p_func->_static; + gdfunc->rpc_mode = p_func->rpc_mode; } #ifdef TOOLS_ENABLED - gdfunc->arg_names=argnames; + gdfunc->arg_names = argnames; #endif //constants if (codegen.constant_map.size()) { - gdfunc->_constant_count=codegen.constant_map.size(); + gdfunc->_constant_count = codegen.constant_map.size(); gdfunc->constants.resize(codegen.constant_map.size()); - gdfunc->_constants_ptr=&gdfunc->constants[0]; - const Variant *K=NULL; - while((K=codegen.constant_map.next(K))) { + gdfunc->_constants_ptr = &gdfunc->constants[0]; + const Variant *K = NULL; + while ((K = codegen.constant_map.next(K))) { int idx = codegen.constant_map[*K]; - gdfunc->constants[idx]=*K; + gdfunc->constants[idx] = *K; } } else { - gdfunc->_constants_ptr=NULL; - gdfunc->_constant_count=0; + gdfunc->_constants_ptr = NULL; + gdfunc->_constant_count = 0; } //global names if (codegen.name_map.size()) { gdfunc->global_names.resize(codegen.name_map.size()); gdfunc->_global_names_ptr = &gdfunc->global_names[0]; - for(Map<StringName,int>::Element *E=codegen.name_map.front();E;E=E->next()) { + for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) { - gdfunc->global_names[E->get()]=E->key(); + gdfunc->global_names[E->get()] = E->key(); } - gdfunc->_global_names_count=gdfunc->global_names.size(); + gdfunc->_global_names_count = gdfunc->global_names.size(); } else { gdfunc->_global_names_ptr = NULL; - gdfunc->_global_names_count =0; + gdfunc->_global_names_count = 0; } - if (codegen.opcodes.size()) { - gdfunc->code=codegen.opcodes; - gdfunc->_code_ptr=&gdfunc->code[0]; - gdfunc->_code_size=codegen.opcodes.size(); + gdfunc->code = codegen.opcodes; + gdfunc->_code_ptr = &gdfunc->code[0]; + gdfunc->_code_size = codegen.opcodes.size(); } else { - gdfunc->_code_ptr=NULL; - gdfunc->_code_size=0; + gdfunc->_code_ptr = NULL; + gdfunc->_code_size = 0; } if (defarg_addr.size()) { - gdfunc->default_arguments=defarg_addr; - gdfunc->_default_arg_count=defarg_addr.size()-1; - gdfunc->_default_arg_ptr=&gdfunc->default_arguments[0]; + gdfunc->default_arguments = defarg_addr; + gdfunc->_default_arg_count = defarg_addr.size() - 1; + gdfunc->_default_arg_ptr = &gdfunc->default_arguments[0]; } else { - gdfunc->_default_arg_count=0; - gdfunc->_default_arg_ptr=NULL; + gdfunc->_default_arg_count = 0; + gdfunc->_default_arg_ptr = NULL; } - gdfunc->_argument_count=p_func ? p_func->arguments.size() : 0; - gdfunc->_stack_size=codegen.stack_max; - gdfunc->_call_size=codegen.call_max; - gdfunc->name=func_name; + gdfunc->_argument_count = p_func ? p_func->arguments.size() : 0; + gdfunc->_stack_size = codegen.stack_max; + gdfunc->_call_size = codegen.call_max; + gdfunc->name = func_name; #ifdef DEBUG_ENABLED - if (ScriptDebugger::get_singleton()){ + if (ScriptDebugger::get_singleton()) { String signature; //path - if (p_script->get_path()!=String()) - signature+=p_script->get_path(); + if (p_script->get_path() != String()) + signature += p_script->get_path(); //loc if (p_func) { - signature+="::"+itos(p_func->body->line); + signature += "::" + itos(p_func->body->line); } else { - signature+="::0"; + signature += "::0"; } //funciton and class if (p_class->name) { - signature+="::"+String(p_class->name)+"."+String(func_name); + signature += "::" + String(p_class->name) + "." + String(func_name); } else { - signature+="::"+String(func_name); + signature += "::" + String(func_name); } - - - gdfunc->profile.signature=signature; + gdfunc->profile.signature = signature; } #endif - gdfunc->_script=p_script; - gdfunc->source=source; + gdfunc->_script = p_script; + gdfunc->source = source; #ifdef DEBUG_ENABLED { - gdfunc->func_cname=(String(source)+" - "+String(func_name)).utf8(); - gdfunc->_func_cname=gdfunc->func_cname.get_data(); - + gdfunc->func_cname = (String(source) + " - " + String(func_name)).utf8(); + gdfunc->_func_cname = gdfunc->func_cname.get_data(); } #endif if (p_func) { - gdfunc->_initial_line=p_func->line; + gdfunc->_initial_line = p_func->line; #ifdef TOOLS_ENABLED - p_script->member_lines[func_name]=p_func->line; + p_script->member_lines[func_name] = p_func->line; #endif } else { - gdfunc->_initial_line=0; + gdfunc->_initial_line = 0; } if (codegen.debug_stack) - gdfunc->stack_debug=codegen.stack_debug; + gdfunc->stack_debug = codegen.stack_debug; if (is_initializer) - p_script->initializer=gdfunc; - + p_script->initializer = gdfunc; return OK; } - - Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state) { - Map<StringName,Ref<GDScript> > old_subclasses; + Map<StringName, Ref<GDScript> > old_subclasses; if (p_keep_state) { - old_subclasses=p_script->subclasses; + old_subclasses = p_script->subclasses; } - p_script->native=Ref<GDNativeClass>(); - p_script->base=Ref<GDScript>(); - p_script->_base=NULL; + p_script->native = Ref<GDNativeClass>(); + p_script->base = Ref<GDScript>(); + p_script->_base = NULL; p_script->members.clear(); p_script->constants.clear(); - for (Map<StringName,GDFunction*>::Element *E=p_script->member_functions.front();E;E=E->next()) { + for (Map<StringName, GDFunction *>::Element *E = p_script->member_functions.front(); E; E = E->next()) { memdelete(E->get()); } p_script->member_functions.clear(); p_script->member_indices.clear(); p_script->member_info.clear(); p_script->_signals.clear(); - p_script->initializer=NULL; + p_script->initializer = NULL; p_script->subclasses.clear(); - p_script->_owner=p_owner; - p_script->tool=p_class->tool; - p_script->name=p_class->name; - + p_script->_owner = p_owner; + p_script->tool = p_class->tool; + p_script->name = p_class->name; Ref<GDNativeClass> native; @@ -1656,8 +1613,7 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa Ref<GDScript> script; - - if (path!="") { + if (path != "") { //path (and optionally subclasses) if (path.is_rel_path()) { @@ -1667,47 +1623,46 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa if (p_owner) { GDScript *current_class = p_owner; while (current_class != NULL) { - base=current_class->get_path(); - if (base=="") + base = current_class->get_path(); + if (base == "") current_class = current_class->_owner; else break; } - } - else { + } else { base = p_script->get_path(); } - if (base=="" || base.is_rel_path()) { - _set_error("Could not resolve relative path for parent class: "+path,p_class); + if (base == "" || base.is_rel_path()) { + _set_error("Could not resolve relative path for parent class: " + path, p_class); return ERR_FILE_NOT_FOUND; } - path=base.get_base_dir().plus_file(path).simplify_path(); + path = base.get_base_dir().plus_file(path).simplify_path(); } script = ResourceLoader::load(path); if (script.is_null()) { - _set_error("Could not load base class: "+path,p_class); + _set_error("Could not load base class: " + path, p_class); return ERR_FILE_NOT_FOUND; } if (!script->valid) { - _set_error("Script not fully loaded (cyclic preload?): "+path,p_class); + _set_error("Script not fully loaded (cyclic preload?): " + path, p_class); return ERR_BUSY; } //print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid)); if (p_class->extends_class.size()) { - for(int i=0;i<p_class->extends_class.size();i++) { + for (int i = 0; i < p_class->extends_class.size(); i++) { String sub = p_class->extends_class[i]; if (script->subclasses.has(sub)) { Ref<Script> subclass = script->subclasses[sub]; //avoid reference from dissapearing - script=subclass; + script = subclass; } else { - _set_error("Could not find subclass: "+sub,p_class); + _set_error("Could not find subclass: " + sub, p_class); return ERR_FILE_NOT_FOUND; } } @@ -1715,54 +1670,52 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa } else { - ERR_FAIL_COND_V(p_class->extends_class.size()==0,ERR_BUG); + ERR_FAIL_COND_V(p_class->extends_class.size() == 0, ERR_BUG); //look around for the subclasses - String base=p_class->extends_class[0]; + String base = p_class->extends_class[0]; GDScript *p = p_owner; Ref<GDScript> base_class; - while(p) { + while (p) { if (p->subclasses.has(base)) { - base_class=p->subclasses[base]; + base_class = p->subclasses[base]; break; } - p=p->_owner; + p = p->_owner; } if (base_class.is_valid()) { - for(int i=1;i<p_class->extends_class.size();i++) { + for (int i = 1; i < p_class->extends_class.size(); i++) { - String subclass=p_class->extends_class[i]; + String subclass = p_class->extends_class[i]; if (base_class->subclasses.has(subclass)) { - base_class=base_class->subclasses[subclass]; + base_class = base_class->subclasses[subclass]; } else { - _set_error("Could not find subclass: "+subclass,p_class); + _set_error("Could not find subclass: " + subclass, p_class); return ERR_FILE_NOT_FOUND; } } - script=base_class; - + script = base_class; } else { - if (p_class->extends_class.size()>1) { + if (p_class->extends_class.size() > 1) { - _set_error("Invalid inheritance (unknown class+subclasses)",p_class); + _set_error("Invalid inheritance (unknown class+subclasses)", p_class); return ERR_FILE_NOT_FOUND; - } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { - _set_error("Unknown class: '"+base+"'",p_class); + _set_error("Unknown class: '" + base + "'", p_class); return ERR_FILE_NOT_FOUND; } @@ -1770,66 +1723,62 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; if (!native.is_valid()) { - _set_error("Global not a class: '"+base+"'",p_class); + _set_error("Global not a class: '" + base + "'", p_class); return ERR_FILE_NOT_FOUND; } } - - } if (script.is_valid()) { - p_script->base=script; - p_script->_base=p_script->base.ptr(); - p_script->member_indices=script->member_indices; + p_script->base = script; + p_script->_base = p_script->base.ptr(); + p_script->member_indices = script->member_indices; } else if (native.is_valid()) { - p_script->native=native; + p_script->native = native; } else { - _set_error("Could not determine inheritance",p_class); + _set_error("Could not determine inheritance", p_class); return ERR_FILE_NOT_FOUND; } - - }else { + } else { // without extends, implicitly extend Reference int native_idx = GDScriptLanguage::get_singleton()->get_global_map()["Reference"]; native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx]; ERR_FAIL_COND_V(native.is_null(), ERR_BUG); - p_script->native=native; + p_script->native = native; } //print_line("Script: "+p_script->get_path()+" indices: "+itos(p_script->member_indices.size())); - - for(int i=0;i<p_class->variables.size();i++) { + for (int i = 0; i < p_class->variables.size(); i++) { StringName name = p_class->variables[i].identifier; if (p_script->member_indices.has(name)) { - _set_error("Member '"+name+"' already exists (in current or parent class)",p_class); + _set_error("Member '" + name + "' already exists (in current or parent class)", p_class); return ERR_ALREADY_EXISTS; } - if (_is_class_member_property(p_script,name)) { - _set_error("Member '"+name+"' already exists as a class property.",p_class); + if (_is_class_member_property(p_script, name)) { + _set_error("Member '" + name + "' already exists as a class property.", p_class); return ERR_ALREADY_EXISTS; } - if (p_class->variables[i]._export.type!=Variant::NIL) { + if (p_class->variables[i]._export.type != Variant::NIL) { - p_script->member_info[name]=p_class->variables[i]._export; + p_script->member_info[name] = p_class->variables[i]._export; #ifdef TOOLS_ENABLED - if (p_class->variables[i].default_value.get_type()!=Variant::NIL) { + if (p_class->variables[i].default_value.get_type() != Variant::NIL) { - p_script->member_default_values[name]=p_class->variables[i].default_value; + p_script->member_default_values[name] = p_class->variables[i].default_value; } #endif } else { - p_script->member_info[name]=PropertyInfo(Variant::NIL,name,PROPERTY_HINT_NONE,"",PROPERTY_USAGE_SCRIPT_VARIABLE); + p_script->member_info[name] = PropertyInfo(Variant::NIL, name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE); } //int new_idx = p_script->member_indices.size(); @@ -1837,176 +1786,168 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa minfo.index = p_script->member_indices.size(); minfo.setter = p_class->variables[i].setter; minfo.getter = p_class->variables[i].getter; - minfo.rpc_mode=p_class->variables[i].rpc_mode; + minfo.rpc_mode = p_class->variables[i].rpc_mode; - p_script->member_indices[name]=minfo; + p_script->member_indices[name] = minfo; p_script->members.insert(name); #ifdef TOOLS_ENABLED - p_script->member_lines[name]=p_class->variables[i].line; + p_script->member_lines[name] = p_class->variables[i].line; #endif - - } - for(int i=0;i<p_class->constant_expressions.size();i++) { + for (int i = 0; i < p_class->constant_expressions.size(); i++) { StringName name = p_class->constant_expressions[i].identifier; - ERR_CONTINUE( p_class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT ); + ERR_CONTINUE(p_class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT); - if (_is_class_member_property(p_script,name)) { - _set_error("Member '"+name+"' already exists as a class property.",p_class); + if (_is_class_member_property(p_script, name)) { + _set_error("Member '" + name + "' already exists as a class property.", p_class); return ERR_ALREADY_EXISTS; } - GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode*>(p_class->constant_expressions[i].expression); + GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode *>(p_class->constant_expressions[i].expression); - p_script->constants.insert(name,constant->value); - //p_script->constants[constant->value].make_const(); + p_script->constants.insert(name, constant->value); +//p_script->constants[constant->value].make_const(); #ifdef TOOLS_ENABLED - p_script->member_lines[name]=p_class->constant_expressions[i].expression->line; + p_script->member_lines[name] = p_class->constant_expressions[i].expression->line; #endif - } - for(int i=0;i<p_class->_signals.size();i++) { + for (int i = 0; i < p_class->_signals.size(); i++) { StringName name = p_class->_signals[i].name; GDScript *c = p_script; - while(c) { + while (c) { if (c->_signals.has(name)) { - _set_error("Signal '"+name+"' redefined (in current or parent class)",p_class); + _set_error("Signal '" + name + "' redefined (in current or parent class)", p_class); return ERR_ALREADY_EXISTS; } if (c->base.is_valid()) { - c=c->base.ptr(); + c = c->base.ptr(); } else { - c=NULL; + c = NULL; } } if (native.is_valid()) { - if (ClassDB::has_signal(native->get_name(),name)) { - _set_error("Signal '"+name+"' redefined (original in native class '"+String(native->get_name())+"')",p_class); + if (ClassDB::has_signal(native->get_name(), name)) { + _set_error("Signal '" + name + "' redefined (original in native class '" + String(native->get_name()) + "')", p_class); return ERR_ALREADY_EXISTS; } } - p_script->_signals[name]=p_class->_signals[i].arguments; + p_script->_signals[name] = p_class->_signals[i].arguments; } //parse sub-classes - for(int i=0;i<p_class->subclasses.size();i++) { + for (int i = 0; i < p_class->subclasses.size(); i++) { StringName name = p_class->subclasses[i]->name; Ref<GDScript> subclass; if (old_subclasses.has(name)) { - subclass=old_subclasses[name]; + subclass = old_subclasses[name]; } else { subclass.instance(); } - Error err = _parse_class(subclass.ptr(),p_script,p_class->subclasses[i],p_keep_state); + Error err = _parse_class(subclass.ptr(), p_script, p_class->subclasses[i], p_keep_state); if (err) return err; #ifdef TOOLS_ENABLED - p_script->member_lines[name]=p_class->subclasses[i]->line; + p_script->member_lines[name] = p_class->subclasses[i]->line; #endif - p_script->constants.insert(name,subclass); //once parsed, goes to the list of constants - p_script->subclasses.insert(name,subclass); - + p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants + p_script->subclasses.insert(name, subclass); } - //parse methods - bool has_initializer=false; - bool has_ready=false; + bool has_initializer = false; + bool has_ready = false; - for(int i=0;i<p_class->functions.size();i++) { + for (int i = 0; i < p_class->functions.size(); i++) { - if (!has_initializer && p_class->functions[i]->name=="_init") - has_initializer=true; - if (!has_ready && p_class->functions[i]->name=="_ready") - has_ready=true; - Error err = _parse_function(p_script,p_class,p_class->functions[i]); + if (!has_initializer && p_class->functions[i]->name == "_init") + has_initializer = true; + if (!has_ready && p_class->functions[i]->name == "_ready") + has_ready = true; + Error err = _parse_function(p_script, p_class, p_class->functions[i]); if (err) return err; } //parse static methods - for(int i=0;i<p_class->static_functions.size();i++) { + for (int i = 0; i < p_class->static_functions.size(); i++) { - Error err = _parse_function(p_script,p_class,p_class->static_functions[i]); + Error err = _parse_function(p_script, p_class, p_class->static_functions[i]); if (err) return err; } - if (!has_initializer) { //create a constructor - Error err = _parse_function(p_script,p_class,NULL); + Error err = _parse_function(p_script, p_class, NULL); if (err) return err; } if (!has_ready && p_class->ready->statements.size()) { //create a constructor - Error err = _parse_function(p_script,p_class,NULL,true); + Error err = _parse_function(p_script, p_class, NULL, true); if (err) return err; } #ifdef DEBUG_ENABLED //validate setters/getters if debug is enabled - for(int i=0;i<p_class->variables.size();i++) { + for (int i = 0; i < p_class->variables.size(); i++) { if (p_class->variables[i].setter) { - const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].setter); + const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].setter); if (!E) { - _set_error("Setter function '"+String(p_class->variables[i].setter)+"' not found in class.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Setter function '" + String(p_class->variables[i].setter) + "' not found in class.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } if (E->get()->is_static()) { - _set_error("Setter function '"+String(p_class->variables[i].setter)+"' is static.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Setter function '" + String(p_class->variables[i].setter) + "' is static.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } - } if (p_class->variables[i].getter) { - const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].getter); + const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].getter); if (!E) { - _set_error("Getter function '"+String(p_class->variables[i].getter)+"' not found in class.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Getter function '" + String(p_class->variables[i].getter) + "' not found in class.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } if (E->get()->is_static()) { - _set_error("Getter function '"+String(p_class->variables[i].getter)+"' is static.",NULL); - err_line=p_class->variables[i].line; - err_column=0; + _set_error("Getter function '" + String(p_class->variables[i].getter) + "' is static.", NULL); + err_line = p_class->variables[i].line; + err_column = 0; return ERR_PARSE_ERROR; } - } } @@ -2014,96 +1955,88 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa if (p_keep_state) { - print_line("RELOAD KEEP "+p_script->path); - for (Set<Object*>::Element *E=p_script->instances.front();E;) { + print_line("RELOAD KEEP " + p_script->path); + for (Set<Object *>::Element *E = p_script->instances.front(); E;) { - Set<Object*>::Element *N = E->next(); + Set<Object *>::Element *N = E->next(); ScriptInstance *si = E->get()->get_script_instance(); if (si->is_placeholder()) { #ifdef TOOLS_ENABLED - PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance*>(si); + PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si); if (p_script->is_tool()) { //re-create as an instance p_script->placeholders.erase(psi); //remove placeholder - GDInstance* instance = memnew( GDInstance ); - instance->base_ref=E->get()->cast_to<Reference>(); + GDInstance *instance = memnew(GDInstance); + instance->base_ref = E->get()->cast_to<Reference>(); instance->members.resize(p_script->member_indices.size()); - instance->script=Ref<GDScript>(p_script); - instance->owner=E->get(); + instance->script = Ref<GDScript>(p_script); + instance->owner = E->get(); //needed for hot reloading - for(Map<StringName,GDScript::MemberInfo>::Element *E=p_script->member_indices.front();E;E=E->next()) { - instance->member_indices_cache[E->key()]=E->get().index; + for (Map<StringName, GDScript::MemberInfo>::Element *E = p_script->member_indices.front(); E; E = E->next()) { + instance->member_indices_cache[E->key()] = E->get().index; } instance->owner->set_script_instance(instance); - /* STEP 2, INITIALIZE AND CONSRTUCT */ Variant::CallError ce; - p_script->initializer->call(instance,NULL,0,ce); + p_script->initializer->call(instance, NULL, 0, ce); - if (ce.error!=Variant::CallError::CALL_OK) { + if (ce.error != Variant::CallError::CALL_OK) { //well, tough luck, not goinna do anything here } } #endif } else { - GDInstance *gi = static_cast<GDInstance*>(si); + GDInstance *gi = static_cast<GDInstance *>(si); gi->reload_members(); } - E=N; - + E = N; } - - } #endif - p_script->valid=true; + p_script->valid = true; return OK; } -Error GDCompiler::compile(const GDParser *p_parser,GDScript *p_script,bool p_keep_state) { +Error GDCompiler::compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state) { - err_line=-1; - err_column=-1; - error=""; - parser=p_parser; - const GDParser::Node* root = parser->get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_INVALID_DATA); + err_line = -1; + err_column = -1; + error = ""; + parser = p_parser; + const GDParser::Node *root = parser->get_parse_tree(); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_INVALID_DATA); - source=p_script->get_path(); + source = p_script->get_path(); - Error err = _parse_class(p_script,NULL,static_cast<const GDParser::ClassNode*>(root),p_keep_state); + Error err = _parse_class(p_script, NULL, static_cast<const GDParser::ClassNode *>(root), p_keep_state); if (err) return err; return OK; - } String GDCompiler::get_error() const { return error; } -int GDCompiler::get_error_line() const{ +int GDCompiler::get_error_line() const { return err_line; } -int GDCompiler::get_error_column() const{ +int GDCompiler::get_error_column() const { return err_column; } -GDCompiler::GDCompiler() -{ +GDCompiler::GDCompiler() { } - - diff --git a/modules/gdscript/gd_compiler.h b/modules/gdscript/gd_compiler.h index eb6079e8e0..c84bd97246 100644 --- a/modules/gdscript/gd_compiler.h +++ b/modules/gdscript/gd_compiler.h @@ -32,7 +32,6 @@ #include "gd_parser.h" #include "gd_script.h" - class GDCompiler { const GDParser *parser; @@ -43,83 +42,86 @@ class GDCompiler { const GDParser::FunctionNode *function_node; bool debug_stack; - List< Map<StringName,int> > stack_id_stack; - Map<StringName,int> stack_identifiers; - - List<GDFunction::StackDebug> stack_debug; - List< Map<StringName,int> > block_identifier_stack; - Map<StringName,int> block_identifiers; - - void add_stack_identifier(const StringName& p_id,int p_stackpos) { - stack_identifiers[p_id]=p_stackpos; - if (debug_stack) { - block_identifiers[p_id]=p_stackpos; - GDFunction::StackDebug sd; - sd.added=true; - sd.line=current_line; - sd.identifier=p_id; - sd.pos=p_stackpos; - stack_debug.push_back(sd); - } - } - - void push_stack_identifiers() { - stack_id_stack.push_back( stack_identifiers ); - if (debug_stack) { - - block_identifier_stack.push_back(block_identifiers); - block_identifiers.clear(); - } - } - - void pop_stack_identifiers() { - stack_identifiers = stack_id_stack.back()->get(); - stack_id_stack.pop_back(); - - if (debug_stack) { - for (Map<StringName,int>::Element *E=block_identifiers.front();E;E=E->next()) { - - GDFunction::StackDebug sd; - sd.added=false; - sd.identifier=E->key(); - sd.line=current_line; - sd.pos=E->get(); - stack_debug.push_back(sd); - } - block_identifiers=block_identifier_stack.back()->get(); - block_identifier_stack.pop_back(); - } - } + List<Map<StringName, int> > stack_id_stack; + Map<StringName, int> stack_identifiers; + + List<GDFunction::StackDebug> stack_debug; + List<Map<StringName, int> > block_identifier_stack; + Map<StringName, int> block_identifiers; + + void add_stack_identifier(const StringName &p_id, int p_stackpos) { + stack_identifiers[p_id] = p_stackpos; + if (debug_stack) { + block_identifiers[p_id] = p_stackpos; + GDFunction::StackDebug sd; + sd.added = true; + sd.line = current_line; + sd.identifier = p_id; + sd.pos = p_stackpos; + stack_debug.push_back(sd); + } + } + void push_stack_identifiers() { + stack_id_stack.push_back(stack_identifiers); + if (debug_stack) { + + block_identifier_stack.push_back(block_identifiers); + block_identifiers.clear(); + } + } + + void pop_stack_identifiers() { + stack_identifiers = stack_id_stack.back()->get(); + stack_id_stack.pop_back(); + + if (debug_stack) { + for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) { + + GDFunction::StackDebug sd; + sd.added = false; + sd.identifier = E->key(); + sd.line = current_line; + sd.pos = E->get(); + stack_debug.push_back(sd); + } + block_identifiers = block_identifier_stack.back()->get(); + block_identifier_stack.pop_back(); + } + } //int get_identifier_pos(const StringName& p_dentifier) const; - HashMap<Variant,int,VariantHasher,VariantComparator> constant_map; - Map<StringName,int> name_map; + HashMap<Variant, int, VariantHasher, VariantComparator> constant_map; + Map<StringName, int> name_map; - int get_name_map_pos(const StringName& p_identifier) { + int get_name_map_pos(const StringName &p_identifier) { int ret; if (!name_map.has(p_identifier)) { - ret=name_map.size(); - name_map[p_identifier]=ret; + ret = name_map.size(); + name_map[p_identifier] = ret; } else { - ret=name_map[p_identifier]; + ret = name_map[p_identifier]; } return ret; } - int get_constant_pos(const Variant& p_constant) { + int get_constant_pos(const Variant &p_constant) { if (constant_map.has(p_constant)) return constant_map[p_constant]; int pos = constant_map.size(); - constant_map[p_constant]=pos; + constant_map[p_constant] = pos; return pos; } Vector<int> opcodes; - void alloc_stack(int p_level) { if (p_level >= stack_max) stack_max=p_level+1; } - void alloc_call(int p_params) { if (p_params >= call_max) call_max=p_params; } + void alloc_stack(int p_level) { + if (p_level >= stack_max) stack_max = p_level + 1; + } + void alloc_call(int p_params) { + if (p_params >= call_max) call_max = p_params; + } - int current_line; + int current_line; int stack_max; int call_max; }; @@ -135,28 +137,27 @@ class GDCompiler { Ref<GDScript> _parse_class(GDParser::ClassNode *p_class); #endif - bool _is_class_member_property(CodeGen & codegen, const StringName & p_name); - bool _is_class_member_property(GDScript *owner, const StringName & p_name); + bool _is_class_member_property(CodeGen &codegen, const StringName &p_name); + bool _is_class_member_property(GDScript *owner, const StringName &p_name); - void _set_error(const String& p_error,const GDParser::Node *p_node); + void _set_error(const String &p_error, const GDParser::Node *p_node); - bool _create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level); - bool _create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer=false); + bool _create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level); + bool _create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer = false); //int _parse_subexpression(CodeGen& codegen,const GDParser::BlockNode *p_block,const GDParser::Node *p_expression); - int _parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level); - int _parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root=false,bool p_initializer=false); - Error _parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level=0,int p_break_addr=-1,int p_continue_addr=-1); - Error _parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready=false); - Error _parse_class(GDScript *p_script,GDScript *p_owner,const GDParser::ClassNode *p_class,bool p_keep_state); + int _parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level); + int _parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false); + Error _parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1); + Error _parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready = false); + Error _parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state); int err_line; int err_column; StringName source; String error; public: - - Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state=false); + Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state = false); String get_error() const; int get_error_line() const; @@ -165,5 +166,4 @@ public: GDCompiler(); }; - #endif // COMPILER_H diff --git a/modules/gdscript/gd_editor.cpp b/modules/gdscript/gd_editor.cpp index 9dd41847d7..bd428941e0 100644 --- a/modules/gdscript/gd_editor.cpp +++ b/modules/gdscript/gd_editor.cpp @@ -26,8 +26,8 @@ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gd_script.h" #include "gd_compiler.h" +#include "gd_script.h" #include "global_config.h" #include "os/file_access.h" @@ -35,73 +35,64 @@ void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const p_delimiters->push_back("#"); p_delimiters->push_back("\"\"\" \"\"\""); - } void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { p_delimiters->push_back("\" \""); p_delimiters->push_back("' '"); - - } -Ref<Script> GDScriptLanguage::get_template(const String& p_class_name, const String& p_base_class_name) const { +Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { - String _template = String()+ - "extends %BASE%\n\n"+ - "# class member variables go here, for example:\n"+ - "# var a = 2\n"+ - "# var b = \"textvar\"\n\n"+ - "func _ready():\n"+ - "\t# Called every time the node is added to the scene.\n"+ - "\t# Initialization here\n"+ - "\tpass\n"; + String _template = String() + + "extends %BASE%\n\n" + + "# class member variables go here, for example:\n" + + "# var a = 2\n" + + "# var b = \"textvar\"\n\n" + + "func _ready():\n" + + "\t# Called every time the node is added to the scene.\n" + + "\t# Initialization here\n" + + "\tpass\n"; - _template = _template.replace("%BASE%",p_base_class_name); + _template = _template.replace("%BASE%", p_base_class_name); Ref<GDScript> script; script.instance(); script->set_source_code(_template); return script; - } - - - -bool GDScriptLanguage::validate(const String& p_script, int &r_line_error,int &r_col_error,String& r_test_error, const String& p_path,List<String> *r_functions) const { +bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { GDParser parser; - Error err = parser.parse(p_script,p_path.get_base_dir(),true,p_path); + Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path); if (err) { - r_line_error=parser.get_error_line(); - r_col_error=parser.get_error_column(); - r_test_error=parser.get_error(); + r_line_error = parser.get_error_line(); + r_col_error = parser.get_error_column(); + r_test_error = parser.get_error(); return false; } else { const GDParser::Node *root = parser.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); - Map<int,String> funcs; - for(int i=0;i<cl->functions.size();i++) { + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); + Map<int, String> funcs; + for (int i = 0; i < cl->functions.size(); i++) { - funcs[cl->functions[i]->line]=cl->functions[i]->name; + funcs[cl->functions[i]->line] = cl->functions[i]->name; } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { - funcs[cl->static_functions[i]->line]=cl->static_functions[i]->name; + funcs[cl->static_functions[i]->line] = cl->static_functions[i]->name; } - for (Map<int,String>::Element *E=funcs.front();E;E=E->next()) { + for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) { - r_functions->push_back(E->get()+":"+itos(E->key())); + r_functions->push_back(E->get() + ":" + itos(E->key())); } - - } return true; @@ -112,142 +103,133 @@ bool GDScriptLanguage::has_named_classes() const { return false; } -int GDScriptLanguage::find_function(const String& p_function,const String& p_code) const { +int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const { GDTokenizerText tokenizer; tokenizer.set_code(p_code); - int indent=0; - while(tokenizer.get_token()!=GDTokenizer::TK_EOF && tokenizer.get_token()!=GDTokenizer::TK_ERROR) { + int indent = 0; + while (tokenizer.get_token() != GDTokenizer::TK_EOF && tokenizer.get_token() != GDTokenizer::TK_ERROR) { - if (tokenizer.get_token()==GDTokenizer::TK_NEWLINE) { - indent=tokenizer.get_token_line_indent(); + if (tokenizer.get_token() == GDTokenizer::TK_NEWLINE) { + indent = tokenizer.get_token_line_indent(); } //print_line("TOKEN: "+String(GDTokenizer::get_token_name(tokenizer.get_token()))); - if (indent==0 && tokenizer.get_token()==GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1)==GDTokenizer::TK_IDENTIFIER) { + if (indent == 0 && tokenizer.get_token() == GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1) == GDTokenizer::TK_IDENTIFIER) { String identifier = tokenizer.get_token_identifier(1); - if (identifier==p_function) { + if (identifier == p_function) { return tokenizer.get_token_line(); } } tokenizer.advance(); //print_line("NEXT: "+String(GDTokenizer::get_token_name(tokenizer.get_token()))); - } return -1; } Script *GDScriptLanguage::create_script() const { - return memnew( GDScript ); + return memnew(GDScript); } /* DEBUGGER FUNCTIONS */ - -bool GDScriptLanguage::debug_break_parse(const String& p_file, int p_line,const String& p_error) { +bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) { //break because of parse error - if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) { - - _debug_parse_err_line=p_line; - _debug_parse_err_file=p_file; - _debug_error=p_error; - ScriptDebugger::get_singleton()->debug(this,false); - return true; - } else { - return false; - } + if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) { + _debug_parse_err_line = p_line; + _debug_parse_err_file = p_file; + _debug_error = p_error; + ScriptDebugger::get_singleton()->debug(this, false); + return true; + } else { + return false; + } } -bool GDScriptLanguage::debug_break(const String& p_error,bool p_allow_continue) { - - if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) { +bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) { - _debug_parse_err_line=-1; - _debug_parse_err_file=""; - _debug_error=p_error; - ScriptDebugger::get_singleton()->debug(this,p_allow_continue); - return true; - } else { - return false; - } + if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) { + _debug_parse_err_line = -1; + _debug_parse_err_file = ""; + _debug_error = p_error; + ScriptDebugger::get_singleton()->debug(this, p_allow_continue); + return true; + } else { + return false; + } } String GDScriptLanguage::debug_get_error() const { - return _debug_error; + return _debug_error; } int GDScriptLanguage::debug_get_stack_level_count() const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return 1; - return _debug_call_stack_pos; } int GDScriptLanguage::debug_get_stack_level_line(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return _debug_parse_err_line; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,-1); + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1); - int l = _debug_call_stack_pos - p_level -1; - - return *(_call_stack[l].line); + int l = _debug_call_stack_pos - p_level - 1; + return *(_call_stack[l].line); } String GDScriptLanguage::debug_get_stack_level_function(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return ""; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,""); - int l = _debug_call_stack_pos - p_level -1; - return _call_stack[l].function->get_name(); + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, ""); + int l = _debug_call_stack_pos - p_level - 1; + return _call_stack[l].function->get_name(); } String GDScriptLanguage::debug_get_stack_level_source(int p_level) const { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return _debug_parse_err_file; - ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,""); - int l = _debug_call_stack_pos - p_level -1; - return _call_stack[l].function->get_source(); - + ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, ""); + int l = _debug_call_stack_pos - p_level - 1; + return _call_stack[l].function->get_source(); } -void GDScriptLanguage::debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return; - ERR_FAIL_INDEX(p_level,_debug_call_stack_pos); - int l = _debug_call_stack_pos - p_level -1; + ERR_FAIL_INDEX(p_level, _debug_call_stack_pos); + int l = _debug_call_stack_pos - p_level - 1; - GDFunction *f = _call_stack[l].function; + GDFunction *f = _call_stack[l].function; - List<Pair<StringName,int> > locals; + List<Pair<StringName, int> > locals; - f->debug_get_stack_member_state(*_call_stack[l].line,&locals); - for( List<Pair<StringName,int> >::Element *E = locals.front();E;E=E->next() ) { - - p_locals->push_back(E->get().first); - p_values->push_back(_call_stack[l].stack[E->get().second]); - } + f->debug_get_stack_member_state(*_call_stack[l].line, &locals); + for (List<Pair<StringName, int> >::Element *E = locals.front(); E; E = E->next()) { + p_locals->push_back(E->get().first); + p_values->push_back(_call_stack[l].stack[E->get().second]); + } } -void GDScriptLanguage::debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return; - ERR_FAIL_INDEX(p_level,_debug_call_stack_pos); - int l = _debug_call_stack_pos - p_level -1; - + ERR_FAIL_INDEX(p_level, _debug_call_stack_pos); + int l = _debug_call_stack_pos - p_level - 1; GDInstance *instance = _call_stack[l].instance; @@ -255,25 +237,23 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level,List<String> *p return; Ref<GDScript> script = instance->get_script(); - ERR_FAIL_COND( script.is_null() ); - + ERR_FAIL_COND(script.is_null()); - const Map<StringName,GDScript::MemberInfo>& mi = script->debug_get_member_indices(); + const Map<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices(); - for(const Map<StringName,GDScript::MemberInfo>::Element *E=mi.front();E;E=E->next()) { + for (const Map<StringName, GDScript::MemberInfo>::Element *E = mi.front(); E; E = E->next()) { p_members->push_back(E->key()); - p_values->push_back( instance->debug_get_member_by_index(E->get().index)); + p_values->push_back(instance->debug_get_member_by_index(E->get().index)); } - } -void GDScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) { +void GDScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { - //no globals are really reachable in gdscript + //no globals are really reachable in gdscript } -String GDScriptLanguage::debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems,int p_max_depth) { +String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { - if (_debug_parse_err_line>=0) + if (_debug_parse_err_line >= 0) return ""; return ""; } @@ -283,11 +263,9 @@ void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) con p_extensions->push_back("gd"); } - void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { - - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { p_functions->push_back(GDFunctions::get_info(GDFunctions::Function(i))); } @@ -295,33 +273,33 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const //not really "functions", but.. { MethodInfo mi; - mi.name="preload:Resource"; - mi.arguments.push_back(PropertyInfo(Variant::STRING,"path")); - mi.return_val=PropertyInfo(Variant::OBJECT,"",PROPERTY_HINT_RESOURCE_TYPE,"Resource"); + mi.name = "preload:Resource"; + mi.arguments.push_back(PropertyInfo(Variant::STRING, "path")); + mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "Resource"); p_functions->push_back(mi); } { MethodInfo mi; - mi.name="yield:GDFunctionState"; - mi.arguments.push_back(PropertyInfo(Variant::OBJECT,"object")); - mi.arguments.push_back(PropertyInfo(Variant::STRING,"signal")); + mi.name = "yield:GDFunctionState"; + mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object")); + mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal")); mi.default_arguments.push_back(Variant::NIL); mi.default_arguments.push_back(Variant::STRING); p_functions->push_back(mi); } { MethodInfo mi; - mi.name="assert"; - mi.arguments.push_back(PropertyInfo(Variant::BOOL,"condition")); + mi.name = "assert"; + mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition")); p_functions->push_back(mi); } } -void GDScriptLanguage::get_public_constants(List<Pair<String,Variant> > *p_constants) const { +void GDScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_constants) const { - Pair<String,Variant> pi; - pi.first="PI"; - pi.second=Math_PI; + Pair<String, Variant> pi; + pi.first = "PI"; + pi.second = Math_PI; p_constants->push_back(pi); Pair<String, Variant> infinity; @@ -335,22 +313,21 @@ void GDScriptLanguage::get_public_constants(List<Pair<String,Variant> > *p_const p_constants->push_back(nan); } -String GDScriptLanguage::make_function(const String& p_class,const String& p_name,const PoolStringArray& p_args) const { +String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { - String s="func "+p_name+"("; + String s = "func " + p_name + "("; if (p_args.size()) { - s+=" "; - for(int i=0;i<p_args.size();i++) { - if (i>0) - s+=", "; - s+=p_args[i].get_slice(":",0); + s += " "; + for (int i = 0; i < p_args.size(); i++) { + if (i > 0) + s += ", "; + s += p_args[i].get_slice(":", 0); } - s+=" "; + s += " "; } - s+="):\n\tpass # replace with function body\n"; + s += "):\n\tpass # replace with function body\n"; return s; - } #if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED) @@ -361,17 +338,14 @@ struct GDCompletionIdentifier { Ref<GDScript> script; Variant::Type type; Variant value; //im case there is a value, also return it - }; - - -static GDCompletionIdentifier _get_type_from_variant(const Variant& p_variant) { +static GDCompletionIdentifier _get_type_from_variant(const Variant &p_variant) { GDCompletionIdentifier t; - t.type=p_variant.get_type(); - t.value=p_variant; - if (p_variant.get_type()==Variant::OBJECT) { + t.type = p_variant.get_type(); + t.value = p_variant; + if (p_variant.get_type() == Variant::OBJECT) { Object *obj = p_variant; if (obj) { /* @@ -380,19 +354,19 @@ static GDCompletionIdentifier _get_type_from_variant(const Variant& p_variant) { t.value=Variant(); } else { */ - t.obj_type=obj->get_class(); + t.obj_type = obj->get_class(); //} } } return t; } -static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo& p_info) { +static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo &p_info) { GDCompletionIdentifier t; - t.type=p_info.type; - if (p_info.hint==PROPERTY_HINT_RESOURCE_TYPE) { - t.obj_type=p_info.hint_string; + t.type = p_info.type; + if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) { + t.obj_type = p_info.hint_string; } return t; } @@ -402,15 +376,11 @@ struct GDCompletionContext { const GDParser::ClassNode *_class; const GDParser::FunctionNode *function; const GDParser::BlockNode *block; - Object* base; + Object *base; String base_path; - }; - -static Ref<Reference> _get_parent_class(GDCompletionContext& context) { - - +static Ref<Reference> _get_parent_class(GDCompletionContext &context) { if (context._class->extends_used) { //do inheritance @@ -419,12 +389,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { Ref<GDScript> script; Ref<GDNativeClass> native; - if (path!="") { + if (path != "") { //path (and optionally subclasses) if (path.is_rel_path()) { - path=context.base_path.plus_file(path); + path = context.base_path.plus_file(path); } if (ScriptCodeCompletionCache::get_sigleton()) @@ -443,12 +413,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { if (context._class->extends_class.size()) { - for(int i=0;i<context._class->extends_class.size();i++) { + for (int i = 0; i < context._class->extends_class.size(); i++) { String sub = context._class->extends_class[i]; if (script->get_subclasses().has(sub)) { - script=script->get_subclasses()[sub]; + script = script->get_subclasses()[sub]; } else { return REF(); @@ -461,17 +431,16 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { } else { - if (context._class->extends_class.size()==0) { + if (context._class->extends_class.size() == 0) { ERR_PRINT("BUG"); return REF(); } - String base=context._class->extends_class[0]; + String base = context._class->extends_class[0]; - if (context._class->extends_class.size()>1) { + if (context._class->extends_class.size() > 1) { return REF(); - } //if not found, try engine classes if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) { @@ -482,22 +451,19 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) { int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base]; native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx]; return native; - } - } return Ref<Reference>(); } - -static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) { +static GDCompletionIdentifier _get_native_class(GDCompletionContext &context) { //eeh... GDCompletionIdentifier id; - id.type=Variant::NIL; + id.type = Variant::NIL; - REF pc = _get_parent_class(context); + REF pc = _get_parent_class(context); if (!pc.is_valid()) { return id; } @@ -507,204 +473,191 @@ static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) { if (s.is_null() && nc.is_null()) { return id; } - while(!s.is_null()) { - nc=s->get_native(); - s=s->get_base(); + while (!s.is_null()) { + nc = s->get_native(); + s = s->get_base(); } if (nc.is_null()) { return id; } - - - id.type=Variant::OBJECT; + id.type = Variant::OBJECT; if (context.base) - id.value=context.base; - id.obj_type=nc->get_name(); + id.value = context.base; + id.obj_type = nc->get_name(); return id; } -static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type); - +static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type); -static bool _guess_expression_type(GDCompletionContext& context,const GDParser::Node* p_node,int p_line,GDCompletionIdentifier &r_type) { +static bool _guess_expression_type(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, GDCompletionIdentifier &r_type) { + if (p_node->type == GDParser::Node::TYPE_CONSTANT) { - if (p_node->type==GDParser::Node::TYPE_CONSTANT) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_node); - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(p_node); - - r_type=_get_type_from_variant(cn->value); + r_type = _get_type_from_variant(cn->value); return true; - } else if (p_node->type==GDParser::Node::TYPE_DICTIONARY) { - - r_type.type=Variant::DICTIONARY; + } else if (p_node->type == GDParser::Node::TYPE_DICTIONARY) { + r_type.type = Variant::DICTIONARY; //what the heck, fill it anyway const GDParser::DictionaryNode *an = static_cast<const GDParser::DictionaryNode *>(p_node); Dictionary d; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { GDCompletionIdentifier k; - if (_guess_expression_type(context,an->elements[i].key,p_line,k) && k.value.get_type()!=Variant::NIL) { + if (_guess_expression_type(context, an->elements[i].key, p_line, k) && k.value.get_type() != Variant::NIL) { GDCompletionIdentifier v; - if (_guess_expression_type(context,an->elements[i].value,p_line,v)) { - d[k.value]=v.value; + if (_guess_expression_type(context, an->elements[i].value, p_line, v)) { + d[k.value] = v.value; } - } } - r_type.value=d; + r_type.value = d; return true; - } else if (p_node->type==GDParser::Node::TYPE_ARRAY) { + } else if (p_node->type == GDParser::Node::TYPE_ARRAY) { - r_type.type=Variant::ARRAY; + r_type.type = Variant::ARRAY; //what the heck, fill it anyway const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_node); Array arr; arr.resize(an->elements.size()); - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { GDCompletionIdentifier ci; - if (_guess_expression_type(context,an->elements[i],p_line,ci)) { - arr[i]=ci.value; + if (_guess_expression_type(context, an->elements[i], p_line, ci)) { + arr[i] = ci.value; } } - r_type.value=arr; + r_type.value = arr; return true; - } else if (p_node->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + } else if (p_node->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { - MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode*>(p_node)->function); - r_type=_get_type_from_pinfo(mi.return_val); + MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode *>(p_node)->function); + r_type = _get_type_from_pinfo(mi.return_val); return true; - } else if (p_node->type==GDParser::Node::TYPE_IDENTIFIER) { + } else if (p_node->type == GDParser::Node::TYPE_IDENTIFIER) { - return _guess_identifier_type(context,p_line-1,static_cast<const GDParser::IdentifierNode *>(p_node)->name,r_type); - } else if (p_node->type==GDParser::Node::TYPE_SELF) { + return _guess_identifier_type(context, p_line - 1, static_cast<const GDParser::IdentifierNode *>(p_node)->name, r_type); + } else if (p_node->type == GDParser::Node::TYPE_SELF) { //eeh... - r_type=_get_native_class(context); - return r_type.type!=Variant::NIL; - - } else if (p_node->type==GDParser::Node::TYPE_OPERATOR) { + r_type = _get_native_class(context); + return r_type.type != Variant::NIL; + } else if (p_node->type == GDParser::Node::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node); - if (op->op==GDParser::OperatorNode::OP_CALL) { - if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + if (op->op == GDParser::OperatorNode::OP_CALL) { + if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) { const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]); - r_type.type=tn->vtype; + r_type.type = tn->vtype; return true; - } else if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { - + } else if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { const GDParser::BuiltInFunctionNode *bin = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]); - return _guess_expression_type(context,bin,p_line,r_type); - - } else if (op->arguments.size()>1 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { + return _guess_expression_type(context, bin, p_line, r_type); + } else if (op->arguments.size() > 1 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { GDCompletionIdentifier base; - if (!_guess_expression_type(context,op->arguments[0],p_line,base)) + if (!_guess_expression_type(context, op->arguments[0], p_line, base)) return false; StringName id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name; - if (base.type==Variant::OBJECT) { + if (base.type == Variant::OBJECT) { - if (id.operator String()=="new" && base.value.get_type()==Variant::OBJECT) { + if (id.operator String() == "new" && base.value.get_type() == Variant::OBJECT) { Object *obj = base.value; if (obj && obj->cast_to<GDNativeClass>()) { GDNativeClass *gdnc = obj->cast_to<GDNativeClass>(); - r_type.type=Variant::OBJECT; - r_type.value=Variant(); - r_type.obj_type=gdnc->get_name(); + r_type.type = Variant::OBJECT; + r_type.value = Variant(); + r_type.obj_type = gdnc->get_name(); return true; } } - if (ClassDB::has_method(base.obj_type,id)) { + if (ClassDB::has_method(base.obj_type, id)) { #ifdef TOOLS_ENABLED - MethodBind *mb = ClassDB::get_method(base.obj_type,id); + MethodBind *mb = ClassDB::get_method(base.obj_type, id); PropertyInfo pi = mb->get_argument_info(-1); //try calling the function if constant and all args are constant, should not crash.. Object *baseptr = base.value; + if (mb->is_const() && pi.type == Variant::OBJECT) { - if (mb->is_const() && pi.type==Variant::OBJECT) { - - bool all_valid=true; + bool all_valid = true; Vector<Variant> args; - for(int i=2;i<op->arguments.size();i++) { + for (int i = 2; i < op->arguments.size(); i++) { GDCompletionIdentifier arg; - if (_guess_expression_type(context,op->arguments[i],p_line,arg)) { - if (arg.value.get_type()!=Variant::NIL && arg.value.get_type()!=Variant::OBJECT) { // calling with object seems dangerous, i don' t know + if (_guess_expression_type(context, op->arguments[i], p_line, arg)) { + if (arg.value.get_type() != Variant::NIL && arg.value.get_type() != Variant::OBJECT) { // calling with object seems dangerous, i don' t know args.push_back(arg.value); } else { - all_valid=false; + all_valid = false; break; } } else { - all_valid=false; + all_valid = false; } } - if (all_valid && String(id)=="get_node" && ClassDB::is_parent_class(base.obj_type,"Node") && args.size()) { + if (all_valid && String(id) == "get_node" && ClassDB::is_parent_class(base.obj_type, "Node") && args.size()) { - String arg1=args[0]; + String arg1 = args[0]; if (arg1.begins_with("/root/")) { - String which = arg1.get_slice("/",2); - if (which!="") { + String which = arg1.get_slice("/", 2); + if (which != "") { List<PropertyInfo> props; GlobalConfig::get_singleton()->get_property_list(&props); //print_line("find singleton"); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; //print_line("found "+s); - String name = s.get_slice("/",1); + String name = s.get_slice("/", 1); //print_line("name: "+name+", which: "+which); - if (name==which) { + if (name == which) { String script = GlobalConfig::get_singleton()->get(s); if (!script.begins_with("res://")) { - script="res://"+script; + script = "res://" + script; } if (!script.ends_with(".gd")) { //not a script, try find the script anyway, //may have some success - script=script.get_basename()+".gd"; + script = script.get_basename() + ".gd"; } if (FileAccess::exists(script)) { //print_line("is a script"); - Ref<Script> scr; if (ScriptCodeCompletionCache::get_sigleton()) scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script); else scr = ResourceLoader::load(script); - - r_type.obj_type="Node"; - r_type.type=Variant::OBJECT; - r_type.script=scr; - r_type.value=Variant(); + r_type.obj_type = "Node"; + r_type.type = Variant::OBJECT; + r_type.script = scr; + r_type.value = Variant(); return true; - } } } @@ -712,40 +665,34 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } } - - if (baseptr) { if (all_valid) { - Vector<const Variant*> argptr; - for(int i=0;i<args.size();i++) { + Vector<const Variant *> argptr; + for (int i = 0; i < args.size(); i++) { argptr.push_back(&args[i]); } Variant::CallError ce; - Variant ret=mb->call(baseptr,argptr.ptr(),argptr.size(),ce); + Variant ret = mb->call(baseptr, argptr.ptr(), argptr.size(), ce); + if (ce.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { - if (ce.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) { + if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != NULL) { - if (ret.get_type()!=Variant::OBJECT || ret.operator Object*()!=NULL) { - - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } - } } } - r_type.type=pi.type; - if (pi.hint==PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type=pi.hint_string; + r_type.type = pi.type; + if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) { + r_type.obj_type = pi.hint_string; } - - return true; #else return false; @@ -756,115 +703,108 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } else { //method for some variant.. Variant::CallError ce; - Variant v = Variant::construct(base.type,NULL,0,ce); + Variant v = Variant::construct(base.type, NULL, 0, ce); List<MethodInfo> mi; v.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { - - if (!E->get().name.begins_with("_") && E->get().name==id.operator String()) { + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { + if (!E->get().name.begins_with("_") && E->get().name == id.operator String()) { MethodInfo mi = E->get(); - r_type.type=mi.return_val.type; - if (mi.return_val.hint==PROPERTY_HINT_RESOURCE_TYPE) { - r_type.obj_type=mi.return_val.hint_string; + r_type.type = mi.return_val.type; + if (mi.return_val.hint == PROPERTY_HINT_RESOURCE_TYPE) { + r_type.obj_type = mi.return_val.hint_string; } return true; } } - } - - } - } else if (op->op==GDParser::OperatorNode::OP_INDEX || op->op==GDParser::OperatorNode::OP_INDEX_NAMED) { + } else if (op->op == GDParser::OperatorNode::OP_INDEX || op->op == GDParser::OperatorNode::OP_INDEX_NAMED) { GDCompletionIdentifier p1; GDCompletionIdentifier p2; + if (op->op == GDParser::OperatorNode::OP_INDEX_NAMED) { - - if (op->op==GDParser::OperatorNode::OP_INDEX_NAMED) { - - if (op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { - String id = static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name; - p2.type=Variant::STRING; - p2.value=id; + if (op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { + String id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name; + p2.type = Variant::STRING; + p2.value = id; } } else { if (op->arguments[1]) { - if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) { + if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { return false; } } } - if (op->arguments[0]->type==GDParser::Node::TYPE_ARRAY) { + if (op->arguments[0]->type == GDParser::Node::TYPE_ARRAY) { const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(op->arguments[0]); if (p2.value.is_num()) { int index = p2.value; - if (index<0 || index>=an->elements.size()) + if (index < 0 || index >= an->elements.size()) return false; - return _guess_expression_type(context,an->elements[index],p_line,r_type); + return _guess_expression_type(context, an->elements[index], p_line, r_type); } - } else if (op->arguments[0]->type==GDParser::Node::TYPE_DICTIONARY) { + } else if (op->arguments[0]->type == GDParser::Node::TYPE_DICTIONARY) { const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(op->arguments[0]); - if (p2.value.get_type()==Variant::NIL) + if (p2.value.get_type() == Variant::NIL) return false; - for(int i=0;i<dn->elements.size();i++) { + for (int i = 0; i < dn->elements.size(); i++) { GDCompletionIdentifier k; - if (!_guess_expression_type(context,dn->elements[i].key,p_line,k)) { + if (!_guess_expression_type(context, dn->elements[i].key, p_line, k)) { return false; } - if (k.value.get_type()==Variant::NIL) + if (k.value.get_type() == Variant::NIL) return false; - if (k.value==p2.value) { + if (k.value == p2.value) { - return _guess_expression_type(context,dn->elements[i].value,p_line,r_type); + return _guess_expression_type(context, dn->elements[i].value, p_line, r_type); } } } else { if (op->arguments[0]) { - if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) { + if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { return false; } - } - if (p1.value.get_type()==Variant::OBJECT) { + if (p1.value.get_type() == Variant::OBJECT) { //?? - } else if (p1.value.get_type()!=Variant::NIL) { + } else if (p1.value.get_type() != Variant::NIL) { bool valid; - Variant ret = p1.value.get(p2.value,&valid); + Variant ret = p1.value.get(p2.value, &valid); if (valid) { - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } else { - if (p1.type!=Variant::NIL) { + if (p1.type != Variant::NIL) { Variant::CallError ce; - Variant base = Variant::construct(p1.type,NULL,0,ce); + Variant base = Variant::construct(p1.type, NULL, 0, ce); bool valid; - Variant ret = base.get(p2.value,&valid); + Variant ret = base.get(p2.value, &valid); if (valid) { - r_type=_get_type_from_variant(ret); + r_type = _get_type_from_variant(ret); return true; } } @@ -873,127 +813,115 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser:: } else { - Variant::Operator vop = Variant::OP_MAX; - switch(op->op) { - case GDParser::OperatorNode::OP_ADD: vop=Variant::OP_ADD; break; - case GDParser::OperatorNode::OP_SUB: vop=Variant::OP_SUBSTRACT; break; - case GDParser::OperatorNode::OP_MUL: vop=Variant::OP_MULTIPLY; break; - case GDParser::OperatorNode::OP_DIV: vop=Variant::OP_DIVIDE; break; - case GDParser::OperatorNode::OP_MOD: vop=Variant::OP_MODULE; break; - case GDParser::OperatorNode::OP_SHIFT_LEFT: vop=Variant::OP_SHIFT_LEFT; break; - case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop=Variant::OP_SHIFT_RIGHT; break; - case GDParser::OperatorNode::OP_BIT_AND: vop=Variant::OP_BIT_AND; break; - case GDParser::OperatorNode::OP_BIT_OR: vop=Variant::OP_BIT_OR; break; - case GDParser::OperatorNode::OP_BIT_XOR: vop=Variant::OP_BIT_XOR; break; - default:{} - + switch (op->op) { + case GDParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break; + case GDParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBSTRACT; break; + case GDParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break; + case GDParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break; + case GDParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break; + case GDParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break; + case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break; + case GDParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break; + case GDParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break; + case GDParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break; + default: {} } - - - if (vop==Variant::OP_MAX) + if (vop == Variant::OP_MAX) return false; - - GDCompletionIdentifier p1; GDCompletionIdentifier p2; if (op->arguments[0]) { - if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) { + if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) { return false; } - } - if (op->arguments.size()>1) { - if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) { + if (op->arguments.size() > 1) { + if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) { return false; } } Variant::CallError ce; - bool v1_use_value = p1.value.get_type()!=Variant::NIL && p1.value.get_type()!=Variant::OBJECT; - Variant v1 = (v1_use_value)?p1.value:Variant::construct(p1.type,NULL,0,ce); - bool v2_use_value = p2.value.get_type()!=Variant::NIL && p2.value.get_type()!=Variant::OBJECT; - Variant v2 = (v2_use_value)?p2.value:Variant::construct(p2.type,NULL,0,ce); + bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT; + Variant v1 = (v1_use_value) ? p1.value : Variant::construct(p1.type, NULL, 0, ce); + bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT; + Variant v2 = (v2_use_value) ? p2.value : Variant::construct(p2.type, NULL, 0, ce); // avoid potential invalid ops - if ((vop==Variant::OP_DIVIDE || vop==Variant::OP_MODULE) && v2.get_type()==Variant::INT) { - v2=1; - v2_use_value=false; + if ((vop == Variant::OP_DIVIDE || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) { + v2 = 1; + v2_use_value = false; } - if (vop==Variant::OP_DIVIDE && v2.get_type()==Variant::REAL) { - v2=1.0; - v2_use_value=false; + if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::REAL) { + v2 = 1.0; + v2_use_value = false; } Variant r; bool valid; - Variant::evaluate(vop,v1,v2,r,valid); + Variant::evaluate(vop, v1, v2, r, valid); if (!valid) return false; - r_type.type=r.get_type(); + r_type.type = r.get_type(); if (v1_use_value && v2_use_value) - r_type.value=r; + r_type.value = r; return true; - } - } return false; } - -static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) { - +static bool _guess_identifier_type_in_block(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) { GDCompletionIdentifier gdi = _get_native_class(context); - if (gdi.obj_type!=StringName()) { + if (gdi.obj_type != StringName()) { bool valid; - Variant::Type t = ClassDB::get_property_type(gdi.obj_type,p_identifier,&valid); - if (t!=Variant::NIL && valid) { - r_type.type=t; + Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_identifier, &valid); + if (t != Variant::NIL && valid) { + r_type.type = t; return true; } } - const GDParser::Node *last_assign=NULL; - int last_assign_line=-1; + const GDParser::Node *last_assign = NULL; + int last_assign_line = -1; - for (int i=0;i<context.block->statements.size();i++) { + for (int i = 0; i < context.block->statements.size(); i++) { - if (context.block->statements[i]->line>p_line) + if (context.block->statements[i]->line > p_line) continue; + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) { - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); - if (lv->assign && lv->name==p_identifier) { + if (lv->assign && lv->name == p_identifier) { - last_assign=lv->assign; - last_assign_line=context.block->statements[i]->line; + last_assign = lv->assign; + last_assign_line = context.block->statements[i]->line; } } - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) { + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(context.block->statements[i]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { - if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) { + if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) { const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]); - if (id->name==p_identifier) { + if (id->name == p_identifier) { - last_assign=op->arguments[1]; - last_assign_line=context.block->statements[i]->line; + last_assign = op->arguments[1]; + last_assign_line = context.block->statements[i]->line; } } } @@ -1003,20 +931,18 @@ static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_l //use the last assignment, (then backwards?) if (last_assign) { - return _guess_expression_type(context,last_assign,last_assign_line,r_type); + return _guess_expression_type(context, last_assign, last_assign_line, r_type); } - return false; } +static bool _guess_identifier_from_assignment_in_function(GDCompletionContext &context, int p_src_line, const StringName &p_identifier, const StringName &p_function, GDCompletionIdentifier &r_type) { -static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& context, int p_src_line, const StringName& p_identifier, const StringName& p_function,GDCompletionIdentifier &r_type) { - - const GDParser::FunctionNode* func=NULL; - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==p_function) { - func=context._class->functions[i]; + const GDParser::FunctionNode *func = NULL; + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == p_function) { + func = context._class->functions[i]; break; } } @@ -1024,23 +950,23 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c if (!func) return false; - for(int i=0;i<func->body->statements.size();i++) { + for (int i = 0; i < func->body->statements.size(); i++) { if (func->body->statements[i]->line == p_src_line) { break; } - if (func->body->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) { + if (func->body->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) { const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->body->statements[i]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { - if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) { + if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) { const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]); - if (id->name==p_identifier) { + if (id->name == p_identifier) { - return _guess_expression_type(context,op->arguments[1],func->body->statements[i]->line,r_type); + return _guess_expression_type(context, op->arguments[1], func->body->statements[i]->line, r_type); } } } @@ -1050,66 +976,62 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c return false; } -static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) { +static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) { //go to block first + const GDParser::BlockNode *block = context.block; - const GDParser::BlockNode *block=context.block; - - while(block) { + while (block) { GDCompletionContext c = context; - c.block=block; + c.block = block; - if (_guess_identifier_type_in_block(c,p_line,p_identifier,r_type)) { + if (_guess_identifier_type_in_block(c, p_line, p_identifier, r_type)) { return true; } - block=block->parent_block; + block = block->parent_block; } //guess from argument if virtual - if (context.function && context.function->name!=StringName()) { + if (context.function && context.function->name != StringName()) { int argindex = -1; - for(int i=0;i<context.function->arguments.size();i++) { + for (int i = 0; i < context.function->arguments.size(); i++) { - if (context.function->arguments[i]==p_identifier) { - argindex=i; + if (context.function->arguments[i] == p_identifier) { + argindex = i; break; } - } - if (argindex!=-1) { - GDCompletionIdentifier id =_get_native_class(context); - if (id.type==Variant::OBJECT && id.obj_type!=StringName()) { + if (argindex != -1) { + GDCompletionIdentifier id = _get_native_class(context); + if (id.type == Variant::OBJECT && id.obj_type != StringName()) { //this kinda sucks but meh List<MethodInfo> vmethods; - ClassDB::get_virtual_methods(id.obj_type,&vmethods); - for (List<MethodInfo>::Element *E=vmethods.front();E;E=E->next()) { - + ClassDB::get_virtual_methods(id.obj_type, &vmethods); + for (List<MethodInfo>::Element *E = vmethods.front(); E; E = E->next()) { - if (E->get().name==context.function->name && argindex<E->get().arguments.size()) { + if (E->get().name == context.function->name && argindex < E->get().arguments.size()) { - PropertyInfo arg=E->get().arguments[argindex]; + PropertyInfo arg = E->get().arguments[argindex]; int scp = arg.name.find(":"); - if (scp!=-1) { + if (scp != -1) { - - r_type.type=Variant::OBJECT; - r_type.obj_type=arg.name.substr(scp+1,arg.name.length()); + r_type.type = Variant::OBJECT; + r_type.obj_type = arg.name.substr(scp + 1, arg.name.length()); return true; } else { - r_type.type=arg.type; - if (arg.hint==PROPERTY_HINT_RESOURCE_TYPE) - r_type.obj_type=arg.hint_string; + r_type.type = arg.type; + if (arg.hint == PROPERTY_HINT_RESOURCE_TYPE) + r_type.obj_type = arg.hint_string; return true; } } @@ -1120,40 +1042,40 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const //guess type in constant - for(int i=0;i<context._class->constant_expressions.size();i++) { + for (int i = 0; i < context._class->constant_expressions.size(); i++) { - if (context._class->constant_expressions[i].identifier==p_identifier) { + if (context._class->constant_expressions[i].identifier == p_identifier) { - ERR_FAIL_COND_V( context._class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT, false ); - r_type=_get_type_from_variant(static_cast<const GDParser::ConstantNode*>(context._class->constant_expressions[i].expression)->value ); + ERR_FAIL_COND_V(context._class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT, false); + r_type = _get_type_from_variant(static_cast<const GDParser::ConstantNode *>(context._class->constant_expressions[i].expression)->value); return true; } } if (!(context.function && context.function->_static)) { - for(int i=0;i<context._class->variables.size();i++) { + for (int i = 0; i < context._class->variables.size(); i++) { - if (context._class->variables[i].identifier==p_identifier) { + if (context._class->variables[i].identifier == p_identifier) { - if (context._class->variables[i]._export.type!=Variant::NIL) { + if (context._class->variables[i]._export.type != Variant::NIL) { - r_type=_get_type_from_pinfo(context._class->variables[i]._export); + r_type = _get_type_from_pinfo(context._class->variables[i]._export); return true; } else if (context._class->variables[i].expression) { - bool rtype = _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type); - if (rtype && r_type.type!=Variant::NIL) + bool rtype = _guess_expression_type(context, context._class->variables[i].expression, context._class->variables[i].line, r_type); + if (rtype && r_type.type != Variant::NIL) return true; //return _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type); } //try to guess from assignment in construtor or _ready - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_ready",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_ready", r_type)) return true; - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_enter_tree",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_enter_tree", r_type)) return true; - if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_init",r_type)) + if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_init", r_type)) return true; return false; @@ -1165,115 +1087,107 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const List<PropertyInfo> props; GlobalConfig::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - String name = s.get_slice("/",1); - if (name==String(p_identifier)) { + String name = s.get_slice("/", 1); + if (name == String(p_identifier)) { String path = GlobalConfig::get_singleton()->get(s); if (path.begins_with("*")) { - String script =path.substr(1,path.length()); + String script = path.substr(1, path.length()); if (!script.ends_with(".gd")) { //not a script, try find the script anyway, //may have some success - script=script.get_basename()+".gd"; + script = script.get_basename() + ".gd"; } if (FileAccess::exists(script)) { //print_line("is a script"); - Ref<Script> scr; if (ScriptCodeCompletionCache::get_sigleton()) scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script); else scr = ResourceLoader::load(script); - - r_type.obj_type="Node"; - r_type.type=Variant::OBJECT; - r_type.script=scr; - r_type.value=Variant(); + r_type.obj_type = "Node"; + r_type.type = Variant::OBJECT; + r_type.script = scr; + r_type.value = Variant(); return true; - } } } - } //global - for(Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) { - if (E->key()==p_identifier) { + for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { + if (E->key() == p_identifier) { - r_type=_get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]); + r_type = _get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]); return true; } - } return false; } - -static void _find_identifiers_in_block(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) { +static void _find_identifiers_in_block(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { if (p_only_functions) return; - for (int i=0;i<context.block->statements.size();i++) { + for (int i = 0; i < context.block->statements.size(); i++) { - if (context.block->statements[i]->line>p_line) + if (context.block->statements[i]->line > p_line) continue; + if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) { - if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]); result.insert(lv->name.operator String()); } } } -static void _find_identifiers_in_class(GDCompletionContext& context,bool p_static,bool p_only_functions,Set<String>& result) { +static void _find_identifiers_in_class(GDCompletionContext &context, bool p_static, bool p_only_functions, Set<String> &result) { if (!p_static && !p_only_functions) { - for(int i=0;i<context._class->variables.size();i++) { + for (int i = 0; i < context._class->variables.size(); i++) { result.insert(context._class->variables[i].identifier); } } if (!p_only_functions) { - for(int i=0;i<context._class->constant_expressions.size();i++) { + for (int i = 0; i < context._class->constant_expressions.size(); i++) { result.insert(context._class->constant_expressions[i].identifier); } - for(int i=0;i<context._class->subclasses.size();i++) { + for (int i = 0; i < context._class->subclasses.size(); i++) { result.insert(context._class->subclasses[i]->name); } - } - for(int i=0;i<context._class->static_functions.size();i++) { + for (int i = 0; i < context._class->static_functions.size(); i++) { if (context._class->static_functions[i]->arguments.size()) - result.insert(context._class->static_functions[i]->name.operator String()+"("); + result.insert(context._class->static_functions[i]->name.operator String() + "("); else - result.insert(context._class->static_functions[i]->name.operator String()+"()"); + result.insert(context._class->static_functions[i]->name.operator String() + "()"); } if (!p_static) { - for(int i=0;i<context._class->functions.size();i++) { + for (int i = 0; i < context._class->functions.size(); i++) { if (context._class->functions[i]->arguments.size()) - result.insert(context._class->functions[i]->name.operator String()+"("); + result.insert(context._class->functions[i]->name.operator String() + "("); else - result.insert(context._class->functions[i]->name.operator String()+"()"); + result.insert(context._class->functions[i]->name.operator String() + "()"); } } @@ -1281,135 +1195,130 @@ static void _find_identifiers_in_class(GDCompletionContext& context,bool p_stati Ref<Reference> base = _get_parent_class(context); - while(true) { + while (true) { Ref<GDScript> script = base; Ref<GDNativeClass> nc = base; if (script.is_valid()) { if (!p_static && !p_only_functions) { - for (const Set<StringName>::Element *E=script->get_members().front();E;E=E->next()) { + for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) { result.insert(E->get().operator String()); } } if (!p_only_functions) { - for (const Map<StringName,Variant>::Element *E=script->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { if (!p_static || E->get()->is_static()) { if (E->get()->get_argument_count()) - result.insert(E->key().operator String()+"("); + result.insert(E->key().operator String() + "("); else - result.insert(E->key().operator String()+"()"); + result.insert(E->key().operator String() + "()"); } } - if (!p_only_functions) { - for (const Map<StringName,Ref<GDScript> >::Element *E=script->get_subclasses().front();E;E=E->next()) { + if (!p_only_functions) { + for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - base=script->get_base(); + base = script->get_base(); if (base.is_null()) - base=script->get_native(); + base = script->get_native(); } else if (nc.is_valid()) { StringName type = nc->get_name(); if (!p_only_functions) { - List<String> constants; - ClassDB::get_integer_constant_list(type,&constants); - for(List<String>::Element *E=constants.front();E;E=E->next()) { + ClassDB::get_integer_constant_list(type, &constants); + for (List<String>::Element *E = constants.front(); E; E = E->next()) { result.insert(E->get()); } List<PropertyInfo> pinfo; - ClassDB::get_property_list(type,&pinfo); + ClassDB::get_property_list(type, &pinfo); - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - if (E->get().usage&(PROPERTY_USAGE_GROUP|PROPERTY_USAGE_CATEGORY)) + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) continue; - if (E->get().name.find("/")!=-1) + if (E->get().name.find("/") != -1) continue; result.insert(E->get().name); } - } List<MethodInfo> methods; - ClassDB::get_method_list(type,&methods); - for(List<MethodInfo>::Element *E=methods.front();E;E=E->next()) { + ClassDB::get_method_list(type, &methods); + for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { if (E->get().name.begins_with("_")) continue; if (E->get().arguments.size()) - result.insert(E->get().name+"("); + result.insert(E->get().name + "("); else - result.insert(E->get().name+"()"); + result.insert(E->get().name + "()"); } - - break; } else break; - } - } -static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) { +static void _find_identifiers(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) { - const GDParser::BlockNode *block=context.block; + const GDParser::BlockNode *block = context.block; if (context.function) { - const GDParser::FunctionNode* f = context.function; + const GDParser::FunctionNode *f = context.function; - for (int i=0;i<f->arguments.size();i++) { + for (int i = 0; i < f->arguments.size(); i++) { result.insert(f->arguments[i].operator String()); } } - while(block) { + while (block) { GDCompletionContext c = context; - c.block=block; + c.block = block; - _find_identifiers_in_block(c,p_line,p_only_functions,result); - block=block->parent_block; + _find_identifiers_in_block(c, p_line, p_only_functions, result); + block = block->parent_block; } - const GDParser::ClassNode *clss=context._class; + const GDParser::ClassNode *clss = context._class; - bool _static=context.function && context.function->_static; + bool _static = context.function && context.function->_static; - while(clss) { + while (clss) { GDCompletionContext c = context; - c._class=clss; - c.block=NULL; - c.function=NULL; - _find_identifiers_in_class(c,_static,p_only_functions,result); - clss=clss->owner; + c._class = clss; + c.block = NULL; + c.function = NULL; + _find_identifiers_in_class(c, _static, p_only_functions, result); + clss = clss->owner; } - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { result.insert(GDFunctions::get_func_name(GDFunctions::Function(i))); } - static const char*_type_names[Variant::VARIANT_MAX]={ - "null","bool","int","float","String","Vector2","Rect2","Vector3","Transform2D","Plane","Quat","AABB","Basis","Transform", - "Color","Image","NodePath","RID","Object","InputEvent","Dictionary","Array","RawArray","IntArray","FloatArray","StringArray", - "Vector2Array","Vector3Array","ColorArray"}; + static const char *_type_names[Variant::VARIANT_MAX] = { + "null", "bool", "int", "float", "String", "Vector2", "Rect2", "Vector3", "Transform2D", "Plane", "Quat", "AABB", "Basis", "Transform", + "Color", "Image", "NodePath", "RID", "Object", "InputEvent", "Dictionary", "Array", "RawArray", "IntArray", "FloatArray", "StringArray", + "Vector2Array", "Vector3Array", "ColorArray" + }; - for(int i=0;i<Variant::VARIANT_MAX;i++) { + for (int i = 0; i < Variant::VARIANT_MAX; i++) { result.insert(_type_names[i]); } @@ -1417,37 +1326,34 @@ static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_onl List<PropertyInfo> props; GlobalConfig::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - String name = s.get_slice("/",1); + String name = s.get_slice("/", 1); String path = GlobalConfig::get_singleton()->get(s); if (path.begins_with("*")) { result.insert(name); } - } - - for(const Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) { + for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { result.insert(E->key().operator String()); } } - -static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true) { +static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) { String n = p_info.name; int idx = n.find(":"); - if (idx!=-1) { - return n.substr(idx+1,n.length()); + if (idx != -1) { + return n.substr(idx + 1, n.length()); } - if (p_info.type==Variant::OBJECT && p_info.hint==PROPERTY_HINT_RESOURCE_TYPE) + if (p_info.type == Variant::OBJECT && p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) return p_info.hint_string; - if (p_info.type==Variant::NIL) { + if (p_info.type == Variant::NIL) { if (p_isarg) return "var"; else @@ -1457,74 +1363,68 @@ static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true) return Variant::get_type_name(p_info.type); } -static void _make_function_hint(const GDParser::FunctionNode* p_func,int p_argidx,String& arghint) { +static void _make_function_hint(const GDParser::FunctionNode *p_func, int p_argidx, String &arghint) { - arghint="func "+p_func->name+"("; - for (int i=0;i<p_func->arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = "func " + p_func->name + "("; + for (int i = 0; i < p_func->arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; + arghint += " "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=p_func->arguments[i].operator String(); - int deffrom = p_func->arguments.size()-p_func->default_values.size(); + arghint += p_func->arguments[i].operator String(); + int deffrom = p_func->arguments.size() - p_func->default_values.size(); - if (i>=deffrom) { - int defidx = deffrom-i; + if (i >= deffrom) { + int defidx = deffrom - i; - if (defidx>=0 && defidx<p_func->default_values.size()) { + if (defidx >= 0 && defidx < p_func->default_values.size()) { - if (p_func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) { - - const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]); - arghint+="="+cn->value.get_construct_string(); + if (p_func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) { + const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]); + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]); + arghint += "=" + cn->value.get_construct_string(); } } else { - } } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - if (p_func->arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (p_func->arguments.size() > 0) + arghint += " "; + arghint += ")"; } - -static void _find_type_arguments(GDCompletionContext& context,const GDParser::Node*p_node,int p_line,const StringName& p_method,const GDCompletionIdentifier& id, int p_argidx, Set<String>& result, String& arghint) { - +static void _find_type_arguments(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, const StringName &p_method, const GDCompletionIdentifier &id, int p_argidx, Set<String> &result, String &arghint) { //print_line("find type arguments?"); - if (id.type==Variant::INPUT_EVENT && String(p_method)=="is_action" && p_argidx==0) { + if (id.type == Variant::INPUT_EVENT && String(p_method) == "is_action" && p_argidx == 0) { List<PropertyInfo> pinfo; GlobalConfig::get_singleton()->get_property_list(&pinfo); - for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - const PropertyInfo &pi=E->get(); + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + const PropertyInfo &pi = E->get(); if (!pi.name.begins_with("input/")) continue; - String name = pi.name.substr(pi.name.find("/")+1,pi.name.length()); - result.insert("\""+name+"\""); + String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length()); + result.insert("\"" + name + "\""); } + } else if (id.type == Variant::OBJECT && id.obj_type != StringName()) { - } else if (id.type==Variant::OBJECT && id.obj_type!=StringName()) { - - - MethodBind *m = ClassDB::get_method(id.obj_type,p_method); + MethodBind *m = ClassDB::get_method(id.obj_type, p_method); if (!m) { //not in static method, see script @@ -1532,51 +1432,49 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No Ref<GDScript> on_script; if (id.value.get_type()) { - Object *obj=id.value; - + Object *obj = id.value; if (obj) { - GDScript *scr = obj->cast_to<GDScript>(); if (scr) { while (scr) { - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { - if (E->get()->is_static() && p_method==E->get()->get_name()) { - arghint="static func "+String(p_method)+"("; - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { + if (E->get()->is_static() && p_method == E->get()->get_name()) { + arghint = "static func " + String(p_method) + "("; + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += "var " + E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=")"; + arghint += ")"; return; //found } } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } else { - on_script=obj->get_script(); + on_script = obj->get_script(); } } } @@ -1584,7 +1482,7 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No //print_line("but it has a script?"); if (!on_script.is_valid() && id.script.is_valid()) { //print_line("yes"); - on_script=id.script; + on_script = id.script; } if (on_script.is_valid()) { @@ -1596,110 +1494,108 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No String code = scr->get_source_code(); //print_line("has source code!"); - if (code!="") { + if (code != "") { //if there is code, parse it. This way is slower but updates in real-time GDParser p; //Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); - Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false); + Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - if (err==OK) { + if (err == OK) { //print_line("checking the functions..."); //only if ok, otherwise use what is cached on the script //GDParser::ClassNode *base = p. const GDParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND(root->type!=GDParser::Node::TYPE_CLASS); + ERR_FAIL_COND(root->type != GDParser::Node::TYPE_CLASS); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); - const GDParser::FunctionNode* func=NULL; - bool st=false; + const GDParser::FunctionNode *func = NULL; + bool st = false; - for(int i=0;i<cl->functions.size();i++) { + for (int i = 0; i < cl->functions.size(); i++) { //print_line(String(cl->functions[i]->name)+" vs "+String(p_method)); - if (cl->functions[i]->name==p_method) { - func=cl->functions[i]; + if (cl->functions[i]->name == p_method) { + func = cl->functions[i]; } } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { //print_line(String(cl->static_functions[i]->name)+" vs "+String(p_method)); - if (cl->static_functions[i]->name==p_method) { - func=cl->static_functions[i]; - st=true; + if (cl->static_functions[i]->name == p_method) { + func = cl->static_functions[i]; + st = true; } - } if (func) { - arghint="func "+String(p_method)+"("; + arghint = "func " + String(p_method) + "("; if (st) - arghint="static "+arghint; - for(int i=0;i<func->arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = "static " + arghint; + for (int i = 0; i < func->arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+String(func->arguments[i]); - int deffrom = func->arguments.size()-func->default_values.size(); - if (i>=deffrom) { + arghint += "var " + String(func->arguments[i]); + int deffrom = func->arguments.size() - func->default_values.size(); + if (i >= deffrom) { - int defidx = deffrom-i; + int defidx = deffrom - i; - if (defidx>=0 && defidx<func->default_values.size() && func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) { - const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]); - if (op->op==GDParser::OperatorNode::OP_ASSIGN) { - const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]); - arghint+="="+cn->value.get_construct_string(); + if (defidx >= 0 && defidx < func->default_values.size() && func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) { + const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]); + if (op->op == GDParser::OperatorNode::OP_ASSIGN) { + const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]); + arghint += "=" + cn->value.get_construct_string(); } } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=" )"; + arghint += " )"; return; } } else { //print_line("failed parsing?"); - code=""; + code = ""; } - } - if (code=="") { + if (code == "") { - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { - if (p_method==E->get()->get_name()) { - arghint="func "+String(p_method)+"("; - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { + if (p_method == E->get()->get_name()) { + arghint = "func " + String(p_method) + "("; + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+="var "+E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += "var " + E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } } - arghint+=")"; + arghint += ")"; return; //found } } @@ -1721,46 +1617,43 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } } - } else { //regular method - if (p_method.operator String()=="connect") { - + if (p_method.operator String() == "connect") { - if (p_argidx==0) { + if (p_argidx == 0) { List<MethodInfo> sigs; - ClassDB::get_signal_list(id.obj_type,&sigs); + ClassDB::get_signal_list(id.obj_type, &sigs); if (id.script.is_valid()) { id.script->get_script_signal_list(&sigs); - } else if (id.value.get_type()==Variant::OBJECT) { + } else if (id.value.get_type() == Variant::OBJECT) { Object *obj = id.value; if (obj && !obj->get_script().is_null()) { - Ref<Script> scr=obj->get_script(); + Ref<Script> scr = obj->get_script(); if (scr.is_valid()) { scr->get_script_signal_list(&sigs); } } } - for (List<MethodInfo>::Element *E=sigs.front();E;E=E->next()) { - result.insert("\""+E->get().name+"\""); + for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) { + result.insert("\"" + E->get().name + "\""); } - } else if (p_argidx==2){ - + } else if (p_argidx == 2) { if (context._class) { - for(int i=0;i<context._class->functions.size();i++) { - result.insert("\""+context._class->functions[i]->name+"\""); + for (int i = 0; i < context._class->functions.size(); i++) { + result.insert("\"" + context._class->functions[i]->name + "\""); } } } @@ -1773,173 +1666,163 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No }*/ } else { - if (p_argidx==0 && (String(p_method)=="get_node" || String(p_method)=="has_node") && ClassDB::is_parent_class(id.obj_type,"Node")) { + if (p_argidx == 0 && (String(p_method) == "get_node" || String(p_method) == "has_node") && ClassDB::is_parent_class(id.obj_type, "Node")) { List<PropertyInfo> props; GlobalConfig::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; //print_line("found "+s); - String name = s.get_slice("/",1); - result.insert("\"/root/"+name+"\""); + String name = s.get_slice("/", 1); + result.insert("\"/root/" + name + "\""); } } - Object *obj=id.value; + Object *obj = id.value; if (obj) { List<String> options; - obj->get_argument_options(p_method,p_argidx,&options); + obj->get_argument_options(p_method, p_argidx, &options); - for(List<String>::Element *E=options.front();E;E=E->next()) { + for (List<String>::Element *E = options.front(); E; E = E->next()) { result.insert(E->get()); } } - } - arghint = _get_visual_datatype(m->get_argument_info(-1),false)+" "+p_method.operator String()+String("("); + arghint = _get_visual_datatype(m->get_argument_info(-1), false) + " " + p_method.operator String() + String("("); - for(int i=0;i<m->get_argument_count();i++) { - if (i>0) - arghint+=", "; + for (int i = 0; i < m->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; + arghint += " "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } String n = m->get_argument_info(i).name; int dp = n.find(":"); - if (dp!=-1) - n=n.substr(0,dp); - arghint+=_get_visual_datatype(m->get_argument_info(i))+" "+n; - int deffrom = m->get_argument_count()-m->get_default_argument_count(); + if (dp != -1) + n = n.substr(0, dp); + arghint += _get_visual_datatype(m->get_argument_info(i)) + " " + n; + int deffrom = m->get_argument_count() - m->get_default_argument_count(); + if (i >= deffrom) { + int defidx = i - deffrom; - if (i>=deffrom) { - int defidx = i-deffrom; - - if (defidx>=0 && defidx<m->get_default_argument_count()) { - Variant v= m->get_default_argument(i); - arghint+="="+v.get_construct_string(); + if (defidx >= 0 && defidx < m->get_default_argument_count()) { + Variant v = m->get_default_argument(i); + arghint += "=" + v.get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (m->get_argument_count()>0) - arghint+=" "; - + if (m->get_argument_count() > 0) + arghint += " "; - arghint+=")"; + arghint += ")"; } - } } +static void _find_call_arguments(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, int p_argidx, Set<String> &result, String &arghint) { -static void _find_call_arguments(GDCompletionContext& context,const GDParser::Node* p_node, int p_line,int p_argidx, Set<String>& result, String& arghint) { - - - - if (!p_node || p_node->type!=GDParser::Node::TYPE_OPERATOR) { + if (!p_node || p_node->type != GDParser::Node::TYPE_OPERATOR) { return; } const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node); - if (op->op!=GDParser::OperatorNode::OP_CALL) { + if (op->op != GDParser::OperatorNode::OP_CALL) { return; } - if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) { + if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) { //complete built-in function - const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode*>(op->arguments[0]); + const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]); MethodInfo mi = GDFunctions::get_info(fn->function); - arghint = _get_visual_datatype(mi.return_val,false)+" "+GDFunctions::get_func_name(fn->function)+String("("); - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint = _get_visual_datatype(mi.return_val, false) + " " + GDFunctions::get_func_name(fn->function) + String("("); + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (mi.arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (mi.arguments.size() > 0) + arghint += " "; + arghint += ")"; - } else if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) { + } else if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) { //complete constructor - const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode*>(op->arguments[0]); + const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]); List<MethodInfo> mil; - Variant::get_constructor_list(tn->vtype,&mil); + Variant::get_constructor_list(tn->vtype, &mil); - for(List<MethodInfo>::Element *E=mil.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = mil.front(); E; E = E->next()) { MethodInfo mi = E->get(); - if (mi.arguments.size()==0) + if (mi.arguments.size() == 0) continue; if (E->prev()) - arghint+="\n"; - arghint += Variant::get_type_name(tn->vtype)+" "+Variant::get_type_name(tn->vtype)+String("("); - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - arghint+=", "; + arghint += "\n"; + arghint += Variant::get_type_name(tn->vtype) + " " + Variant::get_type_name(tn->vtype) + String("("); + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (mi.arguments.size()>0) - arghint+=" "; - arghint+=")"; + if (mi.arguments.size() > 0) + arghint += " "; + arghint += ")"; } - } else if (op->arguments.size()>=2 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) { + } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) { //make sure identifier exists... - const GDParser::IdentifierNode *id=static_cast<const GDParser::IdentifierNode *>(op->arguments[1]); + const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1]); - if (op->arguments[0]->type==GDParser::Node::TYPE_SELF) { + if (op->arguments[0]->type == GDParser::Node::TYPE_SELF) { //self, look up - for(int i=0;i<context._class->static_functions.size();i++) { - if (context._class->static_functions[i]->name==id->name) { - _make_function_hint(context._class->static_functions[i],p_argidx,arghint); + for (int i = 0; i < context._class->static_functions.size(); i++) { + if (context._class->static_functions[i]->name == id->name) { + _make_function_hint(context._class->static_functions[i], p_argidx, arghint); return; } } if (context.function && !context.function->_static) { - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==id->name) { - _make_function_hint(context._class->functions[i],p_argidx,arghint); + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == id->name) { + _make_function_hint(context._class->functions[i], p_argidx, arghint); return; } } @@ -1947,64 +1830,61 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No Ref<Reference> base = _get_parent_class(context); - while(true) { + while (true) { Ref<GDScript> script = base; Ref<GDNativeClass> nc = base; if (script.is_valid()) { + for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) { - for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) { - - if (E->key()==id->name) { + if (E->key() == id->name) { if (context.function && context.function->_static && !E->get()->is_static()) continue; - - arghint = "func "+id->name.operator String()+String("("); - for(int i=0;i<E->get()->get_argument_count();i++) { - if (i>0) - arghint+=", "; + arghint = "func " + id->name.operator String() + String("("); + for (int i = 0; i < E->get()->get_argument_count(); i++) { + if (i > 0) + arghint += ", "; else - arghint+=" "; - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + arghint += " "; + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - arghint+=E->get()->get_argument_name(i); - int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count(); - if (i>=deffrom) { - int defidx = deffrom-i; - if (defidx>=0 && defidx<E->get()->get_default_argument_count()) { - arghint+="="+E->get()->get_default_argument(defidx).get_construct_string(); + arghint += E->get()->get_argument_name(i); + int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count(); + if (i >= deffrom) { + int defidx = deffrom - i; + if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) { + arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string(); } } - if (i==p_argidx) { - arghint+=String::chr(0xFFFF); + if (i == p_argidx) { + arghint += String::chr(0xFFFF); } - } - if (E->get()->get_argument_count()>0) - arghint+=" "; - arghint+=")"; + if (E->get()->get_argument_count() > 0) + arghint += " "; + arghint += ")"; return; } } - base=script->get_base(); + base = script->get_base(); if (base.is_null()) - base=script->get_native(); + base = script->get_native(); } else if (nc.is_valid()) { if (context.function && !context.function->_static) { GDCompletionIdentifier ci; - ci.type=Variant::OBJECT; - ci.obj_type=nc->get_name(); + ci.type = Variant::OBJECT; + ci.obj_type = nc->get_name(); if (!context._class->owner) - ci.value=context.base; + ci.value = context.base; - _find_type_arguments(context,p_node,p_line,id->name,ci,p_argidx,result,arghint); + _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, arghint); //guess type.. /* List<MethodInfo> methods; @@ -2019,20 +1899,17 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No break; } else break; - } } else { //indexed lookup GDCompletionIdentifier ci; - if (_guess_expression_type(context,op->arguments[0],p_line,ci)) { + if (_guess_expression_type(context, op->arguments[0], p_line, ci)) { - _find_type_arguments(context,p_node,p_line,id->name,ci,p_argidx,result,arghint); + _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, arghint); return; } - } - } #if 0 bool _static=context.function->_static; @@ -2127,42 +2004,40 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No } #endif - } -Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { GDParser p; - p.parse(p_code,p_base_path,false,"",true); - bool isfunction=false; + p.parse(p_code, p_base_path, false, "", true); + bool isfunction = false; Set<String> options; GDCompletionContext context; - context._class=p.get_completion_class(); - context.block=p.get_completion_block(); - context.function=p.get_completion_function(); - context.base=p_owner; - context.base_path=p_base_path; + context._class = p.get_completion_class(); + context.block = p.get_completion_block(); + context.function = p.get_completion_function(); + context.base = p_owner; + context.base_path = p_base_path; - switch(p.get_completion_type()) { + switch (p.get_completion_type()) { case GDParser::COMPLETION_NONE: { } break; case GDParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { List<StringName> constants; - Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(),&constants); - for(List<StringName>::Element *E=constants.front();E;E=E->next()) { + Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(), &constants); + for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { options.insert(E->get().operator String()); } - } break; case GDParser::COMPLETION_FUNCTION: - isfunction=true; + isfunction = true; case GDParser::COMPLETION_IDENTIFIER: { - _find_identifiers(context,p.get_completion_line(),isfunction,options); + _find_identifiers(context, p.get_completion_line(), isfunction, options); } break; case GDParser::COMPLETION_PARENT_FUNCTION: { @@ -2171,98 +2046,91 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base if (p_owner) { List<String> opts; - p_owner->get_argument_options("get_node",0,&opts); + p_owner->get_argument_options("get_node", 0, &opts); - for (List<String>::Element *E=opts.front();E;E=E->next()) { + for (List<String>::Element *E = opts.front(); E; E = E->next()) { String opt = E->get().strip_edges(); if (opt.begins_with("\"") && opt.ends_with("\"")) { - String idopt=opt.substr(1,opt.length()-2); - if (idopt.replace("/","_").is_valid_identifier()) { + String idopt = opt.substr(1, opt.length() - 2); + if (idopt.replace("/", "_").is_valid_identifier()) { options.insert(idopt); } else { options.insert(opt); } } } - } } break; case GDParser::COMPLETION_METHOD: - isfunction=true; + isfunction = true; case GDParser::COMPLETION_INDEX: { const GDParser::Node *node = p.get_completion_node(); - if (node->type!=GDParser::Node::TYPE_OPERATOR) + if (node->type != GDParser::Node::TYPE_OPERATOR) break; - - - GDCompletionIdentifier t; - if (_guess_expression_type(context,static_cast<const GDParser::OperatorNode *>(node)->arguments[0],p.get_completion_line(),t)) { + if (_guess_expression_type(context, static_cast<const GDParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) { - if (t.type==Variant::OBJECT && t.obj_type=="GDNativeClass") { + if (t.type == Variant::OBJECT && t.obj_type == "GDNativeClass") { //native enum Ref<GDNativeClass> gdn = t.value; if (gdn.is_valid()) { StringName cn = gdn->get_name(); List<String> cnames; - ClassDB::get_integer_constant_list(cn,&cnames); - for (List<String>::Element *E=cnames.front();E;E=E->next()) { + ClassDB::get_integer_constant_list(cn, &cnames); + for (List<String>::Element *E = cnames.front(); E; E = E->next()) { options.insert(E->get()); } List<PropertyInfo> pinfo; - ClassDB::get_property_list(cn,&pinfo); + ClassDB::get_property_list(cn, &pinfo); - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - if (E->get().usage&(PROPERTY_USAGE_GROUP|PROPERTY_USAGE_CATEGORY)) + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) continue; - if (E->get().name.find("/")!=-1) + if (E->get().name.find("/") != -1) continue; options.insert(E->get().name); } } - } else if (t.type==Variant::OBJECT && t.obj_type!=StringName()) { + } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) { Ref<GDScript> on_script; if (t.value.get_type()) { - Object *obj=t.value; - + Object *obj = t.value; if (obj) { - GDScript *scr = obj->cast_to<GDScript>(); if (scr) { while (scr) { if (!isfunction) { - for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { options.insert(E->key()); } } - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { if (E->get()->is_static()) options.insert(E->key()); } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } else { - on_script=obj->get_script(); + on_script = obj->get_script(); } } } - if (!on_script.is_valid() && t.script.is_valid()) { - on_script=t.script; + on_script = t.script; } if (on_script.is_valid()) { @@ -2273,132 +2141,119 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base String code = scr->get_source_code(); - if (code!="") { + if (code != "") { //if there is code, parse it. This way is slower but updates in real-time GDParser p; - Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false); + Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false); - if (err==OK) { + if (err == OK) { //only if ok, otherwise use what is cached on the script //GDParser::ClassNode *base = p. const GDParser::Node *root = p.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_PARSE_ERROR); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_PARSE_ERROR); - const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root); - for(int i=0;i<cl->functions.size();i++) { + for (int i = 0; i < cl->functions.size(); i++) { if (cl->functions[i]->arguments.size()) - options.insert(String(cl->functions[i]->name)+"("); + options.insert(String(cl->functions[i]->name) + "("); else - options.insert(String(cl->functions[i]->name)+"()"); + options.insert(String(cl->functions[i]->name) + "()"); } - for(int i=0;i<cl->static_functions.size();i++) { + for (int i = 0; i < cl->static_functions.size(); i++) { if (cl->static_functions[i]->arguments.size()) - options.insert(String(cl->static_functions[i]->name)+"("); + options.insert(String(cl->static_functions[i]->name) + "("); else - options.insert(String(cl->static_functions[i]->name)+"()"); - + options.insert(String(cl->static_functions[i]->name) + "()"); } if (!isfunction) { - for(int i=0;i<cl->variables.size();i++) { + for (int i = 0; i < cl->variables.size(); i++) { options.insert(String(cl->variables[i].identifier)); } - for(int i=0;i<cl->constant_expressions.size();i++) { + for (int i = 0; i < cl->constant_expressions.size(); i++) { options.insert(String(cl->constant_expressions[i].identifier)); } - } - } else { - code=""; //well, then no code + code = ""; //well, then no code } - } - if (code=="") { + if (code == "") { //use class directly, no code was found if (!isfunction) { - for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) { + for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) { options.insert(E->key()); } } - for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) { if (E->get()->get_argument_count()) - options.insert(String(E->key())+"()"); + options.insert(String(E->key()) + "()"); else - options.insert(String(E->key())+"("); - + options.insert(String(E->key()) + "("); } - for (const Set<StringName>::Element *E=scr->get_members().front();E;E=E->next()) { + for (const Set<StringName>::Element *E = scr->get_members().front(); E; E = E->next()) { options.insert(E->get()); } } if (scr->get_base().is_valid()) - scr=scr->get_base().ptr(); + scr = scr->get_base().ptr(); else - scr=NULL; + scr = NULL; } } } - - - - - if (!isfunction) { - ClassDB::get_integer_constant_list(t.obj_type,r_options); + ClassDB::get_integer_constant_list(t.obj_type, r_options); List<PropertyInfo> pinfo; - ClassDB::get_property_list(t.obj_type,&pinfo); + ClassDB::get_property_list(t.obj_type, &pinfo); - for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { - if (E->get().usage&(PROPERTY_USAGE_GROUP|PROPERTY_USAGE_CATEGORY)) + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) continue; - if (E->get().name.find("/")!=-1) + if (E->get().name.find("/") != -1) continue; r_options->push_back(E->get().name); } } - List<MethodInfo> mi; - ClassDB::get_method_list(t.obj_type,&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { + ClassDB::get_method_list(t.obj_type, &mi); + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { if (E->get().name.begins_with("_")) continue; if (E->get().arguments.size()) - options.insert(E->get().name+"("); + options.insert(E->get().name + "("); else - options.insert(E->get().name+"()"); - + options.insert(E->get().name + "()"); } } else { - - if (t.type==Variant::INPUT_EVENT) { + if (t.type == Variant::INPUT_EVENT) { //this is hardcoded otherwise it's not obvious Set<String> exclude; - for(int i=0;i<InputEvent::TYPE_MAX;i++) { + for (int i = 0; i < InputEvent::TYPE_MAX; i++) { InputEvent ie; - ie.type=InputEvent::Type(i); - static const char*evnames[]={ + ie.type = InputEvent::Type(i); + static const char *evnames[] = { "# Common", "# Key", "# MouseMotion", @@ -2414,22 +2269,20 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base Variant v = ie; - if (i==0) { + if (i == 0) { List<MethodInfo> mi; v.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { - r_options->push_back(E->get().name+"("); - + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { + r_options->push_back(E->get().name + "("); } - } List<PropertyInfo> pi; v.get_property_list(&pi); - for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) { - if (i==0) + if (i == 0) exclude.insert(E->get().name); else if (exclude.has(E->get().name)) continue; @@ -2439,67 +2292,64 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base } return OK; } else { - if (t.value.get_type()==Variant::NIL) { + if (t.value.get_type() == Variant::NIL) { Variant::CallError ce; - t.value=Variant::construct(t.type,NULL,0,ce); + t.value = Variant::construct(t.type, NULL, 0, ce); } - if (!isfunction) { List<PropertyInfo> pl; t.value.get_property_list(&pl); - for (List<PropertyInfo>::Element *E=pl.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) { - if (E->get().name.find("/")==-1) + if (E->get().name.find("/") == -1) options.insert(E->get().name); } } List<MethodInfo> mi; t.value.get_method_list(&mi); - for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) { + for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) { if (E->get().arguments.size()) - options.insert(E->get().name+"("); + options.insert(E->get().name + "("); else - options.insert(E->get().name+"()"); - + options.insert(E->get().name + "()"); } } } } - } break; case GDParser::COMPLETION_CALL_ARGUMENTS: { - _find_call_arguments(context,p.get_completion_node(),p.get_completion_line(),p.get_completion_argument_index(),options,r_call_hint); + _find_call_arguments(context, p.get_completion_node(), p.get_completion_line(), p.get_completion_argument_index(), options, r_call_hint); } break; case GDParser::COMPLETION_VIRTUAL_FUNC: { GDCompletionIdentifier cid = _get_native_class(context); - if (cid.obj_type!=StringName()) { + if (cid.obj_type != StringName()) { List<MethodInfo> vm; - ClassDB::get_virtual_methods(cid.obj_type,&vm); - for(List<MethodInfo>::Element *E=vm.front();E;E=E->next()) { + ClassDB::get_virtual_methods(cid.obj_type, &vm); + for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) { - MethodInfo &mi=E->get(); + MethodInfo &mi = E->get(); String m = mi.name; - if (m.find(":")!=-1) - m=m.substr(0,m.find(":")); - m+="("; + if (m.find(":") != -1) + m = m.substr(0, m.find(":")); + m += "("; if (mi.arguments.size()) { - for(int i=0;i<mi.arguments.size();i++) { - if (i>0) - m+=", "; - String n =mi.arguments[i].name; - if (n.find(":")!=-1) - n=n.substr(0,n.find(":")); - m+=n; + for (int i = 0; i < mi.arguments.size(); i++) { + if (i > 0) + m += ", "; + String n = mi.arguments[i].name; + if (n.find(":") != -1) + n = n.substr(0, n.find(":")); + m += n; } } - m+="):"; + m += "):"; options.insert(m); } @@ -2510,24 +2360,22 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base const GDParser::Node *node = p.get_completion_node(); GDCompletionIdentifier t; - if (!_guess_expression_type(context,node,p.get_completion_line(),t)) + if (!_guess_expression_type(context, node, p.get_completion_line(), t)) break; - if (t.type==Variant::OBJECT && t.obj_type!=StringName()) { + if (t.type == Variant::OBJECT && t.obj_type != StringName()) { List<MethodInfo> sigs; - ClassDB::get_signal_list(t.obj_type,&sigs); - for (List<MethodInfo>::Element *E=sigs.front();E;E=E->next()) { - options.insert("\""+E->get().name+"\""); + ClassDB::get_signal_list(t.obj_type, &sigs); + for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) { + options.insert("\"" + E->get().name + "\""); } } } break; - } - - for(Set<String>::Element *E=options.front();E;E=E->next()) { + for (Set<String>::Element *E = options.front(); E; E = E->next()) { r_options->push_back(E->get()); } @@ -2536,25 +2384,23 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base #else -Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) { +Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return OK; } #endif - -void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const { - +void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const { Vector<String> lines = p_code.split("\n"); List<int> indent_stack; - for(int i=0;i<lines.size();i++) { + for (int i = 0; i < lines.size(); i++) { String l = lines[i]; - int tc=0; - for(int j=0;j<l.length();j++) { - if (l[j]==' ' || l[j]=='\t') { + int tc = 0; + for (int j = 0; j < l.length(); j++) { + if (l[j] == ' ' || l[j] == '\t') { tc++; } else { @@ -2562,252 +2408,237 @@ void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_ } } - - String st = l.substr(tc,l.length()).strip_edges(); - if (st=="" || st.begins_with("#")) + String st = l.substr(tc, l.length()).strip_edges(); + if (st == "" || st.begins_with("#")) continue; //ignore! - int ilevel=0; + int ilevel = 0; if (indent_stack.size()) { - ilevel=indent_stack.back()->get(); + ilevel = indent_stack.back()->get(); } - if (tc>ilevel) { + if (tc > ilevel) { indent_stack.push_back(tc); - } else if (tc<ilevel) { - while(indent_stack.size() && indent_stack.back()->get()>tc) { + } else if (tc < ilevel) { + while (indent_stack.size() && indent_stack.back()->get() > tc) { indent_stack.pop_back(); } - if (indent_stack.size() && indent_stack.back()->get()!=tc) + if (indent_stack.size() && indent_stack.back()->get() != tc) indent_stack.push_back(tc); //this is not right but gets the job done } - if (i>=p_from_line) { + if (i >= p_from_line) { - l=""; - for(int j=0;j<indent_stack.size();j++) - l+="\t"; - l+=st; + l = ""; + for (int j = 0; j < indent_stack.size(); j++) + l += "\t"; + l += st; - - } else if (i>p_to_line) { + } else if (i > p_to_line) { break; } //print_line(itos(indent_stack.size())+","+itos(tc)+": "+l); - lines[i]=l; + lines[i] = l; } - p_code=""; - for(int i=0;i<lines.size();i++) { - if (i>0) - p_code+="\n"; - p_code+=lines[i]; + p_code = ""; + for (int i = 0; i < lines.size(); i++) { + if (i > 0) + p_code += "\n"; + p_code += lines[i]; } - } #ifdef TOOLS_ENABLED -Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol,const String& p_base_path, Object*p_owner,LookupResult& r_result) { - +Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) { //before parsing, try the usual stuff if (ClassDB::class_exists(p_symbol)) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS; - r_result.class_name=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; + r_result.class_name = p_symbol; return OK; } - for(int i=0;i<Variant::VARIANT_MAX;i++) { + for (int i = 0; i < Variant::VARIANT_MAX; i++) { Variant::Type t = Variant::Type(i); - if (Variant::get_type_name(t)==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS; - r_result.class_name=Variant::get_type_name(t); + if (Variant::get_type_name(t) == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; + r_result.class_name = Variant::get_type_name(t); return OK; } } - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { - if (GDFunctions::get_func_name(GDFunctions::Function(i))==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name="@GDScript"; - r_result.class_member=p_symbol; + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { + if (GDFunctions::get_func_name(GDFunctions::Function(i)) == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = "@GDScript"; + r_result.class_member = p_symbol; return OK; } } GDParser p; - p.parse(p_code,p_base_path,false,"",true); + p.parse(p_code, p_base_path, false, "", true); - if (p.get_completion_type()==GDParser::COMPLETION_NONE) + if (p.get_completion_type() == GDParser::COMPLETION_NONE) return ERR_CANT_RESOLVE; GDCompletionContext context; - context._class=p.get_completion_class(); - context.block=p.get_completion_block(); - context.function=p.get_completion_function(); - context.base=p_owner; - context.base_path=p_base_path; - bool isfunction=false; + context._class = p.get_completion_class(); + context.block = p.get_completion_block(); + context.function = p.get_completion_function(); + context.base = p_owner; + context.base_path = p_base_path; + bool isfunction = false; - switch(p.get_completion_type()) { + switch (p.get_completion_type()) { case GDParser::COMPLETION_GET_NODE: case GDParser::COMPLETION_NONE: { } break; case GDParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name=Variant::get_type_name(p.get_completion_built_in_constant()); - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = Variant::get_type_name(p.get_completion_built_in_constant()); + r_result.class_member = p_symbol; return OK; } break; case GDParser::COMPLETION_FUNCTION: { - if (context._class && context._class->functions.size()) { - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=context._class->functions[i]->line; + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = context._class->functions[i]->line; return OK; } } } Ref<GDScript> parent = _get_parent_class(context); - while(parent.is_valid()) { + while (parent.is_valid()) { int line = parent->get_member_line(p_symbol); - if (line>=0) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=line; - r_result.script=parent; + if (line >= 0) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = line; + r_result.script = parent; return OK; - } - parent=parent->get_base(); + parent = parent->get_base(); } GDCompletionIdentifier identifier = _get_native_class(context); - print_line("identifier: "+String(identifier.obj_type)); + print_line("identifier: " + String(identifier.obj_type)); - if (ClassDB::has_method(identifier.obj_type,p_symbol)) { + if (ClassDB::has_method(identifier.obj_type, p_symbol)) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name=identifier.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = identifier.obj_type; + r_result.class_member = p_symbol; return OK; } - } break; case GDParser::COMPLETION_IDENTIFIER: { //check if a function if (p.get_completion_identifier_is_function()) { if (context._class && context._class->functions.size()) { - for(int i=0;i<context._class->functions.size();i++) { - if (context._class->functions[i]->name==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=context._class->functions[i]->line; + for (int i = 0; i < context._class->functions.size(); i++) { + if (context._class->functions[i]->name == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = context._class->functions[i]->line; return OK; } } } Ref<GDScript> parent = _get_parent_class(context); - while(parent.is_valid()) { + while (parent.is_valid()) { int line = parent->get_member_line(p_symbol); - if (line>=0) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=line; - r_result.script=parent; + if (line >= 0) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = line; + r_result.script = parent; return OK; - } - parent=parent->get_base(); + parent = parent->get_base(); } GDCompletionIdentifier identifier = _get_native_class(context); + if (ClassDB::has_method(identifier.obj_type, p_symbol)) { - if (ClassDB::has_method(identifier.obj_type,p_symbol)) { - - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name=identifier.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = identifier.obj_type; + r_result.class_member = p_symbol; return OK; } } else { - GDCompletionIdentifier gdi = _get_native_class(context); - if (gdi.obj_type!=StringName()) { + if (gdi.obj_type != StringName()) { bool valid; - Variant::Type t = ClassDB::get_property_type(gdi.obj_type,p_symbol,&valid); - if (t!=Variant::NIL && valid) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name=gdi.obj_type; - r_result.class_member=p_symbol; + Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_symbol, &valid); + if (t != Variant::NIL && valid) { + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; + r_result.class_name = gdi.obj_type; + r_result.class_member = p_symbol; return OK; - } } - const GDParser::BlockNode *block=context.block; + const GDParser::BlockNode *block = context.block; //search in blocks going up (local var?) - while(block) { - + while (block) { + for (int i = 0; i < block->statements.size(); i++) { - for (int i=0;i<block->statements.size();i++) { - - if (block->statements[i]->line>p.get_completion_line()) + if (block->statements[i]->line > p.get_completion_line()) continue; + if (block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) { - if (block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) { - - const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(block->statements[i]); + const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(block->statements[i]); - if (lv->assign && lv->name==p_symbol) { + if (lv->assign && lv->name == p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=block->statements[i]->line; + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = block->statements[i]->line; return OK; } } } - block=block->parent_block; + block = block->parent_block; } //guess from function arguments - if (context.function && context.function->name!=StringName()) { + if (context.function && context.function->name != StringName()) { - for(int i=0;i<context.function->arguments.size();i++) { + for (int i = 0; i < context.function->arguments.size(); i++) { - if (context.function->arguments[i]==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=context.function->line; + if (context.function->arguments[i] == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = context.function->line; return OK; } - } } //guess in class constants - for(int i=0;i<context._class->constant_expressions.size();i++) { + for (int i = 0; i < context._class->constant_expressions.size(); i++) { - if (context._class->constant_expressions[i].identifier==p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=context._class->constant_expressions[i].expression->line; + if (context._class->constant_expressions[i].identifier == p_symbol) { + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = context._class->constant_expressions[i].expression->line; return OK; } } @@ -2815,12 +2646,12 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol //guess in class variables if (!(context.function && context.function->_static)) { - for(int i=0;i<context._class->variables.size();i++) { + for (int i = 0; i < context._class->variables.size(); i++) { - if (context._class->variables[i].identifier==p_symbol) { + if (context._class->variables[i].identifier == p_symbol) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=context._class->variables[i].line; + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = context._class->variables[i].line; return OK; } } @@ -2830,29 +2661,29 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol List<PropertyInfo> props; GlobalConfig::get_singleton()->get_property_list(&props); - for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { String s = E->get().name; if (!s.begins_with("autoload/")) continue; - String name = s.get_slice("/",1); - if (name==String(p_symbol)) { + String name = s.get_slice("/", 1); + if (name == String(p_symbol)) { String path = GlobalConfig::get_singleton()->get(s); if (path.begins_with("*")) { - String script =path.substr(1,path.length()); + String script = path.substr(1, path.length()); if (!script.ends_with(".gd")) { //not a script, try find the script anyway, //may have some success - script=script.get_basename()+".gd"; + script = script.get_basename() + ".gd"; } if (FileAccess::exists(script)) { - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=0; - r_result.script=ResourceLoader::load(script); + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = 0; + r_result.script = ResourceLoader::load(script); return OK; } } @@ -2860,33 +2691,32 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol } //global - for(Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) { - if (E->key()==p_symbol) { + for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) { + if (E->key() == p_symbol) { Variant value = GDScriptLanguage::get_singleton()->get_global_array()[E->get()]; - if (value.get_type()==Variant::OBJECT) { + if (value.get_type() == Variant::OBJECT) { Object *obj = value; if (obj) { if (obj->cast_to<GDNativeClass>()) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS; - r_result.class_name=obj->cast_to<GDNativeClass>()->get_name(); + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; + r_result.class_name = obj->cast_to<GDNativeClass>()->get_name(); } else { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS; - r_result.class_name=obj->get_class(); + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; + r_result.class_name = obj->get_class(); } return OK; } } else { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name="@Global Scope"; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = "@Global Scope"; + r_result.class_member = p_symbol; return OK; } } - } #if 0 GDCompletionIdentifier identifier; @@ -2907,122 +2737,109 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol } break; case GDParser::COMPLETION_METHOD: - isfunction=true; + isfunction = true; case GDParser::COMPLETION_INDEX: { const GDParser::Node *node = p.get_completion_node(); - if (node->type!=GDParser::Node::TYPE_OPERATOR) + if (node->type != GDParser::Node::TYPE_OPERATOR) break; - - - GDCompletionIdentifier t; - if (_guess_expression_type(context,static_cast<const GDParser::OperatorNode *>(node)->arguments[0],p.get_completion_line(),t)) { + if (_guess_expression_type(context, static_cast<const GDParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) { - if (t.type==Variant::OBJECT && t.obj_type=="GDNativeClass") { + if (t.type == Variant::OBJECT && t.obj_type == "GDNativeClass") { //native enum Ref<GDNativeClass> gdn = t.value; if (gdn.is_valid()) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name=gdn->get_name(); - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = gdn->get_name(); + r_result.class_member = p_symbol; return OK; - } - } else if (t.type==Variant::OBJECT && t.obj_type!=StringName()) { + } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) { Ref<GDScript> on_script; if (t.value.get_type()) { - Object *obj=t.value; - + Object *obj = t.value; if (obj) { - - on_script=obj->get_script(); + on_script = obj->get_script(); if (on_script.is_valid()) { int loc = on_script->get_member_line(p_symbol); - if (loc>=0) { - r_result.script=on_script; - r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; - r_result.location=loc; + if (loc >= 0) { + r_result.script = on_script; + r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; + r_result.location = loc; return OK; } } } } - if (ClassDB::has_method(t.obj_type,p_symbol)) { + if (ClassDB::has_method(t.obj_type, p_symbol)) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name=t.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = t.obj_type; + r_result.class_member = p_symbol; return OK; - } bool success; - ClassDB::get_integer_constant(t.obj_type,p_symbol,&success); + ClassDB::get_integer_constant(t.obj_type, p_symbol, &success); if (success) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name=t.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = t.obj_type; + r_result.class_member = p_symbol; return OK; } - - ClassDB::get_property_type(t.obj_type,p_symbol,&success); + ClassDB::get_property_type(t.obj_type, p_symbol, &success); if (success) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name=t.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; + r_result.class_name = t.obj_type; + r_result.class_member = p_symbol; return OK; } - } else { Variant::CallError ce; - Variant v = Variant::construct(t.type,NULL,0,ce); + Variant v = Variant::construct(t.type, NULL, 0, ce); bool valid; - v.get_numeric_constant_value(t.type,p_symbol,&valid); + v.get_numeric_constant_value(t.type, p_symbol, &valid); if (valid) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; - r_result.class_name=Variant::get_type_name(t.type); - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; + r_result.class_name = Variant::get_type_name(t.type); + r_result.class_member = p_symbol; return OK; } //todo check all inputevent types for property - v.get(p_symbol,&valid); + v.get(p_symbol, &valid); if (valid) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; - r_result.class_name=Variant::get_type_name(t.type); - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY; + r_result.class_name = Variant::get_type_name(t.type); + r_result.class_member = p_symbol; return OK; } if (v.has_method(p_symbol)) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name=Variant::get_type_name(t.type); - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = Variant::get_type_name(t.type); + r_result.class_member = p_symbol; return OK; - } - - } } - } break; case GDParser::COMPLETION_CALL_ARGUMENTS: { @@ -3032,18 +2849,17 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol GDCompletionIdentifier cid = _get_native_class(context); - if (cid.obj_type!=StringName()) { + if (cid.obj_type != StringName()) { List<MethodInfo> vm; - ClassDB::get_virtual_methods(cid.obj_type,&vm); - for(List<MethodInfo>::Element *E=vm.front();E;E=E->next()) { + ClassDB::get_virtual_methods(cid.obj_type, &vm); + for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) { - if (p_symbol==E->get().name) { + if (p_symbol == E->get().name) { - r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; - r_result.class_name=cid.obj_type; - r_result.class_member=p_symbol; + r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; + r_result.class_name = cid.obj_type; + r_result.class_member = p_symbol; return OK; - } } } @@ -3053,10 +2869,8 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol return ERR_CANT_RESOLVE; } break; - } - return ERR_CANT_RESOLVE; } diff --git a/modules/gdscript/gd_function.cpp b/modules/gdscript/gd_function.cpp index 519fb1cd8c..aaf97001e9 100644 --- a/modules/gdscript/gd_function.cpp +++ b/modules/gdscript/gd_function.cpp @@ -28,21 +28,21 @@ /*************************************************************************/ #include "gd_function.h" +#include "gd_functions.h" #include "gd_script.h" #include "os/os.h" -#include "gd_functions.h" -Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self, Variant *p_stack,String& r_error) const{ +Variant *GDFunction::_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const { - int address = p_address&ADDR_MASK; + int address = p_address & ADDR_MASK; //sequential table (jump table generated by compiler) - switch((p_address&ADDR_TYPE_MASK)>>ADDR_BITS) { + switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) { case ADDR_TYPE_SELF: { if (!p_instance) { - r_error="Cannot access self without instance."; + r_error = "Cannot access self without instance."; return NULL; } return &self; @@ -54,7 +54,7 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript case ADDR_TYPE_MEMBER: { //member indexing is O(1) if (!p_instance) { - r_error="Cannot access member without instance."; + r_error = "Cannot access member without instance."; return NULL; } return &p_instance->members[address]; @@ -62,41 +62,38 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript case ADDR_TYPE_CLASS_CONSTANT: { //todo change to index! - GDScript *o=p_script; - ERR_FAIL_INDEX_V(address,_global_names_count,NULL); + GDScript *o = p_script; + ERR_FAIL_INDEX_V(address, _global_names_count, NULL); const StringName *sn = &_global_names_ptr[address]; - while(o) { - GDScript *s=o; - while(s) { + while (o) { + GDScript *s = o; + while (s) { - Map<StringName,Variant>::Element *E=s->constants.find(*sn); + Map<StringName, Variant>::Element *E = s->constants.find(*sn); if (E) { return &E->get(); } - s=s->_base; + s = s->_base; } - o=o->_owner; + o = o->_owner; } - ERR_EXPLAIN("GDCompiler bug.."); ERR_FAIL_V(NULL); } break; case ADDR_TYPE_LOCAL_CONSTANT: { - ERR_FAIL_INDEX_V(address,_constant_count,NULL); + ERR_FAIL_INDEX_V(address, _constant_count, NULL); return &_constants_ptr[address]; } break; case ADDR_TYPE_STACK: case ADDR_TYPE_STACK_VARIABLE: { - ERR_FAIL_INDEX_V(address,_stack_size,NULL); + ERR_FAIL_INDEX_V(address, _stack_size, NULL); return &p_stack[address]; } break; case ADDR_TYPE_GLOBAL: { - - ERR_FAIL_INDEX_V(address,GDScriptLanguage::get_singleton()->get_global_array_size(),NULL); - + ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), NULL); return &GDScriptLanguage::get_singleton()->get_global_array()[address]; } break; @@ -110,37 +107,33 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript return NULL; } - -String GDFunction::_get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const { - - +String GDFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const { String err_text; - if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - int errorarg=p_err.argument; - err_text="Invalid type in "+p_where+". Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(p_err.expected)+"."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { - err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { - err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) { - err_text="Invalid call. Nonexistent "+p_where+"."; - } else if (p_err.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { - err_text="Attempt to call "+p_where+" on a null instance."; + if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + int errorarg = p_err.argument; + err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + "."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { + err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { + err_text = "Invalid call. Nonexistent " + p_where + "."; + } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { + err_text = "Attempt to call " + p_where + " on a null instance."; } else { - err_text="Bug, call error: #"+itos(p_err.error); + err_text = "Bug, call error: #" + itos(p_err.error); } return err_text; - } -static String _get_var_type(const Variant* p_type) { +static String _get_var_type(const Variant *p_type) { String basestr; - if (p_type->get_type()==Variant::OBJECT) { + if (p_type->get_type() == Variant::OBJECT) { Object *bobj = *p_type; if (!bobj) { basestr = "null instance"; @@ -148,15 +141,15 @@ static String _get_var_type(const Variant* p_type) { #ifdef DEBUG_ENABLED if (ObjectDB::instance_validate(bobj)) { if (bobj->get_script_instance()) - basestr= bobj->get_class()+" ("+bobj->get_script_instance()->get_script()->get_path().get_file()+")"; + basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")"; else basestr = bobj->get_class(); } else { - basestr="previously freed instance"; + basestr = "previously freed instance"; } #else - basestr="Object"; + basestr = "Object"; #endif } @@ -165,114 +158,108 @@ static String _get_var_type(const Variant* p_type) { } return basestr; - } -Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError& r_err, CallState *p_state) { - +Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state) { if (!_code_ptr) { return Variant(); } - r_err.error=Variant::CallError::CALL_OK; + r_err.error = Variant::CallError::CALL_OK; Variant self; Variant retvalue; Variant *stack = NULL; Variant **call_args; - int defarg=0; + int defarg = 0; #ifdef DEBUG_ENABLED - //GDScriptLanguage::get_singleton()->calls++; +//GDScriptLanguage::get_singleton()->calls++; #endif - uint32_t alloca_size=0; + uint32_t alloca_size = 0; GDScript *_class; - int ip=0; - int line=_initial_line; - - + int ip = 0; + int line = _initial_line; if (p_state) { //use existing (supplied) state (yielded) - stack=(Variant*)p_state->stack.ptr(); - call_args=(Variant**)stack + sizeof(Variant)*p_state->stack_size; - line=p_state->line; - ip=p_state->ip; - alloca_size=p_state->stack.size(); - _class=p_state->_class; - p_instance=p_state->instance; - defarg=p_state->defarg; - self=p_state->self; + stack = (Variant *)p_state->stack.ptr(); + call_args = (Variant **)stack + sizeof(Variant) * p_state->stack_size; + line = p_state->line; + ip = p_state->ip; + alloca_size = p_state->stack.size(); + _class = p_state->_class; + p_instance = p_state->instance; + defarg = p_state->defarg; + self = p_state->self; //stack[p_state->result_pos]=p_state->result; //assign stack with result } else { - if (p_argcount!=_argument_count) { - - if (p_argcount>_argument_count) { + if (p_argcount != _argument_count) { - r_err.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_err.argument=_argument_count; + if (p_argcount > _argument_count) { + r_err.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_err.argument = _argument_count; return Variant(); } else if (p_argcount < _argument_count - _default_arg_count) { - r_err.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_err.argument=_argument_count - _default_arg_count; + r_err.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_err.argument = _argument_count - _default_arg_count; return Variant(); } else { - defarg=_argument_count-p_argcount; + defarg = _argument_count - p_argcount; } } - alloca_size = sizeof(Variant*)*_call_size + sizeof(Variant)*_stack_size; + alloca_size = sizeof(Variant *) * _call_size + sizeof(Variant) * _stack_size; if (alloca_size) { - uint8_t *aptr = (uint8_t*)alloca(alloca_size); + uint8_t *aptr = (uint8_t *)alloca(alloca_size); if (_stack_size) { - stack=(Variant*)aptr; - for(int i=0;i<p_argcount;i++) - memnew_placement(&stack[i],Variant(*p_args[i])); - for(int i=p_argcount;i<_stack_size;i++) - memnew_placement(&stack[i],Variant); + stack = (Variant *)aptr; + for (int i = 0; i < p_argcount; i++) + memnew_placement(&stack[i], Variant(*p_args[i])); + for (int i = p_argcount; i < _stack_size; i++) + memnew_placement(&stack[i], Variant); } else { - stack=NULL; + stack = NULL; } if (_call_size) { - call_args = (Variant**)&aptr[sizeof(Variant)*_stack_size]; + call_args = (Variant **)&aptr[sizeof(Variant) * _stack_size]; } else { - call_args=NULL; + call_args = NULL; } - } else { - stack=NULL; - call_args=NULL; + stack = NULL; + call_args = NULL; } if (p_instance) { - if (p_instance->base_ref && static_cast<Reference*>(p_instance->owner)->is_referenced()) { + if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) { - self=REF(static_cast<Reference*>(p_instance->owner)); + self = REF(static_cast<Reference *>(p_instance->owner)); } else { - self=p_instance->owner; + self = p_instance->owner; } - _class=p_instance->script.ptr(); + _class = p_instance->script.ptr(); } else { - _class=_script; + _class = _script; } } @@ -281,537 +268,519 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton()) - GDScriptLanguage::get_singleton()->enter_function(p_instance,this,stack,&ip,&line); - -#define CHECK_SPACE(m_space)\ - ERR_BREAK((ip+m_space)>_code_size) + GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line); -#define GET_VARIANT_PTR(m_v,m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);\ - if (!m_v)\ - break; +#define CHECK_SPACE(m_space) \ + ERR_BREAK((ip + m_space) > _code_size) +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); \ + if (!m_v) \ + break; #else #define CHECK_SPACE(m_space) -#define GET_VARIANT_PTR(m_v,m_code_ofs) \ - Variant *m_v; \ - m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text); +#define GET_VARIANT_PTR(m_v, m_code_ofs) \ + Variant *m_v; \ + m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text); #endif - #ifdef DEBUG_ENABLED uint64_t function_start_time; uint64_t function_call_time; if (GDScriptLanguage::get_singleton()->profiling) { - function_start_time=OS::get_singleton()->get_ticks_usec(); - function_call_time=0; + function_start_time = OS::get_singleton()->get_ticks_usec(); + function_call_time = 0; profile.call_count++; profile.frame_call_count++; } #endif - bool exit_ok=false; + bool exit_ok = false; - while(ip<_code_size) { + while (ip < _code_size) { - - int last_opcode=_code_ptr[ip]; - switch(_code_ptr[ip]) { + int last_opcode = _code_ptr[ip]; + switch (_code_ptr[ip]) { case OPCODE_OPERATOR: { CHECK_SPACE(5); bool valid; - Variant::Operator op = (Variant::Operator)_code_ptr[ip+1]; - ERR_BREAK(op>=Variant::OP_MAX); + Variant::Operator op = (Variant::Operator)_code_ptr[ip + 1]; + ERR_BREAK(op >= Variant::OP_MAX); - GET_VARIANT_PTR(a,2); - GET_VARIANT_PTR(b,3); - GET_VARIANT_PTR(dst,4); + GET_VARIANT_PTR(a, 2); + GET_VARIANT_PTR(b, 3); + GET_VARIANT_PTR(dst, 4); #ifdef DEBUG_ENABLED Variant ret; - Variant::evaluate(op,*a,*b,ret,valid); + Variant::evaluate(op, *a, *b, ret, valid); #else - Variant::evaluate(op,*a,*b,*dst,valid); + Variant::evaluate(op, *a, *b, *dst, valid); #endif if (!valid) { #ifdef DEBUG_ENABLED - if (ret.get_type()==Variant::STRING) { + if (ret.get_type() == Variant::STRING) { //return a string when invalid with the error - err_text=ret; - err_text += " in operator '"+Variant::get_operator_name(op)+"'."; + err_text = ret; + err_text += " in operator '" + Variant::get_operator_name(op) + "'."; } else { - err_text="Invalid operands '"+Variant::get_type_name(a->get_type())+"' and '"+Variant::get_type_name(b->get_type())+"' in operator '"+Variant::get_operator_name(op)+"'."; + err_text = "Invalid operands '" + Variant::get_type_name(a->get_type()) + "' and '" + Variant::get_type_name(b->get_type()) + "' in operator '" + Variant::get_operator_name(op) + "'."; } #endif break; - } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=5; + ip += 5; continue; } case OPCODE_EXTENDS_TEST: { CHECK_SPACE(4); - GET_VARIANT_PTR(a,1); - GET_VARIANT_PTR(b,2); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(a, 1); + GET_VARIANT_PTR(b, 2); + GET_VARIANT_PTR(dst, 3); #ifdef DEBUG_ENABLED - if (a->get_type()!=Variant::OBJECT || a->operator Object*()==NULL) { + if (a->get_type() != Variant::OBJECT || a->operator Object *() == NULL) { - err_text="Left operand of 'extends' is not an instance of anything."; + err_text = "Left operand of 'extends' is not an instance of anything."; break; - } - if (b->get_type()!=Variant::OBJECT || b->operator Object*()==NULL) { + if (b->get_type() != Variant::OBJECT || b->operator Object *() == NULL) { - err_text="Right operand of 'extends' is not a class."; + err_text = "Right operand of 'extends' is not a class."; break; - } #endif - Object *obj_A = *a; Object *obj_B = *b; - GDScript *scr_B = obj_B->cast_to<GDScript>(); - bool extends_ok=false; + bool extends_ok = false; if (scr_B) { //if B is a script, the only valid condition is that A has an instance which inherits from the script //in other situation, this shoul return false. - if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language()==GDScriptLanguage::get_singleton()) { + if (obj_A->get_script_instance() && obj_A->get_script_instance()->get_language() == GDScriptLanguage::get_singleton()) { - GDScript *cmp = static_cast<GDScript*>(obj_A->get_script_instance()->get_script().ptr()); + GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr()); //bool found=false; - while(cmp) { + while (cmp) { - if (cmp==scr_B) { + if (cmp == scr_B) { //inherits from script, all ok - extends_ok=true; + extends_ok = true; break; - } - cmp=cmp->_base; + cmp = cmp->_base; } - } - } else { - GDNativeClass *nc= obj_B->cast_to<GDNativeClass>(); + GDNativeClass *nc = obj_B->cast_to<GDNativeClass>(); if (!nc) { - err_text="Right operand of 'extends' is not a class (type: '"+obj_B->get_class()+"')."; + err_text = "Right operand of 'extends' is not a class (type: '" + obj_B->get_class() + "')."; break; } - extends_ok=ClassDB::is_parent_class(obj_A->get_class_name(),nc->get_name()); + extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name()); } - *dst=extends_ok; - ip+=4; + *dst = extends_ok; + ip += 4; continue; } case OPCODE_SET: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(index,2); - GET_VARIANT_PTR(value,3); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(index, 2); + GET_VARIANT_PTR(value, 3); bool valid; - dst->set(*index,*value,&valid); + dst->set(*index, *value, &valid); if (!valid) { String v = index->operator String(); - if (v!="") { - v="'"+v+"'"; + if (v != "") { + v = "'" + v + "'"; } else { - v="of type '"+_get_var_type(index)+"'"; + v = "of type '" + _get_var_type(index) + "'"; } - err_text="Invalid set index "+v+" (on base: '"+_get_var_type(dst)+"')."; + err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "')."; break; } - ip+=4; + ip += 4; continue; } case OPCODE_GET: { CHECK_SPACE(3); - GET_VARIANT_PTR(src,1); - GET_VARIANT_PTR(index,2); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(src, 1); + GET_VARIANT_PTR(index, 2); + GET_VARIANT_PTR(dst, 3); bool valid; #ifdef DEBUG_ENABLED //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get(*index,&valid); + Variant ret = src->get(*index, &valid); #else - *dst = src->get(*index,&valid); + *dst = src->get(*index, &valid); #endif if (!valid) { String v = index->operator String(); - if (v!="") { - v="'"+v+"'"; + if (v != "") { + v = "'" + v + "'"; } else { - v="of type '"+_get_var_type(index)+"'"; + v = "of type '" + _get_var_type(index) + "'"; } - err_text="Invalid get index "+v+" (on base: '"+_get_var_type(src)+"')."; + err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "')."; break; } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=4; + ip += 4; continue; } case OPCODE_SET_NAMED: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(value,3); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(value, 3); - int indexname = _code_ptr[ip+2]; + int indexname = _code_ptr[ip + 2]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; bool valid; - dst->set_named(*index,*value,&valid); + dst->set_named(*index, *value, &valid); if (!valid) { String err_type; - err_text="Invalid set index '"+String(*index)+"' (on base: '"+_get_var_type(dst)+"')."; + err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "')."; break; } - ip+=4; + ip += 4; continue; } case OPCODE_GET_NAMED: { - CHECK_SPACE(4); - GET_VARIANT_PTR(src,1); - GET_VARIANT_PTR(dst,3); + GET_VARIANT_PTR(src, 1); + GET_VARIANT_PTR(dst, 3); - int indexname = _code_ptr[ip+2]; + int indexname = _code_ptr[ip + 2]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; bool valid; #ifdef DEBUG_ENABLED //allow better error message in cases where src and dst are the same stack position - Variant ret = src->get_named(*index,&valid); + Variant ret = src->get_named(*index, &valid); #else - *dst = src->get_named(*index,&valid); + *dst = src->get_named(*index, &valid); #endif if (!valid) { if (src->has_method(*index)) { - err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"'). Did you mean '."+index->operator String()+"()' ?"; + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' ?"; } else { - err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"')."; + err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "')."; } break; } #ifdef DEBUG_ENABLED - *dst=ret; + *dst = ret; #endif - ip+=4; + ip += 4; continue; } case OPCODE_SET_MEMBER: { CHECK_SPACE(3); - int indexname = _code_ptr[ip+1]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + int indexname = _code_ptr[ip + 1]; + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; - GET_VARIANT_PTR(src,2); + GET_VARIANT_PTR(src, 2); bool valid; - bool ok = ClassDB::set_property(p_instance->owner,*index,*src,&valid); + bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid); #ifdef DEBUG_ENABLED if (!ok) { - err_text="Internal error setting property: "+String(*index); + err_text = "Internal error setting property: " + String(*index); break; } else if (!valid) { - err_text="Error setting property '"+String(*index)+"' with value of type "+Variant::get_type_name(src->get_type())+"."; + err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + "."; break; - } #endif - ip+=3; + ip += 3; continue; } case OPCODE_GET_MEMBER: { CHECK_SPACE(3); - int indexname = _code_ptr[ip+1]; - ERR_BREAK(indexname<0 || indexname>=_global_names_count); + int indexname = _code_ptr[ip + 1]; + ERR_BREAK(indexname < 0 || indexname >= _global_names_count); const StringName *index = &_global_names_ptr[indexname]; - GET_VARIANT_PTR(dst,2); - bool ok = ClassDB::get_property(p_instance->owner,*index,*dst); + GET_VARIANT_PTR(dst, 2); + bool ok = ClassDB::get_property(p_instance->owner, *index, *dst); #ifdef DEBUG_ENABLED if (!ok) { - err_text="Internal error getting property: "+String(*index); + err_text = "Internal error getting property: " + String(*index); break; } #endif - ip+=3; + ip += 3; continue; } case OPCODE_ASSIGN: { CHECK_SPACE(3); - GET_VARIANT_PTR(dst,1); - GET_VARIANT_PTR(src,2); + GET_VARIANT_PTR(dst, 1); + GET_VARIANT_PTR(src, 2); *dst = *src; - ip+=3; + ip += 3; continue; } case OPCODE_ASSIGN_TRUE: { CHECK_SPACE(2); - GET_VARIANT_PTR(dst,1); + GET_VARIANT_PTR(dst, 1); *dst = true; - ip+=2; + ip += 2; continue; } case OPCODE_ASSIGN_FALSE: { CHECK_SPACE(2); - GET_VARIANT_PTR(dst,1); + GET_VARIANT_PTR(dst, 1); *dst = false; - ip+=2; + ip += 2; continue; } case OPCODE_CONSTRUCT: { CHECK_SPACE(2); - Variant::Type t=Variant::Type(_code_ptr[ip+1]); - int argc=_code_ptr[ip+2]; - CHECK_SPACE(argc+2); + Variant::Type t = Variant::Type(_code_ptr[ip + 1]); + int argc = _code_ptr[ip + 2]; + CHECK_SPACE(argc + 2); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,3+i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, 3 + i); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,3+argc); + GET_VARIANT_PTR(dst, 3 + argc); Variant::CallError err; - *dst = Variant::construct(t,(const Variant**)argptrs,argc,err); + *dst = Variant::construct(t, (const Variant **)argptrs, argc, err); - if (err.error!=Variant::CallError::CALL_OK) { + if (err.error != Variant::CallError::CALL_OK) { - err_text=_get_call_error(err,"'"+Variant::get_type_name(t)+"' constructor",(const Variant**)argptrs); + err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs); break; } - ip+=4+argc; + ip += 4 + argc; //construct a basic type continue; } case OPCODE_CONSTRUCT_ARRAY: { CHECK_SPACE(1); - int argc=_code_ptr[ip+1]; + int argc = _code_ptr[ip + 1]; Array array; //arrays are always shared array.resize(argc); - CHECK_SPACE(argc+2); - - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,2+i); - array[i]=*v; + CHECK_SPACE(argc + 2); + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, 2 + i); + array[i] = *v; } - GET_VARIANT_PTR(dst,2+argc); + GET_VARIANT_PTR(dst, 2 + argc); - *dst=array; + *dst = array; - ip+=3+argc; + ip += 3 + argc; continue; } case OPCODE_CONSTRUCT_DICTIONARY: { CHECK_SPACE(1); - int argc=_code_ptr[ip+1]; + int argc = _code_ptr[ip + 1]; Dictionary dict; //arrays are always shared - CHECK_SPACE(argc*2+2); + CHECK_SPACE(argc * 2 + 2); - for(int i=0;i<argc;i++) { - - GET_VARIANT_PTR(k,2+i*2+0); - GET_VARIANT_PTR(v,2+i*2+1); - dict[*k]=*v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(k, 2 + i * 2 + 0); + GET_VARIANT_PTR(v, 2 + i * 2 + 1); + dict[*k] = *v; } - GET_VARIANT_PTR(dst,2+argc*2); + GET_VARIANT_PTR(dst, 2 + argc * 2); - *dst=dict; + *dst = dict; - ip+=3+argc*2; + ip += 3 + argc * 2; continue; } case OPCODE_CALL_RETURN: case OPCODE_CALL: { - CHECK_SPACE(4); - bool call_ret = _code_ptr[ip]==OPCODE_CALL_RETURN; + bool call_ret = _code_ptr[ip] == OPCODE_CALL_RETURN; - int argc=_code_ptr[ip+1]; - GET_VARIANT_PTR(base,2); - int nameg=_code_ptr[ip+3]; + int argc = _code_ptr[ip + 1]; + GET_VARIANT_PTR(base, 2); + int nameg = _code_ptr[ip + 3]; - ERR_BREAK(nameg<0 || nameg>=_global_names_count); + ERR_BREAK(nameg < 0 || nameg >= _global_names_count); const StringName *methodname = &_global_names_ptr[nameg]; - ERR_BREAK(argc<0); - ip+=4; - CHECK_SPACE(argc+1); + ERR_BREAK(argc < 0); + ip += 4; + CHECK_SPACE(argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i); + argptrs[i] = v; } #ifdef DEBUG_ENABLED uint64_t call_time; if (GDScriptLanguage::get_singleton()->profiling) { - call_time=OS::get_singleton()->get_ticks_usec(); + call_time = OS::get_singleton()->get_ticks_usec(); } #endif Variant::CallError err; if (call_ret) { - GET_VARIANT_PTR(ret,argc); - base->call_ptr(*methodname,(const Variant**)argptrs,argc,ret,err); + GET_VARIANT_PTR(ret, argc); + base->call_ptr(*methodname, (const Variant **)argptrs, argc, ret, err); } else { - base->call_ptr(*methodname,(const Variant**)argptrs,argc,NULL,err); + base->call_ptr(*methodname, (const Variant **)argptrs, argc, NULL, err); } #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->profiling) { - function_call_time+=OS::get_singleton()->get_ticks_usec() - call_time; + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; } #endif - if (err.error!=Variant::CallError::CALL_OK) { - + if (err.error != Variant::CallError::CALL_OK) { String methodstr = *methodname; String basestr = _get_var_type(base); - if (methodstr=="call") { - if (argc>=1) { - methodstr=String(*argptrs[0])+" (via call)"; - if (err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { - err.argument-=1; + if (methodstr == "call") { + if (argc >= 1) { + methodstr = String(*argptrs[0]) + " (via call)"; + if (err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { + err.argument -= 1; } } - } else if (methodstr=="free") { + } else if (methodstr == "free") { - if (err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) { + if (err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { if (base->is_ref()) { - err_text="Attempted to free a reference."; + err_text = "Attempted to free a reference."; break; - } else if (base->get_type()==Variant::OBJECT) { + } else if (base->get_type() == Variant::OBJECT) { - err_text="Attempted to free a locked object (calling or emitting)."; + err_text = "Attempted to free a locked object (calling or emitting)."; break; } } } - err_text=_get_call_error(err,"function '"+methodstr+"' in base '"+basestr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); break; } //_call_func(NULL,base,*methodname,ip,argc,p_instance,stack); - ip+=argc+1; + ip += argc + 1; continue; } case OPCODE_CALL_BUILT_IN: { CHECK_SPACE(4); - GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip+1]); - int argc=_code_ptr[ip+2]; - ERR_BREAK(argc<0); + GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip + 1]); + int argc = _code_ptr[ip + 2]; + ERR_BREAK(argc < 0); - ip+=3; - CHECK_SPACE(argc+1); + ip += 3; + CHECK_SPACE(argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,argc); + GET_VARIANT_PTR(dst, argc); Variant::CallError err; - GDFunctions::call(func,(const Variant**)argptrs,argc,*dst,err); - - if (err.error!=Variant::CallError::CALL_OK) { + GDFunctions::call(func, (const Variant **)argptrs, argc, *dst, err); + if (err.error != Variant::CallError::CALL_OK) { String methodstr = GDFunctions::get_func_name(func); - if (dst->get_type()==Variant::STRING) { + if (dst->get_type() == Variant::STRING) { //call provided error string - err_text="Error calling built-in function '"+methodstr+"': "+String(*dst); + err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst); } else { - err_text=_get_call_error(err,"built-in function '"+methodstr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs); } break; } - ip+=argc+1; + ip += argc + 1; continue; } case OPCODE_CALL_SELF: { @@ -821,37 +790,36 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a case OPCODE_CALL_SELF_BASE: { CHECK_SPACE(2); - int self_fun = _code_ptr[ip+1]; + int self_fun = _code_ptr[ip + 1]; #ifdef DEBUG_ENABLED - if (self_fun<0 || self_fun>=_global_names_count) { + if (self_fun < 0 || self_fun >= _global_names_count) { - err_text="compiler bug, function name not found"; + err_text = "compiler bug, function name not found"; break; } #endif const StringName *methodname = &_global_names_ptr[self_fun]; - int argc=_code_ptr[ip+2]; + int argc = _code_ptr[ip + 2]; - CHECK_SPACE(2+argc+1); + CHECK_SPACE(2 + argc + 1); Variant **argptrs = call_args; - for(int i=0;i<argc;i++) { - GET_VARIANT_PTR(v,i+3); - argptrs[i]=v; + for (int i = 0; i < argc; i++) { + GET_VARIANT_PTR(v, i + 3); + argptrs[i] = v; } - GET_VARIANT_PTR(dst,argc+3); + GET_VARIANT_PTR(dst, argc + 3); const GDScript *gds = _script; - - const Map<StringName,GDFunction*>::Element *E=NULL; + const Map<StringName, GDFunction *>::Element *E = NULL; while (gds->base.ptr()) { - gds=gds->base.ptr(); - E=gds->member_functions.find(*methodname); + gds = gds->base.ptr(); + E = gds->member_functions.find(*methodname); if (E) break; } @@ -860,344 +828,332 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a if (E) { - *dst=E->get()->call(p_instance,(const Variant**)argptrs,argc,err); + *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err); } else if (gds->native.ptr()) { - if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) { + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { - MethodBind *mb = ClassDB::get_method(gds->native->get_name(),*methodname); + MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname); if (!mb) { - err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; } else { - *dst=mb->call(p_instance->owner,(const Variant**)argptrs,argc,err); + *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err); } } else { - err.error=Variant::CallError::CALL_OK; + err.error = Variant::CallError::CALL_OK; } } else { - if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) { - err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + if (*methodname != GDScriptLanguage::get_singleton()->strings._init) { + err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; } else { - err.error=Variant::CallError::CALL_OK; + err.error = Variant::CallError::CALL_OK; } } - - if (err.error!=Variant::CallError::CALL_OK) { - + if (err.error != Variant::CallError::CALL_OK) { String methodstr = *methodname; - err_text=_get_call_error(err,"function '"+methodstr+"'",(const Variant**)argptrs); + err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs); break; } - ip+=4+argc; + ip += 4 + argc; continue; } case OPCODE_YIELD: case OPCODE_YIELD_SIGNAL: { - int ipofs=1; - if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) { + int ipofs = 1; + if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) { CHECK_SPACE(4); - ipofs+=2; + ipofs += 2; } else { CHECK_SPACE(2); - } - Ref<GDFunctionState> gdfs = memnew( GDFunctionState ); - gdfs->function=this; + Ref<GDFunctionState> gdfs = memnew(GDFunctionState); + gdfs->function = this; gdfs->state.stack.resize(alloca_size); //copy variant stack - for(int i=0;i<_stack_size;i++) { - memnew_placement(&gdfs->state.stack[sizeof(Variant)*i],Variant(stack[i])); + for (int i = 0; i < _stack_size; i++) { + memnew_placement(&gdfs->state.stack[sizeof(Variant) * i], Variant(stack[i])); } - gdfs->state.stack_size=_stack_size; - gdfs->state.self=self; - gdfs->state.alloca_size=alloca_size; - gdfs->state._class=_class; - gdfs->state.ip=ip+ipofs; - gdfs->state.line=line; - gdfs->state.instance_id=(p_instance && p_instance->get_owner())?p_instance->get_owner()->get_instance_ID():0; - gdfs->state.script_id=_class->get_instance_ID(); + gdfs->state.stack_size = _stack_size; + gdfs->state.self = self; + gdfs->state.alloca_size = alloca_size; + gdfs->state._class = _class; + gdfs->state.ip = ip + ipofs; + gdfs->state.line = line; + gdfs->state.instance_id = (p_instance && p_instance->get_owner()) ? p_instance->get_owner()->get_instance_ID() : 0; + gdfs->state.script_id = _class->get_instance_ID(); //gdfs->state.result_pos=ip+ipofs-1; - gdfs->state.defarg=defarg; - gdfs->state.instance=p_instance; - gdfs->function=this; + gdfs->state.defarg = defarg; + gdfs->state.instance = p_instance; + gdfs->function = this; - retvalue=gdfs; + retvalue = gdfs; - if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) { - GET_VARIANT_PTR(argobj,1); - GET_VARIANT_PTR(argname,2); + if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) { + GET_VARIANT_PTR(argobj, 1); + GET_VARIANT_PTR(argname, 2); //do the oneshot connect - if (argobj->get_type()!=Variant::OBJECT) { - err_text="First argument of yield() not of type object."; + if (argobj->get_type() != Variant::OBJECT) { + err_text = "First argument of yield() not of type object."; break; } - if (argname->get_type()!=Variant::STRING) { - err_text="Second argument of yield() not a string (for signal name)."; + if (argname->get_type() != Variant::STRING) { + err_text = "Second argument of yield() not a string (for signal name)."; break; } - Object *obj=argobj->operator Object *(); + Object *obj = argobj->operator Object *(); String signal = argname->operator String(); #ifdef DEBUG_ENABLED if (!obj) { - err_text="First argument of yield() is null."; + err_text = "First argument of yield() is null."; break; } if (ScriptDebugger::get_singleton()) { if (!ObjectDB::instance_validate(obj)) { - err_text="First argument of yield() is a previously freed instance."; + err_text = "First argument of yield() is a previously freed instance."; break; } } - if (signal.length()==0) { + if (signal.length() == 0) { - err_text="Second argument of yield() is an empty string (for signal name)."; + err_text = "Second argument of yield() is an empty string (for signal name)."; break; } #endif - Error err = obj->connect(signal,gdfs.ptr(),"_signal_callback",varray(gdfs),Object::CONNECT_ONESHOT); - if (err!=OK) { - err_text="Error connecting to signal: "+signal+" during yield()."; + Error err = obj->connect(signal, gdfs.ptr(), "_signal_callback", varray(gdfs), Object::CONNECT_ONESHOT); + if (err != OK) { + err_text = "Error connecting to signal: " + signal + " during yield()."; break; } - - } - exit_ok=true; + exit_ok = true; break; } case OPCODE_YIELD_RESUME: { CHECK_SPACE(2); if (!p_state) { - err_text=("Invalid Resume (bug?)"); + err_text = ("Invalid Resume (bug?)"); break; } - GET_VARIANT_PTR(result,1); - *result=p_state->result; - ip+=2; + GET_VARIANT_PTR(result, 1); + *result = p_state->result; + ip += 2; continue; } case OPCODE_JUMP: { CHECK_SPACE(2); - int to = _code_ptr[ip+1]; + int to = _code_ptr[ip + 1]; - ERR_BREAK(to<0 || to>_code_size); - ip=to; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; continue; } case OPCODE_JUMP_IF: { CHECK_SPACE(3); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); bool valid; bool result = test->booleanize(valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } #endif if (result) { - int to = _code_ptr[ip+2]; - ERR_BREAK(to<0 || to>_code_size); - ip=to; + int to = _code_ptr[ip + 2]; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; continue; } - ip+=3; + ip += 3; continue; } case OPCODE_JUMP_IF_NOT: { CHECK_SPACE(3); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); bool valid; bool result = test->booleanize(valid); #ifdef DEBUG_ENABLED if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } #endif if (!result) { - int to = _code_ptr[ip+2]; - ERR_BREAK(to<0 || to>_code_size); - ip=to; + int to = _code_ptr[ip + 2]; + ERR_BREAK(to < 0 || to > _code_size); + ip = to; continue; } - ip+=3; + ip += 3; continue; } case OPCODE_JUMP_TO_DEF_ARGUMENT: { CHECK_SPACE(2); - ip=_default_arg_ptr[defarg]; + ip = _default_arg_ptr[defarg]; continue; } case OPCODE_RETURN: { CHECK_SPACE(2); - GET_VARIANT_PTR(r,1); - retvalue=*r; - exit_ok=true; + GET_VARIANT_PTR(r, 1); + retvalue = *r; + exit_ok = true; break; } case OPCODE_ITERATE_BEGIN: { CHECK_SPACE(8); //space for this an regular iterate - GET_VARIANT_PTR(counter,1); - GET_VARIANT_PTR(container,2); + GET_VARIANT_PTR(counter, 1); + GET_VARIANT_PTR(container, 2); bool valid; - if (!container->iter_init(*counter,valid)) { + if (!container->iter_init(*counter, valid)) { if (!valid) { - err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"'."; + err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "'."; break; } - int jumpto=_code_ptr[ip+3]; - ERR_BREAK(jumpto<0 || jumpto>_code_size); - ip=jumpto; + int jumpto = _code_ptr[ip + 3]; + ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; continue; } - GET_VARIANT_PTR(iterator,4); + GET_VARIANT_PTR(iterator, 4); - - *iterator=container->iter_get(*counter,valid); + *iterator = container->iter_get(*counter, valid); if (!valid) { - err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"'."; + err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "'."; break; } - - ip+=5; //skip regular iterate which is always next + ip += 5; //skip regular iterate which is always next continue; } case OPCODE_ITERATE: { CHECK_SPACE(4); - GET_VARIANT_PTR(counter,1); - GET_VARIANT_PTR(container,2); + GET_VARIANT_PTR(counter, 1); + GET_VARIANT_PTR(container, 2); bool valid; - if (!container->iter_next(*counter,valid)) { + if (!container->iter_next(*counter, valid)) { if (!valid) { - err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"' (type changed since first iteration?)."; + err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?)."; break; } - int jumpto=_code_ptr[ip+3]; - ERR_BREAK(jumpto<0 || jumpto>_code_size); - ip=jumpto; + int jumpto = _code_ptr[ip + 3]; + ERR_BREAK(jumpto < 0 || jumpto > _code_size); + ip = jumpto; continue; } - GET_VARIANT_PTR(iterator,4); + GET_VARIANT_PTR(iterator, 4); - *iterator=container->iter_get(*counter,valid); + *iterator = container->iter_get(*counter, valid); if (!valid) { - err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"' (but was obtained on first iteration?)."; + err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?)."; break; } - ip+=5; //loop again + ip += 5; //loop again continue; } case OPCODE_ASSERT: { CHECK_SPACE(2); - GET_VARIANT_PTR(test,1); + GET_VARIANT_PTR(test, 1); #ifdef DEBUG_ENABLED bool valid; bool result = test->booleanize(valid); - if (!valid) { - err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type()); + err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type()); break; } - if (!result) { - err_text="Assertion failed."; + err_text = "Assertion failed."; break; } #endif - ip+=2; + ip += 2; continue; } case OPCODE_BREAKPOINT: { #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement",true); + GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true); } #endif - ip+=1; + ip += 1; continue; } case OPCODE_LINE: { CHECK_SPACE(2); - line=_code_ptr[ip+1]; - ip+=2; + line = _code_ptr[ip + 1]; + ip += 2; if (ScriptDebugger::get_singleton()) { // line - bool do_break=false; + bool do_break = false; - if (ScriptDebugger::get_singleton()->get_lines_left()>0) { + if (ScriptDebugger::get_singleton()->get_lines_left() > 0) { - if (ScriptDebugger::get_singleton()->get_depth()<=0) - ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 ); - if (ScriptDebugger::get_singleton()->get_lines_left()<=0) - do_break=true; + if (ScriptDebugger::get_singleton()->get_depth() <= 0) + ScriptDebugger::get_singleton()->set_lines_left(ScriptDebugger::get_singleton()->get_lines_left() - 1); + if (ScriptDebugger::get_singleton()->get_lines_left() <= 0) + do_break = true; } - if (ScriptDebugger::get_singleton()->is_breakpoint(line,source)) - do_break=true; + if (ScriptDebugger::get_singleton()->is_breakpoint(line, source)) + do_break = true; if (do_break) { - GDScriptLanguage::get_singleton()->debug_break("Breakpoint",true); + GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true); } ScriptDebugger::get_singleton()->line_poll(); - } continue; } case OPCODE_END: { - exit_ok=true; + exit_ok = true; break; - } default: { - err_text="Illegal opcode "+itos(_code_ptr[ip])+" at address "+itos(ip); + err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip); break; } - } if (exit_ok) @@ -1206,73 +1162,69 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a // function, file, line, error, explanation String err_file; if (p_instance) - err_file=p_instance->script->path; + err_file = p_instance->script->path; else if (_class) - err_file=_class->path; - if (err_file=="") - err_file="<built-in>"; + err_file = _class->path; + if (err_file == "") + err_file = "<built-in>"; String err_func = name; - if (p_instance && p_instance->script->name!="") - err_func=p_instance->script->name+"."+err_func; - int err_line=line; - if (err_text=="") { - err_text="Internal Script Error! - opcode #"+itos(last_opcode)+" (report please)."; + if (p_instance && p_instance->script->name != "") + err_func = p_instance->script->name + "." + err_func; + int err_line = line; + if (err_text == "") { + err_text = "Internal Script Error! - opcode #" + itos(last_opcode) + " (report please)."; } - if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) { + if (!GDScriptLanguage::get_singleton()->debug_break(err_text, false)) { // debugger break did not happen - _err_print_error(err_func.utf8().get_data(),err_file.utf8().get_data(),err_line,err_text.utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT); } - break; } #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->profiling) { uint64_t time_taken = OS::get_singleton()->get_ticks_usec() - function_start_time; - profile.total_time+=time_taken; - profile.self_time+=time_taken-function_call_time; - profile.frame_total_time+=time_taken; - profile.frame_self_time+=time_taken-function_call_time; - GDScriptLanguage::get_singleton()->script_frame_time+=time_taken-function_call_time; - + profile.total_time += time_taken; + profile.self_time += time_taken - function_call_time; + profile.frame_total_time += time_taken; + profile.frame_self_time += time_taken - function_call_time; + GDScriptLanguage::get_singleton()->script_frame_time += time_taken - function_call_time; } #endif if (ScriptDebugger::get_singleton()) GDScriptLanguage::get_singleton()->exit_function(); - if (_stack_size) { //free stack - for(int i=0;i<_stack_size;i++) + for (int i = 0; i < _stack_size; i++) stack[i].~Variant(); } return retvalue; - } -const int* GDFunction::get_code() const { +const int *GDFunction::get_code() const { return _code_ptr; } -int GDFunction::get_code_size() const{ +int GDFunction::get_code_size() const { return _code_size; } Variant GDFunction::get_constant(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,constants.size(),"<errconst>"); + ERR_FAIL_INDEX_V(p_idx, constants.size(), "<errconst>"); return constants[p_idx]; } StringName GDFunction::get_global_name(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,global_names.size(),"<errgname>"); + ERR_FAIL_INDEX_V(p_idx, global_names.size(), "<errgname>"); return global_names[p_idx]; } @@ -1280,13 +1232,12 @@ int GDFunction::get_default_argument_count() const { return default_arguments.size(); } -int GDFunction::get_default_argument_addr(int p_arg) const{ +int GDFunction::get_default_argument_addr(int p_arg) const { - ERR_FAIL_INDEX_V(p_arg,default_arguments.size(),-1); + ERR_FAIL_INDEX_V(p_arg, default_arguments.size(), -1); return default_arguments[p_arg]; } - StringName GDFunction::get_name() const { return name; @@ -1311,66 +1262,60 @@ struct _GDFKCS { bool operator<(const _GDFKCS &p_r) const { - return order<p_r.order; + return order < p_r.order; } }; -void GDFunction::debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const { +void GDFunction::debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const { + int oc = 0; + Map<StringName, _GDFKC> sdmap; + for (const List<StackDebug>::Element *E = stack_debug.front(); E; E = E->next()) { - int oc=0; - Map<StringName,_GDFKC> sdmap; - for( const List<StackDebug>::Element *E=stack_debug.front();E;E=E->next()) { - - const StackDebug &sd=E->get(); - if (sd.line>p_line) + const StackDebug &sd = E->get(); + if (sd.line > p_line) break; if (sd.added) { if (!sdmap.has(sd.identifier)) { _GDFKC d; - d.order=oc++; + d.order = oc++; d.pos.push_back(sd.pos); - sdmap[sd.identifier]=d; + sdmap[sd.identifier] = d; } else { sdmap[sd.identifier].pos.push_back(sd.pos); } } else { - ERR_CONTINUE(!sdmap.has(sd.identifier)); sdmap[sd.identifier].pos.pop_back(); if (sdmap[sd.identifier].pos.empty()) sdmap.erase(sd.identifier); } - } - List<_GDFKCS> stackpositions; - for(Map<StringName,_GDFKC>::Element *E=sdmap.front();E;E=E->next() ) { + for (Map<StringName, _GDFKC>::Element *E = sdmap.front(); E; E = E->next()) { _GDFKCS spp; - spp.id=E->key(); - spp.order=E->get().order; - spp.pos=E->get().pos.back()->get(); + spp.id = E->key(); + spp.order = E->get().order; + spp.pos = E->get().pos.back()->get(); stackpositions.push_back(spp); } stackpositions.sort(); - for(List<_GDFKCS>::Element *E=stackpositions.front();E;E=E->next()) { + for (List<_GDFKCS>::Element *E = stackpositions.front(); E; E = E->next()) { - Pair<StringName,int> p; - p.first=E->get().id; - p.second=E->get().pos; + Pair<StringName, int> p; + p.first = E->get().id; + p.second = E->get().pos; r_stackvars->push_back(p); } - - } #if 0 @@ -1389,14 +1334,15 @@ void GDFunction::clear() { } #endif -GDFunction::GDFunction() : function_list(this) { +GDFunction::GDFunction() + : function_list(this) { - _stack_size=0; - _call_size=0; - rpc_mode=ScriptInstance::RPC_MODE_DISABLED; - name="<anonymous>"; + _stack_size = 0; + _call_size = 0; + rpc_mode = ScriptInstance::RPC_MODE_DISABLED; + name = "<anonymous>"; #ifdef DEBUG_ENABLED - _func_cname=NULL; + _func_cname = NULL; if (GDScriptLanguage::get_singleton()->lock) { GDScriptLanguage::get_singleton()->lock->lock(); @@ -1407,20 +1353,20 @@ GDFunction::GDFunction() : function_list(this) { GDScriptLanguage::get_singleton()->lock->unlock(); } - profile.call_count=0; - profile.self_time=0; - profile.total_time=0; - profile.frame_call_count=0; - profile.frame_self_time=0; - profile.frame_total_time=0; - profile.last_frame_call_count=0; - profile.last_frame_self_time=0; - profile.last_frame_total_time=0; + profile.call_count = 0; + profile.self_time = 0; + profile.total_time = 0; + profile.frame_call_count = 0; + profile.frame_self_time = 0; + profile.frame_total_time = 0; + profile.last_frame_call_count = 0; + profile.last_frame_self_time = 0; + profile.last_frame_total_time = 0; #endif } -GDFunction::~GDFunction() { +GDFunction::~GDFunction() { #ifdef DEBUG_ENABLED if (GDScriptLanguage::get_singleton()->lock) { GDScriptLanguage::get_singleton()->lock->lock(); @@ -1435,8 +1381,7 @@ GDFunction::~GDFunction() { ///////////////////// - -Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error) { +Variant GDFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { #ifdef DEBUG_ENABLED if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { @@ -1451,51 +1396,50 @@ Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount #endif Variant arg; - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; - ERR_FAIL_COND_V(!function,Variant()); + ERR_FAIL_COND_V(!function, Variant()); - if (p_argcount==0) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; + if (p_argcount == 0) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; return Variant(); - } else if (p_argcount==1) { + } else if (p_argcount == 1) { //noooneee - } else if (p_argcount==2) { - arg=*p_args[0]; + } else if (p_argcount == 2) { + arg = *p_args[0]; } else { Array extra_args; - for(int i=0;i<p_argcount-1;i++) { + for (int i = 0; i < p_argcount - 1; i++) { extra_args.push_back(*p_args[i]); } - arg=extra_args; + arg = extra_args; } - Ref<GDFunctionState> self = *p_args[p_argcount-1]; + Ref<GDFunctionState> self = *p_args[p_argcount - 1]; if (self.is_null()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=p_argcount-1; - r_error.expected=Variant::OBJECT; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = p_argcount - 1; + r_error.expected = Variant::OBJECT; return Variant(); } - state.result=arg; - Variant ret = function->call(NULL,NULL,0,r_error,&state); - function=NULL; //cleaned up; - state.result=Variant(); + state.result = arg; + Variant ret = function->call(NULL, NULL, 0, r_error, &state); + function = NULL; //cleaned up; + state.result = Variant(); return ret; } - bool GDFunctionState::is_valid() const { - return function!=NULL; + return function != NULL; } -Variant GDFunctionState::resume(const Variant& p_arg) { +Variant GDFunctionState::resume(const Variant &p_arg) { - ERR_FAIL_COND_V(!function,Variant()); + ERR_FAIL_COND_V(!function, Variant()); #ifdef DEBUG_ENABLED if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) { ERR_EXPLAIN("Resumed after yield, but class instance is gone"); @@ -1508,36 +1452,33 @@ Variant GDFunctionState::resume(const Variant& p_arg) { } #endif - state.result=p_arg; + state.result = p_arg; Variant::CallError err; - Variant ret = function->call(NULL,NULL,0,err,&state); - function=NULL; //cleaned up; - state.result=Variant(); + Variant ret = function->call(NULL, NULL, 0, err, &state); + function = NULL; //cleaned up; + state.result = Variant(); return ret; } - void GDFunctionState::_bind_methods() { - ClassDB::bind_method(D_METHOD("resume:Variant","arg"),&GDFunctionState::resume,DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("is_valid"),&GDFunctionState::is_valid); - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"_signal_callback",&GDFunctionState::_signal_callback,MethodInfo("_signal_callback")); - + ClassDB::bind_method(D_METHOD("resume:Variant", "arg"), &GDFunctionState::resume, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("is_valid"), &GDFunctionState::is_valid); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &GDFunctionState::_signal_callback, MethodInfo("_signal_callback")); } GDFunctionState::GDFunctionState() { - function=NULL; + function = NULL; } GDFunctionState::~GDFunctionState() { - if (function!=NULL) { + if (function != NULL) { //never called, deinitialize stack - for(int i=0;i<state.stack_size;i++) { - Variant *v=(Variant*)&state.stack[sizeof(Variant)*i]; + for (int i = 0; i < state.stack_size; i++) { + Variant *v = (Variant *)&state.stack[sizeof(Variant) * i]; v->~Variant(); } } } - diff --git a/modules/gdscript/gd_function.h b/modules/gdscript/gd_function.h index aff6341601..321b3b6cfa 100644 --- a/modules/gdscript/gd_function.h +++ b/modules/gdscript/gd_function.h @@ -29,21 +29,19 @@ #ifndef GD_FUNCTION_H #define GD_FUNCTION_H -#include "self_list.h" #include "os/thread.h" #include "pair.h" -#include "variant.h" -#include "string_db.h" #include "reference.h" #include "script_language.h" +#include "self_list.h" +#include "string_db.h" +#include "variant.h" class GDInstance; class GDScript; - class GDFunction { public: - enum Opcode { OPCODE_OPERATOR, OPCODE_EXTENDS_TEST, @@ -81,18 +79,18 @@ public: }; enum Address { - ADDR_BITS=24, - ADDR_MASK=((1<<ADDR_BITS)-1), - ADDR_TYPE_MASK=~ADDR_MASK, - ADDR_TYPE_SELF=0, - ADDR_TYPE_CLASS=1, - ADDR_TYPE_MEMBER=2, - ADDR_TYPE_CLASS_CONSTANT=3, - ADDR_TYPE_LOCAL_CONSTANT=4, - ADDR_TYPE_STACK=5, - ADDR_TYPE_STACK_VARIABLE=6, - ADDR_TYPE_GLOBAL=7, - ADDR_TYPE_NIL=8 + ADDR_BITS = 24, + ADDR_MASK = ((1 << ADDR_BITS) - 1), + ADDR_TYPE_MASK = ~ADDR_MASK, + ADDR_TYPE_SELF = 0, + ADDR_TYPE_CLASS = 1, + ADDR_TYPE_MEMBER = 2, + ADDR_TYPE_CLASS_CONSTANT = 3, + ADDR_TYPE_LOCAL_CONSTANT = 4, + ADDR_TYPE_STACK = 5, + ADDR_TYPE_STACK_VARIABLE = 6, + ADDR_TYPE_GLOBAL = 7, + ADDR_TYPE_NIL = 8 }; enum RPCMode { @@ -103,16 +101,16 @@ public: RPC_SYNC_SLAVE }; - struct StackDebug { + struct StackDebug { - int line; - int pos; - bool added; - StringName identifier; - }; + int line; + int pos; + bool added; + StringName identifier; + }; private: -friend class GDCompiler; + friend class GDCompiler; StringName source; @@ -146,15 +144,15 @@ friend class GDCompiler; List<StackDebug> stack_debug; - _FORCE_INLINE_ Variant *_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self,Variant *p_stack,String& r_error) const; - _FORCE_INLINE_ String _get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const; + _FORCE_INLINE_ Variant *_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const; + _FORCE_INLINE_ String _get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const; -friend class GDScriptLanguage; + friend class GDScriptLanguage; SelfList<GDFunction> function_list; #ifdef DEBUG_ENABLED CharString func_cname; - const char*_func_cname; + const char *_func_cname; struct Profile { StringName signature; @@ -172,9 +170,6 @@ friend class GDScriptLanguage; #endif public: - - - struct CallState { ObjectID instance_id; //by debug only @@ -190,12 +185,11 @@ public: int line; int defarg; Variant result; - }; _FORCE_INLINE_ bool is_static() const { return _static; } - const int* get_code() const; //used for debug + const int *get_code() const; //used for debug int get_code_size() const; Variant get_constant(int p_idx) const; StringName get_global_name(int p_idx) const; @@ -206,48 +200,46 @@ public: GDScript *get_script() const { return _script; } StringName get_source() const { return source; } - void debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const; + void debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const; - _FORCE_INLINE_ bool is_empty() const { return _code_size==0; } + _FORCE_INLINE_ bool is_empty() const { return _code_size == 0; } int get_argument_count() const { return _argument_count; } StringName get_argument_name(int p_idx) const { #ifdef TOOLS_ENABLED - ERR_FAIL_INDEX_V(p_idx,arg_names.size(),StringName()); + ERR_FAIL_INDEX_V(p_idx, arg_names.size(), StringName()); return arg_names[p_idx]; #endif return StringName(); - } Variant get_default_argument(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx,default_arguments.size(),Variant()); + ERR_FAIL_INDEX_V(p_idx, default_arguments.size(), Variant()); return default_arguments[p_idx]; } - Variant call(GDInstance *p_instance,const Variant **p_args, int p_argcount,Variant::CallError& r_err,CallState *p_state=NULL); + Variant call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state = NULL); _FORCE_INLINE_ ScriptInstance::RPCMode get_rpc_mode() const { return rpc_mode; } GDFunction(); ~GDFunction(); }; - class GDFunctionState : public Reference { - GDCLASS(GDFunctionState,Reference); -friend class GDFunction; + GDCLASS(GDFunctionState, Reference); + friend class GDFunction; GDFunction *function; GDFunction::CallState state; - Variant _signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error); + Variant _signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error); + protected: static void _bind_methods(); -public: +public: bool is_valid() const; - Variant resume(const Variant& p_arg=Variant()); + Variant resume(const Variant &p_arg = Variant()); GDFunctionState(); ~GDFunctionState(); }; - #endif // GD_FUNCTION_H diff --git a/modules/gdscript/gd_functions.cpp b/modules/gdscript/gd_functions.cpp index d0fc241734..fa92f0a194 100644 --- a/modules/gdscript/gd_functions.cpp +++ b/modules/gdscript/gd_functions.cpp @@ -27,21 +27,21 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_functions.h" -#include "math_funcs.h" #include "class_db.h" -#include "reference.h" -#include "gd_script.h" #include "func_ref.h" +#include "gd_script.h" +#include "io/json.h" +#include "io/marshalls.h" +#include "math_funcs.h" #include "os/os.h" +#include "reference.h" #include "variant_parser.h" -#include "io/marshalls.h" -#include "io/json.h" const char *GDFunctions::get_func_name(Function p_func) { - ERR_FAIL_INDEX_V(p_func,FUNC_MAX,""); + ERR_FAIL_INDEX_V(p_func, FUNC_MAX, ""); - static const char *_names[FUNC_MAX]={ + static const char *_names[FUNC_MAX] = { "sin", "cos", "tan", @@ -115,35 +115,34 @@ const char *GDFunctions::get_func_name(Function p_func) { }; return _names[p_func]; - } -void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Variant &r_ret,Variant::CallError &r_error) { +void GDFunctions::call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error) { - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; #ifdef DEBUG_ENABLED -#define VALIDATE_ARG_COUNT(m_count) \ - if (p_arg_count<m_count) {\ - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;\ - r_error.argument=m_count;\ - r_ret=Variant();\ - return;\ - }\ - if (p_arg_count>m_count) {\ - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;\ - r_error.argument=m_count;\ - r_ret=Variant();\ - return;\ +#define VALIDATE_ARG_COUNT(m_count) \ + if (p_arg_count < m_count) { \ + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; \ + r_error.argument = m_count; \ + r_ret = Variant(); \ + return; \ + } \ + if (p_arg_count > m_count) { \ + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; \ + r_error.argument = m_count; \ + r_ret = Variant(); \ + return; \ } -#define VALIDATE_ARG_NUM(m_arg) \ - if (!p_args[m_arg]->is_num()) {\ - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\ - r_error.argument=m_arg;\ - r_error.expected=Variant::REAL;\ - r_ret=Variant();\ - return;\ +#define VALIDATE_ARG_NUM(m_arg) \ + if (!p_args[m_arg]->is_num()) { \ + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \ + r_error.argument = m_arg; \ + r_error.expected = Variant::REAL; \ + r_ret = Variant(); \ + return; \ } #else @@ -154,245 +153,245 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va //using a switch, so the compiler generates a jumptable - switch(p_func) { + switch (p_func) { case MATH_SIN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sin((double)*p_args[0]); + r_ret = Math::sin((double)*p_args[0]); } break; case MATH_COS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::cos((double)*p_args[0]); + r_ret = Math::cos((double)*p_args[0]); } break; case MATH_TAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::tan((double)*p_args[0]); + r_ret = Math::tan((double)*p_args[0]); } break; case MATH_SINH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sinh((double)*p_args[0]); + r_ret = Math::sinh((double)*p_args[0]); } break; case MATH_COSH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::cosh((double)*p_args[0]); + r_ret = Math::cosh((double)*p_args[0]); } break; case MATH_TANH: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::tanh((double)*p_args[0]); + r_ret = Math::tanh((double)*p_args[0]); } break; case MATH_ASIN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::asin((double)*p_args[0]); + r_ret = Math::asin((double)*p_args[0]); } break; case MATH_ACOS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::acos((double)*p_args[0]); + r_ret = Math::acos((double)*p_args[0]); } break; case MATH_ATAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::atan((double)*p_args[0]); + r_ret = Math::atan((double)*p_args[0]); } break; case MATH_ATAN2: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::atan2((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::atan2((double)*p_args[0], (double)*p_args[1]); } break; case MATH_SQRT: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::sqrt((double)*p_args[0]); + r_ret = Math::sqrt((double)*p_args[0]); } break; case MATH_FMOD: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::fmod((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::fmod((double)*p_args[0], (double)*p_args[1]); } break; case MATH_FPOSMOD: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::fposmod((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::fposmod((double)*p_args[0], (double)*p_args[1]); } break; case MATH_FLOOR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::floor((double)*p_args[0]); - } break; + r_ret = Math::floor((double)*p_args[0]); + } break; case MATH_CEIL: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::ceil((double)*p_args[0]); + r_ret = Math::ceil((double)*p_args[0]); } break; case MATH_ROUND: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::round((double)*p_args[0]); + r_ret = Math::round((double)*p_args[0]); } break; case MATH_ABS: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT) { int64_t i = *p_args[0]; - r_ret=ABS(i); - } else if (p_args[0]->get_type()==Variant::REAL) { + r_ret = ABS(i); + } else if (p_args[0]->get_type() == Variant::REAL) { double r = *p_args[0]; - r_ret=Math::abs(r); + r_ret = Math::abs(r); } else { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::REAL; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::REAL; + r_ret = Variant(); } } break; case MATH_SIGN: { - VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::INT) { + VALIDATE_ARG_COUNT(1); + if (p_args[0]->get_type() == Variant::INT) { - int64_t i = *p_args[0]; - r_ret= i < 0 ? -1 : ( i > 0 ? +1 : 0); - } else if (p_args[0]->get_type()==Variant::REAL) { + int64_t i = *p_args[0]; + r_ret = i < 0 ? -1 : (i > 0 ? +1 : 0); + } else if (p_args[0]->get_type() == Variant::REAL) { - real_t r = *p_args[0]; - r_ret= r < 0.0 ? -1.0 : ( r > 0.0 ? +1.0 : 0.0); - } else { + real_t r = *p_args[0]; + r_ret = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0); + } else { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::REAL; - r_ret=Variant(); - } + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::REAL; + r_ret = Variant(); + } } break; case MATH_POW: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::pow((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::pow((double)*p_args[0], (double)*p_args[1]); } break; case MATH_LOG: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::log((double)*p_args[0]); + r_ret = Math::log((double)*p_args[0]); } break; case MATH_EXP: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::exp((double)*p_args[0]); + r_ret = Math::exp((double)*p_args[0]); } break; case MATH_ISNAN: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::is_nan((double)*p_args[0]); + r_ret = Math::is_nan((double)*p_args[0]); } break; case MATH_ISINF: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::is_inf((double)*p_args[0]); + r_ret = Math::is_inf((double)*p_args[0]); } break; case MATH_EASE: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::ease((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::ease((double)*p_args[0], (double)*p_args[1]); } break; case MATH_DECIMALS: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::step_decimals((double)*p_args[0]); + r_ret = Math::step_decimals((double)*p_args[0]); } break; case MATH_STEPIFY: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::stepify((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::stepify((double)*p_args[0], (double)*p_args[1]); } break; case MATH_LERP: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - r_ret=Math::lerp((double)*p_args[0],(double)*p_args[1],(double)*p_args[2]); + r_ret = Math::lerp((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]); } break; case MATH_DECTIME: { VALIDATE_ARG_COUNT(3); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - r_ret=Math::dectime((double)*p_args[0],(double)*p_args[1],(double)*p_args[2]); + r_ret = Math::dectime((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]); } break; case MATH_RANDOMIZE: { Math::randomize(); - r_ret=Variant(); + r_ret = Variant(); } break; case MATH_RAND: { - r_ret=Math::rand(); + r_ret = Math::rand(); } break; case MATH_RANDF: { - r_ret=Math::randf(); + r_ret = Math::randf(); } break; case MATH_RANDOM: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - r_ret=Math::random((double)*p_args[0],(double)*p_args[1]); + r_ret = Math::random((double)*p_args[0], (double)*p_args[1]); } break; case MATH_SEED: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - uint64_t seed=*p_args[0]; + uint64_t seed = *p_args[0]; Math::seed(seed); - r_ret=Variant(); + r_ret = Variant(); } break; case MATH_RANDSEED: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - uint64_t seed=*p_args[0]; + uint64_t seed = *p_args[0]; int ret = Math::rand_from_seed(&seed); Array reta; reta.push_back(ret); reta.push_back(seed); - r_ret=reta; + r_ret = reta; } break; case MATH_DEG2RAD: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::deg2rad((double)*p_args[0]); + r_ret = Math::deg2rad((double)*p_args[0]); } break; case MATH_RAD2DEG: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::rad2deg((double)*p_args[0]); + r_ret = Math::rad2deg((double)*p_args[0]); } break; case MATH_LINEAR2DB: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::linear2db((double)*p_args[0]); + r_ret = Math::linear2db((double)*p_args[0]); } break; case MATH_DB2LINEAR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - r_ret=Math::db2linear((double)*p_args[0]); + r_ret = Math::db2linear((double)*p_args[0]); } break; case LOGIC_MAX: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; - r_ret=MAX(a,b); + r_ret = MAX(a, b); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -400,17 +399,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t a = *p_args[0]; real_t b = *p_args[1]; - r_ret=MAX(a,b); + r_ret = MAX(a, b); } } break; case LOGIC_MIN: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; - r_ret=MIN(a,b); + r_ret = MIN(a, b); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -418,17 +417,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t a = *p_args[0]; real_t b = *p_args[1]; - r_ret=MIN(a,b); + r_ret = MIN(a, b); } } break; case LOGIC_CLAMP: { VALIDATE_ARG_COUNT(3); - if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT && p_args[2]->get_type()==Variant::INT) { + if (p_args[0]->get_type() == Variant::INT && p_args[1]->get_type() == Variant::INT && p_args[2]->get_type() == Variant::INT) { int64_t a = *p_args[0]; int64_t b = *p_args[1]; int64_t c = *p_args[2]; - r_ret=CLAMP(a,b,c); + r_ret = CLAMP(a, b, c); } else { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); @@ -438,7 +437,7 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va real_t b = *p_args[1]; real_t c = *p_args[2]; - r_ret=CLAMP(a,b,c); + r_ret = CLAMP(a, b, c); } } break; case LOGIC_NEAREST_PO2: { @@ -449,87 +448,80 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va } break; case OBJ_WEAKREF: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::OBJECT) { + if (p_args[0]->get_type() != Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); return; - } if (p_args[0]->is_ref()) { REF r = *p_args[0]; if (!r.is_valid()) { - r_ret=Variant(); + r_ret = Variant(); return; } - Ref<WeakRef> wref = memnew( WeakRef ); + Ref<WeakRef> wref = memnew(WeakRef); wref->set_ref(r); - r_ret=wref; + r_ret = wref; } else { Object *obj = *p_args[0]; if (!obj) { - r_ret=Variant(); + r_ret = Variant(); return; } - Ref<WeakRef> wref = memnew( WeakRef ); + Ref<WeakRef> wref = memnew(WeakRef); wref->set_obj(obj); - r_ret=wref; + r_ret = wref; } - - - } break; case FUNC_FUNCREF: { VALIDATE_ARG_COUNT(2); - if (p_args[0]->get_type()!=Variant::OBJECT) { + if (p_args[0]->get_type() != Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); return; - } - if (p_args[1]->get_type()!=Variant::STRING && p_args[1]->get_type()!=Variant::NODE_PATH) { + if (p_args[1]->get_type() != Variant::STRING && p_args[1]->get_type() != Variant::NODE_PATH) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=1; - r_error.expected=Variant::STRING; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 1; + r_error.expected = Variant::STRING; + r_ret = Variant(); return; - } - Ref<FuncRef> fr = memnew( FuncRef); + Ref<FuncRef> fr = memnew(FuncRef); fr->set_instance(*p_args[0]); fr->set_function(*p_args[1]); - r_ret=fr; + r_ret = fr; } break; case TYPE_CONVERT: { VALIDATE_ARG_COUNT(2); VALIDATE_ARG_NUM(1); - int type=*p_args[1]; - if (type<0 || type>=Variant::VARIANT_MAX) { + int type = *p_args[1]; + if (type < 0 || type >= Variant::VARIANT_MAX) { - r_ret=RTR("Invalid type argument to convert(), use TYPE_* constants."); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::INT; + r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants."); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::INT; return; } else { - - r_ret=Variant::construct(Variant::Type(type),p_args,1,r_error); + r_ret = Variant::construct(Variant::Type(type), p_args, 1, r_error); } } break; case TYPE_OF: { @@ -547,125 +539,122 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va case TEXT_CHAR: { VALIDATE_ARG_COUNT(1); VALIDATE_ARG_NUM(0); - CharType result[2] = {*p_args[0], 0}; - r_ret=String(result); + CharType result[2] = { *p_args[0], 0 }; + r_ret = String(result); } break; case TEXT_STR: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); - if (i==0) - str=os; + if (i == 0) + str = os; else - str+=os; + str += os; } - r_ret=str; + r_ret = str; } break; case TEXT_PRINT: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINT_TABBED: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { if (i) - str+="\t"; - str+=p_args[i]->operator String(); + str += "\t"; + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINT_SPACED: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { if (i) - str+=" "; - str+=p_args[i]->operator String(); + str += " "; + str += p_args[i]->operator String(); } //str+="\n"; print_line(str); - r_ret=Variant(); - + r_ret = Variant(); } break; case TEXT_PRINTERR: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; - OS::get_singleton()->printerr("%s\n",str.utf8().get_data()); - r_ret=Variant(); + OS::get_singleton()->printerr("%s\n", str.utf8().get_data()); + r_ret = Variant(); } break; case TEXT_PRINTRAW: { String str; - for(int i=0;i<p_arg_count;i++) { + for (int i = 0; i < p_arg_count; i++) { - str+=p_args[i]->operator String(); + str += p_args[i]->operator String(); } //str+="\n"; - OS::get_singleton()->print("%s",str.utf8().get_data()); - r_ret=Variant(); + OS::get_singleton()->print("%s", str.utf8().get_data()); + r_ret = Variant(); } break; case VAR_TO_STR: { VALIDATE_ARG_COUNT(1); String vars; - VariantWriter::write_to_string(*p_args[0],vars); - r_ret=vars; + VariantWriter::write_to_string(*p_args[0], vars); + r_ret = vars; } break; case STR_TO_VAR: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = Variant(); return; } VariantParser::StreamString ss; - ss.s=*p_args[0]; + ss.s = *p_args[0]; String errs; int line; - Error err = VariantParser::parse(&ss,r_ret,errs,line); + Error err = VariantParser::parse(&ss, r_ret, errs, line); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret="Parse error at line "+itos(line)+": "+errs; + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = "Parse error at line " + itos(line) + ": " + errs; return; } @@ -675,106 +664,104 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va PoolByteArray barr; int len; - Error err = encode_variant(*p_args[0],NULL,len); + Error err = encode_variant(*p_args[0], NULL, len); if (err) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::NIL; - r_ret="Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::NIL; + r_ret = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."; return; } barr.resize(len); { PoolByteArray::Write w = barr.write(); - encode_variant(*p_args[0],w.ptr(),len); - + encode_variant(*p_args[0], w.ptr(), len); } - r_ret=barr; + r_ret = barr; } break; case BYTES_TO_VAR: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::POOL_BYTE_ARRAY) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::POOL_BYTE_ARRAY; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::POOL_BYTE_ARRAY) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::POOL_BYTE_ARRAY; + r_ret = Variant(); return; } - PoolByteArray varr=*p_args[0]; + PoolByteArray varr = *p_args[0]; Variant ret; { - PoolByteArray::Read r=varr.read(); - Error err = decode_variant(ret,r.ptr(),varr.size(),NULL); - if (err!=OK) { - r_ret=RTR("Not enough bytes for decoding bytes, or invalid format."); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::POOL_BYTE_ARRAY; + PoolByteArray::Read r = varr.read(); + Error err = decode_variant(ret, r.ptr(), varr.size(), NULL); + if (err != OK) { + r_ret = RTR("Not enough bytes for decoding bytes, or invalid format."); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::POOL_BYTE_ARRAY; return; } - } - r_ret=ret; + r_ret = ret; } break; case GEN_RANGE: { - switch(p_arg_count) { + switch (p_arg_count) { case 0: { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; + r_ret = Variant(); } break; case 1: { VALIDATE_ARG_NUM(0); - int count=*p_args[0]; + int count = *p_args[0]; Array arr; - if (count<=0) { - r_ret=arr; + if (count <= 0) { + r_ret = arr; return; } Error err = arr.resize(count); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - for(int i=0;i<count;i++) { - arr[i]=i; + for (int i = 0; i < count; i++) { + arr[i] = i; } - r_ret=arr; + r_ret = arr; } break; case 2: { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - int from=*p_args[0]; - int to=*p_args[1]; + int from = *p_args[0]; + int to = *p_args[1]; Array arr; - if (from>=to) { - r_ret=arr; + if (from >= to) { + r_ret = arr; return; } - Error err = arr.resize(to-from); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + Error err = arr.resize(to - from); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - for(int i=from;i<to;i++) - arr[i-from]=i; - r_ret=arr; + for (int i = from; i < to; i++) + arr[i - from] = i; + r_ret = arr; } break; case 3: { @@ -782,65 +769,64 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - int from=*p_args[0]; - int to=*p_args[1]; - int incr=*p_args[2]; - if (incr==0) { + int from = *p_args[0]; + int to = *p_args[1]; + int incr = *p_args[2]; + if (incr == 0) { - r_ret=RTR("step argument is zero!"); - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = RTR("step argument is zero!"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return; } Array arr; - if (from>=to && incr>0) { - r_ret=arr; + if (from >= to && incr > 0) { + r_ret = arr; return; } - if (from<=to && incr<0) { - r_ret=arr; + if (from <= to && incr < 0) { + r_ret = arr; return; } //calculate how many - int count=0; - if (incr>0) { + int count = 0; + if (incr > 0) { - count=((to-from-1)/incr)+1; + count = ((to - from - 1) / incr) + 1; } else { - count=((from-to-1)/-incr)+1; + count = ((from - to - 1) / -incr) + 1; } - Error err = arr.resize(count); - if (err!=OK) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; - r_ret=Variant(); + if (err != OK) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_ret = Variant(); return; } - if (incr>0) { - int idx=0; - for(int i=from;i<to;i+=incr) { - arr[idx++]=i; + if (incr > 0) { + int idx = 0; + for (int i = from; i < to; i += incr) { + arr[idx++] = i; } } else { - int idx=0; - for(int i=from;i>to;i+=incr) { - arr[idx++]=i; + int idx = 0; + for (int i = from; i > to; i += incr) { + arr[idx++] = i; } } - r_ret=arr; + r_ret = arr; } break; default: { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=3; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 3; + r_ret = Variant(); } break; } @@ -848,13 +834,13 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va } break; case RESOURCE_LOAD: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = Variant(); } else { - r_ret=ResourceLoader::load(*p_args[0]); + r_ret = ResourceLoader::load(*p_args[0]); } } break; @@ -862,91 +848,85 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()==Variant::NIL) { - r_ret=Variant(); - } else if (p_args[0]->get_type()!=Variant::OBJECT) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_ret=Variant(); + if (p_args[0]->get_type() == Variant::NIL) { + r_ret = Variant(); + } else if (p_args[0]->get_type() != Variant::OBJECT) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_ret = Variant(); } else { Object *obj = *p_args[0]; if (!obj) { - r_ret=Variant(); + r_ret = Variant(); - } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language()!=GDScriptLanguage::get_singleton()) { + } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=RTR("Not a script with an instance"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = RTR("Not a script with an instance"); return; } else { - GDInstance *ins = static_cast<GDInstance*>(obj->get_script_instance()); + GDInstance *ins = static_cast<GDInstance *>(obj->get_script_instance()); Ref<GDScript> base = ins->get_script(); if (base.is_null()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=RTR("Not based on a script"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = RTR("Not based on a script"); return; - } - GDScript *p = base.ptr(); Vector<StringName> sname; - while(p->_owner) { + while (p->_owner) { sname.push_back(p->name); - p=p->_owner; + p = p->_owner; } sname.invert(); - if (!p->path.is_resource_file()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = Variant(); - - r_ret=RTR("Not based on a resource file"); + r_ret = RTR("Not based on a resource file"); return; } - NodePath cp(sname,Vector<StringName>(),false); + NodePath cp(sname, Vector<StringName>(), false); Dictionary d; - d["@subpath"]=cp; - d["@path"]=p->path; - + d["@subpath"] = cp; + d["@path"] = p->path; p = base.ptr(); - while(p) { + while (p) { - for(Set<StringName>::Element *E=p->members.front();E;E=E->next()) { + for (Set<StringName>::Element *E = p->members.front(); E; E = E->next()) { Variant value; - if (ins->get(E->get(),value)) { + if (ins->get(E->get(), value)) { String k = E->get(); if (!d.has(k)) { - d[k]=value; + d[k] = value; } } } - p=p->_base; + p = p->_base; } - r_ret=d; - + r_ret = d; } } @@ -955,12 +935,12 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::DICTIONARY) { + if (p_args[0]->get_type() != Variant::DICTIONARY) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::DICTIONARY; - r_ret=Variant(); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::DICTIONARY; + r_ret = Variant(); return; } @@ -969,10 +949,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va if (!d.has("@path")) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=RTR("Invalid instance dictionary format (missing @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = RTR("Invalid instance dictionary format (missing @path)"); return; } @@ -980,10 +960,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va Ref<Script> scr = ResourceLoader::load(d["@path"]); if (!scr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=RTR("Invalid instance dictionary format (can't load script at @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = RTR("Invalid instance dictionary format (can't load script at @path)"); return; } @@ -991,40 +971,40 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va if (!gdscr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); - r_ret=RTR("Invalid instance dictionary format (invalid script at @path)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); + r_ret = RTR("Invalid instance dictionary format (invalid script at @path)"); return; } NodePath sub; if (d.has("@subpath")) { - sub=d["@subpath"]; + sub = d["@subpath"]; } - for(int i=0;i<sub.get_name_count();i++) { + for (int i = 0; i < sub.get_name_count(); i++) { - gdscr = gdscr->subclasses[ sub.get_name(i)]; + gdscr = gdscr->subclasses[sub.get_name(i)]; if (!gdscr.is_valid()) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::OBJECT; - r_ret=Variant(); - r_ret=RTR("Invalid instance dictionary (invalid subclasses)"); + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::OBJECT; + r_ret = Variant(); + r_ret = RTR("Invalid instance dictionary (invalid subclasses)"); return; } } - r_ret = gdscr->_new(NULL,0,r_error); + r_ret = gdscr->_new(NULL, 0, r_error); - GDInstance *ins = static_cast<GDInstance*>(static_cast<Object*>(r_ret)->get_script_instance()); + GDInstance *ins = static_cast<GDInstance *>(static_cast<Object *>(r_ret)->get_script_instance()); Ref<GDScript> gd_ref = ins->get_script(); - for(Map<StringName,GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) { - if(d.has(E->key())) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) { + if (d.has(E->key())) { ins->members[E->get().index] = d[E->key()]; } } @@ -1034,23 +1014,23 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = Variant(); return; } String errs; int errl; - Error err = JSON::parse(*p_args[0],r_ret,errs,errl); + Error err = JSON::parse(*p_args[0], r_ret, errs, errl); - if (err!=OK) { - r_ret=itos(errl)+":"+errs; + if (err != OK) { + r_ret = itos(errl) + ":" + errs; } else { - r_ret=""; + r_ret = ""; } } break; @@ -1058,21 +1038,21 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::STRING; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::STRING; + r_ret = Variant(); return; } String errs; int errl; - Error err = JSON::parse(*p_args[0],r_ret,errs,errl); + Error err = JSON::parse(*p_args[0], r_ret, errs, errl); - if (err!=OK) { - r_ret=Variant(); + if (err != OK) { + r_ret = Variant(); } } break; @@ -1084,22 +1064,22 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va case HASH: { VALIDATE_ARG_COUNT(1); - r_ret=p_args[0]->hash(); + r_ret = p_args[0]->hash(); } break; case COLOR8: { - if (p_arg_count<3) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=3; - r_ret=Variant(); + if (p_arg_count < 3) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 3; + r_ret = Variant(); return; } - if (p_arg_count>4) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=4; - r_ret=Variant(); + if (p_arg_count > 4) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 4; + r_ret = Variant(); return; } @@ -1108,78 +1088,76 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va VALIDATE_ARG_NUM(1); VALIDATE_ARG_NUM(2); - Color color((float)*p_args[0]/255.0f,(float)*p_args[1]/255.0f,(float)*p_args[2]/255.0f); + Color color((float)*p_args[0] / 255.0f, (float)*p_args[1] / 255.0f, (float)*p_args[2] / 255.0f); - if (p_arg_count==4) { + if (p_arg_count == 4) { VALIDATE_ARG_NUM(3); - color.a=(float)*p_args[3]/255.0f; + color.a = (float)*p_args[3] / 255.0f; } - r_ret=color; + r_ret = color; } break; case COLORN: { - if (p_arg_count<1) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument=1; - r_ret=Variant(); + if (p_arg_count < 1) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; + r_ret = Variant(); return; } - if (p_arg_count>2) { - r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; - r_error.argument=2; - r_ret=Variant(); + if (p_arg_count > 2) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; + r_error.argument = 2; + r_ret = Variant(); return; } - - if (p_args[0]->get_type()!=Variant::STRING) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_ret=Variant(); + + if (p_args[0]->get_type() != Variant::STRING) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_ret = Variant(); } else { Color color = Color::named(*p_args[0]); - if (p_arg_count==2) { + if (p_arg_count == 2) { VALIDATE_ARG_NUM(1); - color.a=*p_args[1]; + color.a = *p_args[1]; } - r_ret=color; + r_ret = color; } } break; case PRINT_STACK: { - ScriptLanguage* script = GDScriptLanguage::get_singleton(); - for (int i=0; i < script->debug_get_stack_level_count(); i++) { + ScriptLanguage *script = GDScriptLanguage::get_singleton(); + for (int i = 0; i < script->debug_get_stack_level_count(); i++) { - print_line("Frame "+itos(i)+" - "+script->debug_get_stack_level_source(i)+":"+itos(script->debug_get_stack_level_line(i))+" in function '"+script->debug_get_stack_level_function(i)+"'"); + print_line("Frame " + itos(i) + " - " + script->debug_get_stack_level_source(i) + ":" + itos(script->debug_get_stack_level_line(i)) + " in function '" + script->debug_get_stack_level_function(i) + "'"); }; } break; case INSTANCE_FROM_ID: { VALIDATE_ARG_COUNT(1); - if (p_args[0]->get_type()!=Variant::INT && p_args[0]->get_type()!=Variant::REAL) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument=0; - r_error.expected=Variant::INT; - r_ret=Variant(); + if (p_args[0]->get_type() != Variant::INT && p_args[0]->get_type() != Variant::REAL) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = 0; + r_error.expected = Variant::INT; + r_ret = Variant(); break; } - uint32_t id=*p_args[0]; - r_ret=ObjectDB::get_instance(id); + uint32_t id = *p_args[0]; + r_ret = ObjectDB::get_instance(id); } break; case FUNC_MAX: { ERR_FAIL(); } break; - } - } bool GDFunctions::is_deterministic(Function p_func) { @@ -1187,7 +1165,7 @@ bool GDFunctions::is_deterministic(Function p_func) { //man i couldn't have chosen a worse function name, //way too controversial.. - switch(p_func) { + switch (p_func) { case MATH_SIN: case MATH_COS: @@ -1231,16 +1209,13 @@ bool GDFunctions::is_deterministic(Function p_func) { case TEXT_CHAR: case TEXT_STR: case COLOR8: -// enable for debug only, otherwise not desirable - case GEN_RANGE: + // enable for debug only, otherwise not desirable - case GEN_RANGE: return true; default: return false; - } return false; - - } MethodInfo GDFunctions::get_info(Function p_func) { @@ -1248,401 +1223,401 @@ MethodInfo GDFunctions::get_info(Function p_func) { #ifdef TOOLS_ENABLED //using a switch, so the compiler generates a jumptable - switch(p_func) { + switch (p_func) { case MATH_SIN: { - MethodInfo mi("sin",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sin", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_COS: { - MethodInfo mi("cos",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("cos", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_TAN: { - MethodInfo mi("tan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("tan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SINH: { - MethodInfo mi("sinh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sinh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_COSH: { - MethodInfo mi("cosh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("cosh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_TANH: { - MethodInfo mi("tanh",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("tanh", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ASIN: { - MethodInfo mi("asin",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("asin", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ACOS: { - MethodInfo mi("acos",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("acos", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ATAN: { - MethodInfo mi("atan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("atan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ATAN2: { - MethodInfo mi("atan2",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("atan2", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SQRT: { - MethodInfo mi("sqrt",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sqrt", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FMOD: { - MethodInfo mi("fmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FPOSMOD: { - MethodInfo mi("fposmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_FLOOR: { - MethodInfo mi("floor",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("floor", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; - } break; + } break; case MATH_CEIL: { - MethodInfo mi("ceil",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("ceil", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ROUND: { - MethodInfo mi("round",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("round", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ABS: { - MethodInfo mi("abs",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("abs", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SIGN: { - MethodInfo mi("sign",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("sign", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_POW: { - MethodInfo mi("pow",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("pow", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LOG: { - MethodInfo mi("log",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("log", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_EXP: { - MethodInfo mi("exp",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("exp", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ISNAN: { - MethodInfo mi("is_nan",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("is_nan", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_ISINF: { - MethodInfo mi("is_inf",PropertyInfo(Variant::REAL,"s")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("is_inf", PropertyInfo(Variant::REAL, "s")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_EASE: { - MethodInfo mi("ease",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"curve")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("ease", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "curve")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DECIMALS: { - MethodInfo mi("decimals",PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("decimals", PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_STEPIFY: { - MethodInfo mi("stepify",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("stepify", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LERP: { - MethodInfo mi("lerp",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to"), PropertyInfo(Variant::REAL,"weight")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("lerp", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DECTIME: { - MethodInfo mi("dectime",PropertyInfo(Variant::REAL,"value"),PropertyInfo(Variant::REAL,"amount"),PropertyInfo(Variant::REAL,"step")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("dectime", PropertyInfo(Variant::REAL, "value"), PropertyInfo(Variant::REAL, "amount"), PropertyInfo(Variant::REAL, "step")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RANDOMIZE: { MethodInfo mi("randomize"); - mi.return_val.type=Variant::NIL; + mi.return_val.type = Variant::NIL; return mi; } break; case MATH_RAND: { MethodInfo mi("randi"); - mi.return_val.type=Variant::INT; + mi.return_val.type = Variant::INT; return mi; } break; case MATH_RANDF: { MethodInfo mi("randf"); - mi.return_val.type=Variant::REAL; + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RANDOM: { - MethodInfo mi("rand_range",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("rand_range", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_SEED: { - MethodInfo mi("seed",PropertyInfo(Variant::INT,"seed")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("seed", PropertyInfo(Variant::INT, "seed")); + mi.return_val.type = Variant::NIL; return mi; } break; case MATH_RANDSEED: { - MethodInfo mi("rand_seed",PropertyInfo(Variant::INT,"seed")); - mi.return_val.type=Variant::ARRAY; + MethodInfo mi("rand_seed", PropertyInfo(Variant::INT, "seed")); + mi.return_val.type = Variant::ARRAY; return mi; } break; case MATH_DEG2RAD: { - MethodInfo mi("deg2rad",PropertyInfo(Variant::REAL,"deg")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("deg2rad", PropertyInfo(Variant::REAL, "deg")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_RAD2DEG: { - MethodInfo mi("rad2deg",PropertyInfo(Variant::REAL,"rad")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("rad2deg", PropertyInfo(Variant::REAL, "rad")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_LINEAR2DB: { - MethodInfo mi("linear2db",PropertyInfo(Variant::REAL,"nrg")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("linear2db", PropertyInfo(Variant::REAL, "nrg")); + mi.return_val.type = Variant::REAL; return mi; } break; case MATH_DB2LINEAR: { - MethodInfo mi("db2linear",PropertyInfo(Variant::REAL,"db")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("db2linear", PropertyInfo(Variant::REAL, "db")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_MAX: { - MethodInfo mi("max",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("max", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_MIN: { - MethodInfo mi("min",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("min", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_CLAMP: { - MethodInfo mi("clamp",PropertyInfo(Variant::REAL,"val"),PropertyInfo(Variant::REAL,"min"),PropertyInfo(Variant::REAL,"max")); - mi.return_val.type=Variant::REAL; + MethodInfo mi("clamp", PropertyInfo(Variant::REAL, "val"), PropertyInfo(Variant::REAL, "min"), PropertyInfo(Variant::REAL, "max")); + mi.return_val.type = Variant::REAL; return mi; } break; case LOGIC_NEAREST_PO2: { - MethodInfo mi("nearest_po2",PropertyInfo(Variant::INT,"val")); - mi.return_val.type=Variant::INT; + MethodInfo mi("nearest_po2", PropertyInfo(Variant::INT, "val")); + mi.return_val.type = Variant::INT; return mi; } break; case OBJ_WEAKREF: { - MethodInfo mi("weakref",PropertyInfo(Variant::OBJECT,"obj")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="WeakRef"; + MethodInfo mi("weakref", PropertyInfo(Variant::OBJECT, "obj")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "WeakRef"; return mi; } break; case FUNC_FUNCREF: { - MethodInfo mi("funcref",PropertyInfo(Variant::OBJECT,"instance"),PropertyInfo(Variant::STRING,"funcname")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="FuncRef"; + MethodInfo mi("funcref", PropertyInfo(Variant::OBJECT, "instance"), PropertyInfo(Variant::STRING, "funcname")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "FuncRef"; return mi; } break; case TYPE_CONVERT: { - MethodInfo mi("convert",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::INT,"type")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::INT, "type")); + mi.return_val.type = Variant::OBJECT; return mi; } break; case TYPE_OF: { - MethodInfo mi("typeof",PropertyInfo(Variant::NIL,"what")); - mi.return_val.type=Variant::INT; + MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what")); + mi.return_val.type = Variant::INT; return mi; } break; case TYPE_EXISTS: { - MethodInfo mi("type_exists",PropertyInfo(Variant::STRING,"type")); - mi.return_val.type=Variant::BOOL; + MethodInfo mi("type_exists", PropertyInfo(Variant::STRING, "type")); + mi.return_val.type = Variant::BOOL; return mi; } break; case TEXT_CHAR: { - MethodInfo mi("char",PropertyInfo(Variant::INT,"ascii")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("char", PropertyInfo(Variant::INT, "ascii")); + mi.return_val.type = Variant::STRING; return mi; } break; case TEXT_STR: { - MethodInfo mi("str",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("str", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::STRING; return mi; } break; case TEXT_PRINT: { - MethodInfo mi("print",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("print", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINT_TABBED: { - MethodInfo mi("printt",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printt", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINT_SPACED: { - MethodInfo mi("prints",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("prints", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINTERR: { - MethodInfo mi("printerr",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printerr", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case TEXT_PRINTRAW: { - MethodInfo mi("printraw",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("printraw", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::NIL; return mi; } break; case VAR_TO_STR: { - MethodInfo mi("var2str",PropertyInfo(Variant::NIL,"var")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var")); + mi.return_val.type = Variant::STRING; return mi; } break; case STR_TO_VAR: { - MethodInfo mi("str2var:Variant",PropertyInfo(Variant::STRING,"string")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("str2var:Variant", PropertyInfo(Variant::STRING, "string")); + mi.return_val.type = Variant::NIL; return mi; } break; case VAR_TO_BYTES: { - MethodInfo mi("var2bytes",PropertyInfo(Variant::NIL,"var")); - mi.return_val.type=Variant::POOL_BYTE_ARRAY; + MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var")); + mi.return_val.type = Variant::POOL_BYTE_ARRAY; return mi; } break; case BYTES_TO_VAR: { - MethodInfo mi("bytes2var:Variant",PropertyInfo(Variant::POOL_BYTE_ARRAY,"bytes")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("bytes2var:Variant", PropertyInfo(Variant::POOL_BYTE_ARRAY, "bytes")); + mi.return_val.type = Variant::NIL; return mi; } break; case GEN_RANGE: { - MethodInfo mi("range",PropertyInfo(Variant::NIL,"...")); - mi.return_val.type=Variant::ARRAY; + MethodInfo mi("range", PropertyInfo(Variant::NIL, "...")); + mi.return_val.type = Variant::ARRAY; return mi; } break; case RESOURCE_LOAD: { - MethodInfo mi("load",PropertyInfo(Variant::STRING,"path")); - mi.return_val.type=Variant::OBJECT; - mi.return_val.name="Resource"; + MethodInfo mi("load", PropertyInfo(Variant::STRING, "path")); + mi.return_val.type = Variant::OBJECT; + mi.return_val.name = "Resource"; return mi; } break; case INST2DICT: { - MethodInfo mi("inst2dict",PropertyInfo(Variant::OBJECT,"inst")); - mi.return_val.type=Variant::DICTIONARY; + MethodInfo mi("inst2dict", PropertyInfo(Variant::OBJECT, "inst")); + mi.return_val.type = Variant::DICTIONARY; return mi; } break; case DICT2INST: { - MethodInfo mi("dict2inst",PropertyInfo(Variant::DICTIONARY,"dict")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("dict2inst", PropertyInfo(Variant::DICTIONARY, "dict")); + mi.return_val.type = Variant::OBJECT; return mi; } break; case VALIDATE_JSON: { - MethodInfo mi("validate_json:Variant",PropertyInfo(Variant::STRING,"json")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("validate_json:Variant", PropertyInfo(Variant::STRING, "json")); + mi.return_val.type = Variant::STRING; return mi; } break; case PARSE_JSON: { - MethodInfo mi("parse_json:Variant",PropertyInfo(Variant::STRING,"json")); - mi.return_val.type=Variant::NIL; + MethodInfo mi("parse_json:Variant", PropertyInfo(Variant::STRING, "json")); + mi.return_val.type = Variant::NIL; return mi; } break; case TO_JSON: { - MethodInfo mi("to_json",PropertyInfo(Variant::NIL,"var:Variant")); - mi.return_val.type=Variant::STRING; + MethodInfo mi("to_json", PropertyInfo(Variant::NIL, "var:Variant")); + mi.return_val.type = Variant::STRING; return mi; } break; case HASH: { - MethodInfo mi("hash",PropertyInfo(Variant::NIL,"var:Variant")); - mi.return_val.type=Variant::INT; + MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var:Variant")); + mi.return_val.type = Variant::INT; return mi; } break; case COLOR8: { - MethodInfo mi("Color8",PropertyInfo(Variant::INT,"r8"),PropertyInfo(Variant::INT,"g8"),PropertyInfo(Variant::INT,"b8"),PropertyInfo(Variant::INT,"a8")); - mi.return_val.type=Variant::COLOR; + MethodInfo mi("Color8", PropertyInfo(Variant::INT, "r8"), PropertyInfo(Variant::INT, "g8"), PropertyInfo(Variant::INT, "b8"), PropertyInfo(Variant::INT, "a8")); + mi.return_val.type = Variant::COLOR; return mi; } break; case COLORN: { - MethodInfo mi("ColorN",PropertyInfo(Variant::STRING,"name"),PropertyInfo(Variant::REAL,"alpha")); - mi.return_val.type=Variant::COLOR; + MethodInfo mi("ColorN", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::REAL, "alpha")); + mi.return_val.type = Variant::COLOR; return mi; } break; case PRINT_STACK: { MethodInfo mi("print_stack"); - mi.return_val.type=Variant::NIL; + mi.return_val.type = Variant::NIL; return mi; } break; case INSTANCE_FROM_ID: { - MethodInfo mi("instance_from_id",PropertyInfo(Variant::INT,"instance_id")); - mi.return_val.type=Variant::OBJECT; + MethodInfo mi("instance_from_id", PropertyInfo(Variant::INT, "instance_id")); + mi.return_val.type = Variant::OBJECT; return mi; } break; @@ -1650,7 +1625,6 @@ MethodInfo GDFunctions::get_info(Function p_func) { ERR_FAIL_V(MethodInfo()); } break; - } #endif diff --git a/modules/gdscript/gd_functions.h b/modules/gdscript/gd_functions.h index 6e30b4dbb5..cde1a9210d 100644 --- a/modules/gdscript/gd_functions.h +++ b/modules/gdscript/gd_functions.h @@ -33,7 +33,6 @@ class GDFunctions { public: - enum Function { MATH_SIN, MATH_COS, @@ -110,10 +109,9 @@ public: }; static const char *get_func_name(Function p_func); - static void call(Function p_func,const Variant **p_args,int p_arg_count,Variant &r_ret,Variant::CallError &r_error); + static void call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error); static bool is_deterministic(Function p_func); static MethodInfo get_info(Function p_func); - }; #endif // GD_FUNCTIONS_H diff --git a/modules/gdscript/gd_parser.cpp b/modules/gdscript/gd_parser.cpp index 5147ccd63f..86b97e27a9 100644 --- a/modules/gdscript/gd_parser.cpp +++ b/modules/gdscript/gd_parser.cpp @@ -27,74 +27,72 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_parser.h" -#include "print_string.h" +#include "gd_script.h" #include "io/resource_loader.h" #include "os/file_access.h" +#include "print_string.h" #include "script_language.h" -#include "gd_script.h" -template<class T> -T* GDParser::alloc_node() { +template <class T> +T *GDParser::alloc_node() { - T *t = memnew( T); + T *t = memnew(T); - t->next=list; - list=t; + t->next = list; + list = t; if (!head) - head=t; + head = t; - t->line=tokenizer->get_token_line(); - t->column=tokenizer->get_token_column(); + t->line = tokenizer->get_token_line(); + t->column = tokenizer->get_token_column(); return t; - } bool GDParser::_end_statement() { - if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) { tokenizer->advance(); return true; //handle next - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) { return true; //will be handled properly } return false; } -bool GDParser::_enter_indent_block(BlockNode* p_block) { - +bool GDParser::_enter_indent_block(BlockNode *p_block) { - if (tokenizer->get_token()!=GDTokenizer::TK_COLON) { + if (tokenizer->get_token() != GDTokenizer::TK_COLON) { // report location at the previous token (on the previous line) int error_line = tokenizer->get_token_line(-1); int error_column = tokenizer->get_token_column(-1); - _set_error("':' expected at end of line.",error_line,error_column); + _set_error("':' expected at end of line.", error_line, error_column); return false; } tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) { // be more python-like int current = tab_level.back()->get(); - tab_level.push_back(current+1); + tab_level.push_back(current + 1); return true; //_set_error("newline expected after ':'."); //return false; } - while(true) { + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) { return false; //wtf - } else if (tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); int current = tab_level.back()->get(); - if (indent<=current) { - print_line("current: "+itos(current)+" indent: "+itos(indent)); + if (indent <= current) { + print_line("current: " + itos(current) + " indent: " + itos(indent)); print_line("less than current"); return false; } @@ -106,52 +104,51 @@ bool GDParser::_enter_indent_block(BlockNode* p_block) { } else if (p_block) { NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); - } tokenizer->advance(); // go to next newline } } -bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_static,bool p_can_codecomplete) { +bool GDParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete) { - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); } else { - parenthesis ++; - int argidx=0; + parenthesis++; + int argidx = 0; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(argidx); - completion_node=p_parent; - } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING && tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) { + completion_node = p_parent; + } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING && tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) { //completing a string argument.. - completion_cursor=tokenizer->get_token_constant(); + completion_cursor = tokenizer->get_token_constant(); _make_completable_call(argidx); - completion_node=p_parent; + completion_node = p_parent; tokenizer->advance(1); return false; } - Node*arg = _parse_expression(p_parent,p_static); + Node *arg = _parse_expression(p_parent, p_static); if (!arg) return false; p_args.push_back(arg); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { - if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expression expected"); return false; @@ -164,57 +161,52 @@ bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_stat _set_error("Expected ',' or ')'"); return false; } - } - parenthesis --; + parenthesis--; } return true; - } - void GDParser::_make_completable_call(int p_arg) { - completion_cursor=StringName(); - completion_type=COMPLETION_CALL_ARGUMENTS; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_argument=p_arg; - completion_block=current_block; - completion_found=true; + completion_cursor = StringName(); + completion_type = COMPLETION_CALL_ARGUMENTS; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_argument = p_arg; + completion_block = current_block; + completion_found = true; tokenizer->advance(); - } +bool GDParser::_get_completable_identifier(CompletionType p_type, StringName &identifier) { -bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& identifier) { - - identifier=StringName(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { - identifier=tokenizer->get_token_identifier(); + identifier = StringName(); + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { + identifier = tokenizer->get_token_identifier(); tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { - - completion_cursor=identifier; - completion_type=p_type; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_block=current_block; - completion_found=true; - completion_ident_is_call=false; + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { + + completion_cursor = identifier; + completion_type = p_type; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_block = current_block; + completion_found = true; + completion_ident_is_call = false; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { - identifier=identifier.operator String() + tokenizer->get_token_identifier().operator String(); + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { + identifier = identifier.operator String() + tokenizer->get_token_identifier().operator String(); tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { - completion_ident_is_call=true; + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { + completion_ident_is_call = true; } return true; } @@ -222,132 +214,129 @@ bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& ide return false; } - -GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_allow_assign,bool p_parsing_constant) { +GDParser::Node *GDParser::_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign, bool p_parsing_constant) { //Vector<Node*> expressions; //Vector<OperatorNode::Operator> operators; Vector<Expression> expression; - Node *expr=NULL; + Node *expr = NULL; int op_line = tokenizer->get_token_line(); // when operators are created at the bottom, the line might have been changed (\n found) - while(true) { - + while (true) { /*****************/ /* Parse Operand */ /*****************/ - if (parenthesis>0) { + if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } } - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { //subexpression () tokenizer->advance(); parenthesis++; - Node* subexpr = _parse_expression(p_parent,p_static,p_allow_assign,p_parsing_constant); + Node *subexpr = _parse_expression(p_parent, p_static, p_allow_assign, p_parsing_constant); parenthesis--; if (!subexpr) return NULL; - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in expression"); return NULL; } tokenizer->advance(); - expr=subexpr; - } else if (tokenizer->get_token()==GDTokenizer::TK_DOLLAR) { + expr = subexpr; + } else if (tokenizer->get_token() == GDTokenizer::TK_DOLLAR) { tokenizer->advance(); String path; - bool need_identifier=true; - bool done=false; + bool need_identifier = true; + bool done = false; - while(!done) { + while (!done) { - switch(tokenizer->get_token()) { + switch (tokenizer->get_token()) { case GDTokenizer::TK_CURSOR: { - completion_cursor=StringName(); - completion_type=COMPLETION_GET_NODE; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_cursor=path; - completion_argument=0; - completion_block=current_block; - completion_found=true; + completion_cursor = StringName(); + completion_type = COMPLETION_GET_NODE; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_cursor = path; + completion_argument = 0; + completion_block = current_block; + completion_found = true; tokenizer->advance(); } break; case GDTokenizer::TK_CONSTANT: { if (!need_identifier) { - done=true; + done = true; break; } - if (tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token_constant().get_type() != Variant::STRING) { _set_error("Expected string constant or identifier after '$' or '/'."); return NULL; } - path+=String(tokenizer->get_token_constant()); + path += String(tokenizer->get_token_constant()); tokenizer->advance(); - need_identifier=false; + need_identifier = false; } break; case GDTokenizer::TK_IDENTIFIER: { if (!need_identifier) { - done=true; + done = true; break; } - path+=String(tokenizer->get_token_identifier()); + path += String(tokenizer->get_token_identifier()); tokenizer->advance(); - need_identifier=false; + need_identifier = false; } break; case GDTokenizer::TK_OP_DIV: { if (need_identifier) { - done=true; + done = true; break; } - path+="/"; + path += "/"; tokenizer->advance(); - need_identifier=true; + need_identifier = true; } break; default: { - done=true; + done = true; break; } } } - if (path=="") { + if (path == "") { _set_error("Path expected after $."); return NULL; - } OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_CALL; + op->op = OperatorNode::OP_CALL; op->arguments.push_back(alloc_node<SelfNode>()); IdentifierNode *funcname = alloc_node<IdentifierNode>(); - funcname->name="get_node"; + funcname->name = "get_node"; op->arguments.push_back(funcname); @@ -355,47 +344,45 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ nodepath->value = NodePath(StringName(path)); op->arguments.push_back(nodepath); - expr=op; + expr = op; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { tokenizer->advance(); continue; //no point in cursor in the middle of expression - } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=tokenizer->get_token_constant(); + constant->value = tokenizer->get_token_constant(); tokenizer->advance(); - expr=constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_CONST_PI) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_PI) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=Math_PI; + constant->value = Math_PI; tokenizer->advance(); - expr=constant; - } - else if (tokenizer->get_token() == GDTokenizer::TK_CONST_INF) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_INF) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_INF; tokenizer->advance(); expr = constant; - } - else if (tokenizer->get_token() == GDTokenizer::TK_CONST_NAN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_NAN) { //constant defined by tokenizer ConstantNode *constant = alloc_node<ConstantNode>(); constant->value = Math_NAN; tokenizer->advance(); expr = constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_PR_PRELOAD) { + } else if (tokenizer->get_token() == GDTokenizer::TK_PR_PRELOAD) { //constant defined by tokenizer tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after 'preload'"); return NULL; } @@ -409,18 +396,18 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ Node *subexpr = _parse_and_reduce_expression(p_parent, p_static); if (subexpr) { if (subexpr->type == Node::TYPE_CONSTANT) { - cn = static_cast<ConstantNode*>(subexpr); + cn = static_cast<ConstantNode *>(subexpr); found_constant = true; } if (subexpr->type == Node::TYPE_IDENTIFIER) { - IdentifierNode *in = static_cast<IdentifierNode*>(subexpr); + IdentifierNode *in = static_cast<IdentifierNode *>(subexpr); Vector<ClassNode::Constant> ce = current_class->constant_expressions; // Try to find the constant expression by the identifier - for(int i=0; i < ce.size(); ++i){ - if(ce[i].identifier == in->name) { - if(ce[i].expression->type == Node::TYPE_CONSTANT) { - cn = static_cast<ConstantNode*>(ce[i].expression); + for (int i = 0; i < ce.size(); ++i) { + if (ce[i].identifier == in->name) { + if (ce[i].expression->type == Node::TYPE_CONSTANT) { + cn = static_cast<ConstantNode *>(ce[i].expression); found_constant = true; } } @@ -429,7 +416,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ if (found_constant && cn->value.get_type() == Variant::STRING) { valid = true; - path = (String) cn->value; + path = (String)cn->value; } } @@ -438,17 +425,15 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - if (!path.is_abs_path() && base_path!="") - path=base_path+"/"+path; - path = path.replace("///","//").simplify_path(); - if (path==self_path) { + if (!path.is_abs_path() && base_path != "") + path = base_path + "/" + path; + path = path.replace("///", "//").simplify_path(); + if (path == self_path) { _set_error("Can't preload itself (use 'get_script()')."); return NULL; - } - Ref<Resource> res; if (!validating) { @@ -459,33 +444,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ res = ResourceLoader::load(path); } if (!res.is_valid()) { - _set_error("Can't preload resource at path: "+path); + _set_error("Can't preload resource at path: " + path); return NULL; } } else { if (!FileAccess::exists(path)) { - _set_error("Can't preload resource at path: "+path); + _set_error("Can't preload resource at path: " + path); return NULL; } } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' after 'preload' path"); return NULL; } ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value=res; + constant->value = res; tokenizer->advance(); - expr=constant; - } else if (tokenizer->get_token()==GDTokenizer::TK_PR_YIELD) { + expr = constant; + } else if (tokenizer->get_token() == GDTokenizer::TK_PR_YIELD) { //constant defined by tokenizer tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after 'yield'"); return NULL; } @@ -493,65 +478,63 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ tokenizer->advance(); OperatorNode *yield = alloc_node<OperatorNode>(); - yield->op=OperatorNode::OP_YIELD; + yield->op = OperatorNode::OP_YIELD; - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { - expr=yield; + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { + expr = yield; tokenizer->advance(); } else { - parenthesis ++; + parenthesis++; - Node *object = _parse_and_reduce_expression(p_parent,p_static); + Node *object = _parse_and_reduce_expression(p_parent, p_static); if (!object) return NULL; yield->arguments.push_back(object); - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ',' after first argument of 'yield'"); return NULL; } tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { - - - completion_cursor=StringName(); - completion_node=object; - completion_type=COMPLETION_YIELD; - completion_class=current_class; - completion_function=current_function; - completion_line=tokenizer->get_token_line(); - completion_argument=0; - completion_block=current_block; - completion_found=true; + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { + + completion_cursor = StringName(); + completion_node = object; + completion_type = COMPLETION_YIELD; + completion_class = current_class; + completion_function = current_function; + completion_line = tokenizer->get_token_line(); + completion_argument = 0; + completion_block = current_block; + completion_found = true; tokenizer->advance(); } - Node *signal = _parse_and_reduce_expression(p_parent,p_static); + Node *signal = _parse_and_reduce_expression(p_parent, p_static); if (!signal) return NULL; yield->arguments.push_back(signal); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' after second argument of 'yield'"); return NULL; } - parenthesis --; + parenthesis--; tokenizer->advance(); - expr=yield; + expr = yield; } - - } else if (tokenizer->get_token()==GDTokenizer::TK_SELF) { + } else if (tokenizer->get_token() == GDTokenizer::TK_SELF) { if (p_static) { _set_error("'self'' not allowed in static function or constant expression"); @@ -560,51 +543,50 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ //constant defined by tokenizer SelfNode *self = alloc_node<SelfNode>(); tokenizer->advance(); - expr=self; - } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1)==GDTokenizer::TK_PERIOD) { + expr = self; + } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) { Variant::Type bi_type = tokenizer->get_token_type(); tokenizer->advance(2); StringName identifier; - if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT,identifier)) { + if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT, identifier)) { - completion_built_in_constant=bi_type; + completion_built_in_constant = bi_type; } - if (identifier==StringName()) { + if (identifier == StringName()) { _set_error("Built-in type constant expected after '.'"); return NULL; } - if (!Variant::has_numeric_constant(bi_type,identifier)) { + if (!Variant::has_numeric_constant(bi_type, identifier)) { - _set_error("Static constant '"+identifier.operator String()+"' not present in built-in type "+Variant::get_type_name(bi_type)+"."); + _set_error("Static constant '" + identifier.operator String() + "' not present in built-in type " + Variant::get_type_name(bi_type) + "."); return NULL; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=Variant::get_numeric_constant_value(bi_type,identifier); - expr=cn; + cn->value = Variant::get_numeric_constant_value(bi_type, identifier); + expr = cn; - - } else if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC)) { + } else if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC)) { //function or constructor OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_CALL; + op->op = OperatorNode::OP_CALL; - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) { TypeNode *tn = alloc_node<TypeNode>(); - tn->vtype=tokenizer->get_token_type(); + tn->vtype = tokenizer->get_token_type(); op->arguments.push_back(tn); tokenizer->advance(2); - } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) { BuiltInFunctionNode *bn = alloc_node<BuiltInFunctionNode>(); - bn->function=tokenizer->get_token_built_in_func(); + bn->function = tokenizer->get_token_built_in_func(); op->arguments.push_back(bn); tokenizer->advance(2); } else { @@ -613,43 +595,40 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(self); StringName identifier; - if (_get_completable_identifier(COMPLETION_FUNCTION,identifier)) { - + if (_get_completable_identifier(COMPLETION_FUNCTION, identifier)) { } - IdentifierNode* id = alloc_node<IdentifierNode>(); - id->name=identifier; + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = identifier; op->arguments.push_back(id); tokenizer->advance(1); } - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(0); - completion_node=op; - + completion_node = op; } - if (!_parse_arguments(op,op->arguments,p_static,true)) + if (!_parse_arguments(op, op->arguments, p_static, true)) return NULL; - expr=op; + expr = op; - } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { + } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { //identifier (reference) - const ClassNode* cln = current_class; - bool bfn = false; - StringName identifier; - if (_get_completable_identifier(COMPLETION_IDENTIFIER,identifier)) { - + const ClassNode *cln = current_class; + bool bfn = false; + StringName identifier; + if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) { } if (p_parsing_constant) { - for( int i=0; i<cln->constant_expressions.size(); ++i ) { + for (int i = 0; i < cln->constant_expressions.size(); ++i) { - if( cln->constant_expressions[i].identifier == identifier ) { + if (cln->constant_expressions[i].identifier == identifier) { expr = cln->constant_expressions[i].expression; - bfn = true; + bfn = true; break; } } @@ -657,37 +636,36 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) { //check from constants ConstantNode *constant = alloc_node<ConstantNode>(); - constant->value = GDScriptLanguage::get_singleton()->get_global_array()[ GDScriptLanguage::get_singleton()->get_global_map()[identifier] ]; - expr=constant; + constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]]; + expr = constant; bfn = true; } } - if ( !bfn ) { + if (!bfn) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = identifier; expr = id; } - } else if (tokenizer->get_token()==GDTokenizer::TK_OP_ADD || tokenizer->get_token()==GDTokenizer::TK_OP_SUB || tokenizer->get_token()==GDTokenizer::TK_OP_NOT || tokenizer->get_token()==GDTokenizer::TK_OP_BIT_INVERT) { + } else if (tokenizer->get_token() == GDTokenizer::TK_OP_ADD || tokenizer->get_token() == GDTokenizer::TK_OP_SUB || tokenizer->get_token() == GDTokenizer::TK_OP_NOT || tokenizer->get_token() == GDTokenizer::TK_OP_BIT_INVERT) { //single prefix operators like !expr +expr -expr ++expr --expr alloc_node<OperatorNode>(); Expression e; - e.is_op=true; + e.is_op = true; - switch(tokenizer->get_token()) { - case GDTokenizer::TK_OP_ADD: e.op=OperatorNode::OP_POS; break; - case GDTokenizer::TK_OP_SUB: e.op=OperatorNode::OP_NEG; break; - case GDTokenizer::TK_OP_NOT: e.op=OperatorNode::OP_NOT; break; - case GDTokenizer::TK_OP_BIT_INVERT: e.op=OperatorNode::OP_BIT_INVERT; break; + switch (tokenizer->get_token()) { + case GDTokenizer::TK_OP_ADD: e.op = OperatorNode::OP_POS; break; + case GDTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break; + case GDTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break; + case GDTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break; default: {} } - tokenizer->advance(); - if (e.op!=OperatorNode::OP_NOT && tokenizer->get_token()==GDTokenizer::TK_OP_NOT) { + if (e.op != OperatorNode::OP_NOT && tokenizer->get_token() == GDTokenizer::TK_OP_NOT) { _set_error("Misplaced 'not'."); return NULL; } @@ -702,33 +680,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(subexpr); expr=op;*/ - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) { // array tokenizer->advance(); ArrayNode *arr = alloc_node<ArrayNode>(); - bool expecting_comma=false; + bool expecting_comma = false; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_EOF) { _set_error("Unterminated array"); return NULL; - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_CLOSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { if (!expecting_comma) { _set_error("expression or ']' expected"); return NULL; } - expecting_comma=false; + expecting_comma = false; tokenizer->advance(); //ignore newline } else { //parse expression @@ -736,16 +714,16 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ _set_error("',' or ']' expected"); return NULL; } - Node *n = _parse_expression(arr,p_static,p_allow_assign,p_parsing_constant); + Node *n = _parse_expression(arr, p_static, p_allow_assign, p_parsing_constant); if (!n) return NULL; arr->elements.push_back(n); - expecting_comma=true; + expecting_comma = true; } } - expr=arr; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_OPEN) { + expr = arr; + } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_OPEN) { // array tokenizer->advance(); @@ -760,105 +738,105 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ }; - Node *key=NULL; + Node *key = NULL; Set<Variant> keys; - DictExpect expecting=DICT_EXPECT_KEY; + DictExpect expecting = DICT_EXPECT_KEY; - while(true) { + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_EOF) { _set_error("Unterminated dictionary"); return NULL; - } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_CLOSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) { - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } tokenizer->advance(); break; - } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - expecting=DICT_EXPECT_KEY; + expecting = DICT_EXPECT_KEY; tokenizer->advance(); //ignore newline - } else if (tokenizer->get_token()==GDTokenizer::TK_COLON) { + } else if (tokenizer->get_token() == GDTokenizer::TK_COLON) { - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { _set_error("key or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_VALUE) { + if (expecting == DICT_EXPECT_VALUE) { _set_error("value expected"); return NULL; } - if (expecting==DICT_EXPECT_COMMA) { + if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return NULL; } - expecting=DICT_EXPECT_VALUE; + expecting = DICT_EXPECT_VALUE; tokenizer->advance(); //ignore newline } else { - if (expecting==DICT_EXPECT_COMMA) { + if (expecting == DICT_EXPECT_COMMA) { _set_error("',' or '}' expected"); return NULL; } - if (expecting==DICT_EXPECT_COLON) { + if (expecting == DICT_EXPECT_COLON) { _set_error("':' expected"); return NULL; } - if (expecting==DICT_EXPECT_KEY) { + if (expecting == DICT_EXPECT_KEY) { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) == GDTokenizer::TK_OP_ASSIGN) { //lua style identifier, easier to write ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = tokenizer->get_token_identifier(); key = cn; tokenizer->advance(2); - expecting=DICT_EXPECT_VALUE; + expecting = DICT_EXPECT_VALUE; } else { //python/js style more flexible - key = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant); + key = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!key) return NULL; - expecting=DICT_EXPECT_COLON; + expecting = DICT_EXPECT_COLON; } } - if (expecting==DICT_EXPECT_VALUE) { - Node *value = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant); + if (expecting == DICT_EXPECT_VALUE) { + Node *value = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant); if (!value) return NULL; - expecting=DICT_EXPECT_COMMA; + expecting = DICT_EXPECT_COMMA; if (key->type == GDParser::Node::TYPE_CONSTANT) { - Variant const& keyName = static_cast<const GDParser::ConstantNode*>(key)->value; + Variant const &keyName = static_cast<const GDParser::ConstantNode *>(key)->value; if (keys.has(keyName)) { _set_error("Duplicate key found in Dictionary literal"); @@ -868,43 +846,40 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ } DictionaryNode::Pair pair; - pair.key=key; - pair.value=value; + pair.key = key; + pair.value = value; dict->elements.push_back(pair); - key=NULL; - + key = NULL; } - } } - expr=dict; + expr = dict; - } else if (tokenizer->get_token()==GDTokenizer::TK_PERIOD && (tokenizer->get_token(1)==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) && tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && (tokenizer->get_token(1) == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) && tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) { // parent call tokenizer->advance(); //goto identifier OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_PARENT_CALL; - + op->op = OperatorNode::OP_PARENT_CALL; /*SelfNode *self = alloc_node<SelfNode>(); op->arguments.push_back(self); forbidden for now */ StringName identifier; - if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION,identifier)) { + if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier)) { //indexing stuff } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=identifier; + id->name = identifier; op->arguments.push_back(id); tokenizer->advance(1); - if (!_parse_arguments(op,op->arguments,p_static)) + if (!_parse_arguments(op, op->arguments, p_static)) return NULL; - expr=op; + expr = op; } else { @@ -912,113 +887,106 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ //print_line("found bug?"); - _set_error("Error parsing expression, misplaced: "+String(tokenizer->get_token_name(tokenizer->get_token()))); - return NULL; //nothing + _set_error("Error parsing expression, misplaced: " + String(tokenizer->get_token_name(tokenizer->get_token()))); + return NULL; //nothing } if (!expr) { ERR_EXPLAIN("GDParser bug, couldn't figure out what expression is.."); - ERR_FAIL_COND_V(!expr,NULL); + ERR_FAIL_COND_V(!expr, NULL); } - /******************/ /* Parse Indexing */ /******************/ - while (true) { //expressions can be indexed any number of times - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { //indexing using "." - if (tokenizer->get_token(1)!=GDTokenizer::TK_CURSOR && tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)!=GDTokenizer::TK_BUILT_IN_FUNC ) { + if (tokenizer->get_token(1) != GDTokenizer::TK_CURSOR && tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) != GDTokenizer::TK_BUILT_IN_FUNC) { _set_error("Expected identifier as member"); return NULL; - } else if (tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) { + } else if (tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) { //call!! - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_CALL; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_CALL; tokenizer->advance(); - IdentifierNode * id = alloc_node<IdentifierNode>(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC ) { + IdentifierNode *id = alloc_node<IdentifierNode>(); + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) { //small hack so built in funcs don't obfuscate methods - id->name=GDFunctions::get_func_name(tokenizer->get_token_built_in_func()); + id->name = GDFunctions::get_func_name(tokenizer->get_token_built_in_func()); tokenizer->advance(); } else { StringName identifier; - if (_get_completable_identifier(COMPLETION_METHOD,identifier)) { - completion_node=op; + if (_get_completable_identifier(COMPLETION_METHOD, identifier)) { + completion_node = op; //indexing stuff } - id->name=identifier; + id->name = identifier; } op->arguments.push_back(expr); // call what op->arguments.push_back(id); // call func //get arguments tokenizer->advance(1); - if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) { + if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) { _make_completable_call(0); - completion_node=op; - + completion_node = op; } - if (!_parse_arguments(op,op->arguments,p_static,true)) + if (!_parse_arguments(op, op->arguments, p_static, true)) return NULL; - expr=op; + expr = op; } else { //simple indexing! - - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INDEX_NAMED; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_INDEX_NAMED; tokenizer->advance(); - StringName identifier; - if (_get_completable_identifier(COMPLETION_INDEX,identifier)) { + if (_get_completable_identifier(COMPLETION_INDEX, identifier)) { - if (identifier==StringName()) { - identifier="@temp"; //so it parses allright + if (identifier == StringName()) { + identifier = "@temp"; //so it parses allright } - completion_node=op; + completion_node = op; //indexing stuff } - IdentifierNode * id = alloc_node<IdentifierNode>(); - id->name=identifier; + IdentifierNode *id = alloc_node<IdentifierNode>(); + id->name = identifier; op->arguments.push_back(expr); op->arguments.push_back(id); - expr=op; - - + expr = op; } - } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) { + } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) { //indexing using "[]" - OperatorNode * op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INDEX; + OperatorNode *op = alloc_node<OperatorNode>(); + op->op = OperatorNode::OP_INDEX; tokenizer->advance(1); - Node *subexpr = _parse_expression(op,p_static,p_allow_assign,p_parsing_constant); + Node *subexpr = _parse_expression(op, p_static, p_allow_assign, p_parsing_constant); if (!subexpr) { return NULL; } - if (tokenizer->get_token()!=GDTokenizer::TK_BRACKET_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_BRACKET_CLOSE) { _set_error("Expected ']'"); return NULL; } @@ -1026,7 +994,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ op->arguments.push_back(expr); op->arguments.push_back(subexpr); tokenizer->advance(1); - expr=op; + expr = op; } else break; @@ -1036,88 +1004,91 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ /* Parse Operator */ /******************/ - if (parenthesis>0) { + if (parenthesis > 0) { //remove empty space (only allowed if inside parenthesis - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } } Expression e; - e.is_op=false; - e.node=expr; + e.is_op = false; + e.node = expr; expression.push_back(e); // determine which operator is next OperatorNode::Operator op; - bool valid=true; + bool valid = true; //assign, if allowed is only alowed on the first operator -#define _VALIDATE_ASSIGN if (!p_allow_assign) { _set_error("Unexpected assign."); return NULL; } p_allow_assign=false; - switch(tokenizer->get_token()) { //see operator - - case GDTokenizer::TK_OP_IN: op=OperatorNode::OP_IN; break; - case GDTokenizer::TK_OP_EQUAL: op=OperatorNode::OP_EQUAL ; break; - case GDTokenizer::TK_OP_NOT_EQUAL: op=OperatorNode::OP_NOT_EQUAL ; break; - case GDTokenizer::TK_OP_LESS: op=OperatorNode::OP_LESS ; break; - case GDTokenizer::TK_OP_LESS_EQUAL: op=OperatorNode::OP_LESS_EQUAL ; break; - case GDTokenizer::TK_OP_GREATER: op=OperatorNode::OP_GREATER ; break; - case GDTokenizer::TK_OP_GREATER_EQUAL: op=OperatorNode::OP_GREATER_EQUAL ; break; - case GDTokenizer::TK_OP_AND: op=OperatorNode::OP_AND ; break; - case GDTokenizer::TK_OP_OR: op=OperatorNode::OP_OR ; break; - case GDTokenizer::TK_OP_ADD: op=OperatorNode::OP_ADD ; break; - case GDTokenizer::TK_OP_SUB: op=OperatorNode::OP_SUB ; break; - case GDTokenizer::TK_OP_MUL: op=OperatorNode::OP_MUL ; break; - case GDTokenizer::TK_OP_DIV: op=OperatorNode::OP_DIV ; break; - case GDTokenizer::TK_OP_MOD: op=OperatorNode::OP_MOD ; break; +#define _VALIDATE_ASSIGN \ + if (!p_allow_assign) { \ + _set_error("Unexpected assign."); \ + return NULL; \ + } \ + p_allow_assign = false; + switch (tokenizer->get_token()) { //see operator + + case GDTokenizer::TK_OP_IN: op = OperatorNode::OP_IN; break; + case GDTokenizer::TK_OP_EQUAL: op = OperatorNode::OP_EQUAL; break; + case GDTokenizer::TK_OP_NOT_EQUAL: op = OperatorNode::OP_NOT_EQUAL; break; + case GDTokenizer::TK_OP_LESS: op = OperatorNode::OP_LESS; break; + case GDTokenizer::TK_OP_LESS_EQUAL: op = OperatorNode::OP_LESS_EQUAL; break; + case GDTokenizer::TK_OP_GREATER: op = OperatorNode::OP_GREATER; break; + case GDTokenizer::TK_OP_GREATER_EQUAL: op = OperatorNode::OP_GREATER_EQUAL; break; + case GDTokenizer::TK_OP_AND: op = OperatorNode::OP_AND; break; + case GDTokenizer::TK_OP_OR: op = OperatorNode::OP_OR; break; + case GDTokenizer::TK_OP_ADD: op = OperatorNode::OP_ADD; break; + case GDTokenizer::TK_OP_SUB: op = OperatorNode::OP_SUB; break; + case GDTokenizer::TK_OP_MUL: op = OperatorNode::OP_MUL; break; + case GDTokenizer::TK_OP_DIV: op = OperatorNode::OP_DIV; break; + case GDTokenizer::TK_OP_MOD: + op = OperatorNode::OP_MOD; + break; //case GDTokenizer::TK_OP_NEG: op=OperatorNode::OP_NEG ; break; - case GDTokenizer::TK_OP_SHIFT_LEFT: op=OperatorNode::OP_SHIFT_LEFT ; break; - case GDTokenizer::TK_OP_SHIFT_RIGHT: op=OperatorNode::OP_SHIFT_RIGHT ; break; - case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN ; break; - case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_ADD ; break; - case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SUB ; break; - case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MUL ; break; - case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_DIV ; break; - case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MOD ; break; - case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_LEFT; break; - case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_AND ; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_OR ; break; - case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_XOR ; break; - case GDTokenizer::TK_OP_BIT_AND: op=OperatorNode::OP_BIT_AND ; break; - case GDTokenizer::TK_OP_BIT_OR: op=OperatorNode::OP_BIT_OR ; break; - case GDTokenizer::TK_OP_BIT_XOR: op=OperatorNode::OP_BIT_XOR ; break; - case GDTokenizer::TK_PR_EXTENDS: op=OperatorNode::OP_EXTENDS; break; - case GDTokenizer::TK_CF_IF: op=OperatorNode::OP_TERNARY_IF; break; - case GDTokenizer::TK_CF_ELSE: op=OperatorNode::OP_TERNARY_ELSE; break; - default: valid=false; break; + case GDTokenizer::TK_OP_SHIFT_LEFT: op = OperatorNode::OP_SHIFT_LEFT; break; + case GDTokenizer::TK_OP_SHIFT_RIGHT: op = OperatorNode::OP_SHIFT_RIGHT; break; + case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN; break; + case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_ADD; break; + case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SUB; break; + case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MUL; break; + case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_DIV; break; + case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MOD; break; + case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_LEFT; break; + case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break; + case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_AND; break; + case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_OR; break; + case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_XOR; break; + case GDTokenizer::TK_OP_BIT_AND: op = OperatorNode::OP_BIT_AND; break; + case GDTokenizer::TK_OP_BIT_OR: op = OperatorNode::OP_BIT_OR; break; + case GDTokenizer::TK_OP_BIT_XOR: op = OperatorNode::OP_BIT_XOR; break; + case GDTokenizer::TK_PR_EXTENDS: op = OperatorNode::OP_EXTENDS; break; + case GDTokenizer::TK_CF_IF: op = OperatorNode::OP_TERNARY_IF; break; + case GDTokenizer::TK_CF_ELSE: op = OperatorNode::OP_TERNARY_ELSE; break; + default: valid = false; break; } if (valid) { - e.is_op=true; - e.op=op; + e.is_op = true; + e.op = op; expression.push_back(e); tokenizer->advance(); } else { break; } - } /* Reduce the set set of expressions and place them in an operator tree, respecting precedence */ + while (expression.size() > 1) { - while(expression.size()>1) { - - int next_op=-1; - int min_priority=0xFFFFF; - bool is_unary=false; - bool is_ternary=false; - - for(int i=0;i<expression.size();i++) { - + int next_op = -1; + int min_priority = 0xFFFFF; + bool is_unary = false; + bool is_ternary = false; + for (int i = 0; i < expression.size(); i++) { if (!expression[i].is_op) { @@ -1126,102 +1097,115 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ int priority; - bool unary=false; - bool ternary=false; - bool error=false; + bool unary = false; + bool ternary = false; + bool error = false; - switch(expression[i].op) { + switch (expression[i].op) { - case OperatorNode::OP_EXTENDS: priority=-1; break; //before anything + case OperatorNode::OP_EXTENDS: + priority = -1; + break; //before anything - case OperatorNode::OP_BIT_INVERT: priority=0; unary=true; break; - case OperatorNode::OP_NEG: priority=1; unary=true; break; - case OperatorNode::OP_POS: priority=1; unary=true; break; + case OperatorNode::OP_BIT_INVERT: + priority = 0; + unary = true; + break; + case OperatorNode::OP_NEG: + priority = 1; + unary = true; + break; + case OperatorNode::OP_POS: + priority = 1; + unary = true; + break; - case OperatorNode::OP_MUL: priority=2; break; - case OperatorNode::OP_DIV: priority=2; break; - case OperatorNode::OP_MOD: priority=2; break; + case OperatorNode::OP_MUL: priority = 2; break; + case OperatorNode::OP_DIV: priority = 2; break; + case OperatorNode::OP_MOD: priority = 2; break; - case OperatorNode::OP_ADD: priority=3; break; - case OperatorNode::OP_SUB: priority=3; break; + case OperatorNode::OP_ADD: priority = 3; break; + case OperatorNode::OP_SUB: priority = 3; break; - case OperatorNode::OP_SHIFT_LEFT: priority=4; break; - case OperatorNode::OP_SHIFT_RIGHT: priority=4; break; + case OperatorNode::OP_SHIFT_LEFT: priority = 4; break; + case OperatorNode::OP_SHIFT_RIGHT: priority = 4; break; - case OperatorNode::OP_BIT_AND: priority=5; break; - case OperatorNode::OP_BIT_XOR: priority=6; break; - case OperatorNode::OP_BIT_OR: priority=7; break; + case OperatorNode::OP_BIT_AND: priority = 5; break; + case OperatorNode::OP_BIT_XOR: priority = 6; break; + case OperatorNode::OP_BIT_OR: priority = 7; break; - case OperatorNode::OP_LESS: priority=8; break; - case OperatorNode::OP_LESS_EQUAL: priority=8; break; - case OperatorNode::OP_GREATER: priority=8; break; - case OperatorNode::OP_GREATER_EQUAL: priority=8; break; + case OperatorNode::OP_LESS: priority = 8; break; + case OperatorNode::OP_LESS_EQUAL: priority = 8; break; + case OperatorNode::OP_GREATER: priority = 8; break; + case OperatorNode::OP_GREATER_EQUAL: priority = 8; break; - case OperatorNode::OP_EQUAL: priority=8; break; - case OperatorNode::OP_NOT_EQUAL: priority=8; break; + case OperatorNode::OP_EQUAL: priority = 8; break; + case OperatorNode::OP_NOT_EQUAL: priority = 8; break; - - case OperatorNode::OP_IN: priority=10; break; - - case OperatorNode::OP_NOT: priority=11; unary=true; break; - case OperatorNode::OP_AND: priority=12; break; - case OperatorNode::OP_OR: priority=13; break; - - case OperatorNode::OP_TERNARY_IF: priority=14; ternary=true; break; - case OperatorNode::OP_TERNARY_ELSE: priority=14; error=true; break; // Errors out when found without IF (since IF would consume it) + case OperatorNode::OP_IN: priority = 10; break; - case OperatorNode::OP_ASSIGN: priority=15; break; - case OperatorNode::OP_ASSIGN_ADD: priority=15; break; - case OperatorNode::OP_ASSIGN_SUB: priority=15; break; - case OperatorNode::OP_ASSIGN_MUL: priority=15; break; - case OperatorNode::OP_ASSIGN_DIV: priority=15; break; - case OperatorNode::OP_ASSIGN_MOD: priority=15; break; - case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority=15; break; - case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_AND: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_OR: priority=15; break; - case OperatorNode::OP_ASSIGN_BIT_XOR: priority=15; break; + case OperatorNode::OP_NOT: + priority = 11; + unary = true; + break; + case OperatorNode::OP_AND: priority = 12; break; + case OperatorNode::OP_OR: priority = 13; break; + case OperatorNode::OP_TERNARY_IF: + priority = 14; + ternary = true; + break; + case OperatorNode::OP_TERNARY_ELSE: + priority = 14; + error = true; + break; // Errors out when found without IF (since IF would consume it) + + case OperatorNode::OP_ASSIGN: priority = 15; break; + case OperatorNode::OP_ASSIGN_ADD: priority = 15; break; + case OperatorNode::OP_ASSIGN_SUB: priority = 15; break; + case OperatorNode::OP_ASSIGN_MUL: priority = 15; break; + case OperatorNode::OP_ASSIGN_DIV: priority = 15; break; + case OperatorNode::OP_ASSIGN_MOD: priority = 15; break; + case OperatorNode::OP_ASSIGN_SHIFT_LEFT: priority = 15; break; + case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_AND: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_OR: priority = 15; break; + case OperatorNode::OP_ASSIGN_BIT_XOR: priority = 15; break; default: { - _set_error("GDParser bug, invalid operator in expression: "+itos(expression[i].op)); + _set_error("GDParser bug, invalid operator in expression: " + itos(expression[i].op)); return NULL; } - } - if (priority<min_priority) { - if(error) { + if (priority < min_priority) { + if (error) { _set_error("Unexpected operator"); return NULL; } // < is used for left to right (default) // <= is used for right to left - next_op=i; - min_priority=priority; - is_unary=unary; - is_ternary=ternary; + next_op = i; + min_priority = priority; + is_unary = unary; + is_ternary = ternary; } - } - - if (next_op==-1) { - + if (next_op == -1) { _set_error("Yet another parser bug...."); - ERR_FAIL_COND_V(next_op==-1,NULL); + ERR_FAIL_COND_V(next_op == -1, NULL); } - // OK! create operator.. if (is_unary) { - int expr_pos=next_op; - while(expression[expr_pos].is_op) { + int expr_pos = next_op; + while (expression[expr_pos].is_op) { expr_pos++; - if (expr_pos==expression.size()) { + if (expr_pos == expression.size()) { //can happen.. _set_error("Unexpected end of expression.."); return NULL; @@ -1229,44 +1213,43 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ } //consecutively do unary opeators - for(int i=expr_pos-1;i>=next_op;i--) { + for (int i = expr_pos - 1; i >= next_op; i--) { OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[i].op; - op->arguments.push_back(expression[i+1].node); - op->line=op_line; //line might have been changed from a \n - expression[i].is_op=false; - expression[i].node=op; - expression.remove(i+1); + op->op = expression[i].op; + op->arguments.push_back(expression[i + 1].node); + op->line = op_line; //line might have been changed from a \n + expression[i].is_op = false; + expression[i].node = op; + expression.remove(i + 1); } - - } else if(is_ternary) { - if (next_op <1 || next_op>=(expression.size()-1)) { + } else if (is_ternary) { + if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - - if(next_op>=(expression.size()-2) || expression[next_op+2].op != OperatorNode::OP_TERNARY_ELSE) { + + if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) { _set_error("Expected else after ternary if."); ERR_FAIL_V(NULL); } - if(next_op>=(expression.size()-3)) { + if (next_op >= (expression.size() - 3)) { _set_error("Expected value after ternary else."); ERR_FAIL_V(NULL); } OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[next_op].op; - op->line=op_line; //line might have been changed from a \n + op->op = expression[next_op].op; + op->line = op_line; //line might have been changed from a \n - if (expression[next_op-1].is_op) { + if (expression[next_op - 1].is_op) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - if (expression[next_op+1].is_op) { + if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1276,7 +1259,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - if (expression[next_op+3].is_op) { + if (expression[next_op + 3].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1286,35 +1269,34 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - - op->arguments.push_back(expression[next_op+1].node); //next expression goes as first - op->arguments.push_back(expression[next_op-1].node); //left expression goes as when-true - op->arguments.push_back(expression[next_op+3].node); //expression after next goes as when-false + op->arguments.push_back(expression[next_op + 1].node); //next expression goes as first + op->arguments.push_back(expression[next_op - 1].node); //left expression goes as when-true + op->arguments.push_back(expression[next_op + 3].node); //expression after next goes as when-false //replace all 3 nodes by this operator and make it an expression - expression[next_op-1].node=op; + expression[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); expression.remove(next_op); } else { - if (next_op <1 || next_op>=(expression.size()-1)) { + if (next_op < 1 || next_op >= (expression.size() - 1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } OperatorNode *op = alloc_node<OperatorNode>(); - op->op=expression[next_op].op; - op->line=op_line; //line might have been changed from a \n + op->op = expression[next_op].op; + op->line = op_line; //line might have been changed from a \n - if (expression[next_op-1].is_op) { + if (expression[next_op - 1].is_op) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } - if (expression[next_op+1].is_op) { + if (expression[next_op + 1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, @@ -1324,26 +1306,22 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_ return NULL; } - - op->arguments.push_back(expression[next_op-1].node); //expression goes as left - op->arguments.push_back(expression[next_op+1].node); //next expression goes as right + op->arguments.push_back(expression[next_op - 1].node); //expression goes as left + op->arguments.push_back(expression[next_op + 1].node); //next expression goes as right //replace all 3 nodes by this operator and make it an expression - expression[next_op-1].node=op; + expression[next_op - 1].node = op; expression.remove(next_op); expression.remove(next_op); } - } return expression[0].node; - } +GDParser::Node *GDParser::_reduce_expression(Node *p_node, bool p_to_const) { -GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { - - switch(p_node->type) { + switch (p_node->type) { case Node::TYPE_BUILT_IN_FUNCTION: { //many may probably be optimizable @@ -1351,14 +1329,14 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { } break; case Node::TYPE_ARRAY: { - ArrayNode *an = static_cast<ArrayNode*>(p_node); - bool all_constants=true; + ArrayNode *an = static_cast<ArrayNode *>(p_node); + bool all_constants = true; - for(int i=0;i<an->elements.size();i++) { + for (int i = 0; i < an->elements.size(); i++) { - an->elements[i]=_reduce_expression(an->elements[i],p_to_const); - if (an->elements[i]->type!=Node::TYPE_CONSTANT) - all_constants=false; + an->elements[i] = _reduce_expression(an->elements[i], p_to_const); + if (an->elements[i]->type != Node::TYPE_CONSTANT) + all_constants = false; } if (all_constants && p_to_const) { @@ -1368,12 +1346,11 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { Array arr; //print_line("mk array "+itos(!p_to_const)); arr.resize(an->elements.size()); - for(int i=0;i<an->elements.size();i++) { - ConstantNode *acn = static_cast<ConstantNode*>(an->elements[i]); - arr[i]=acn->value; - + for (int i = 0; i < an->elements.size(); i++) { + ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]); + arr[i] = acn->value; } - cn->value=arr; + cn->value = arr; return cn; } @@ -1382,18 +1359,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { } break; case Node::TYPE_DICTIONARY: { - DictionaryNode *dn = static_cast<DictionaryNode*>(p_node); - bool all_constants=true; - - for(int i=0;i<dn->elements.size();i++) { + DictionaryNode *dn = static_cast<DictionaryNode *>(p_node); + bool all_constants = true; - dn->elements[i].key=_reduce_expression(dn->elements[i].key,p_to_const); - if (dn->elements[i].key->type!=Node::TYPE_CONSTANT) - all_constants=false; - dn->elements[i].value=_reduce_expression(dn->elements[i].value,p_to_const); - if (dn->elements[i].value->type!=Node::TYPE_CONSTANT) - all_constants=false; + for (int i = 0; i < dn->elements.size(); i++) { + dn->elements[i].key = _reduce_expression(dn->elements[i].key, p_to_const); + if (dn->elements[i].key->type != Node::TYPE_CONSTANT) + all_constants = false; + dn->elements[i].value = _reduce_expression(dn->elements[i].value, p_to_const); + if (dn->elements[i].value->type != Node::TYPE_CONSTANT) + all_constants = false; } if (all_constants && p_to_const) { @@ -1401,157 +1377,143 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { ConstantNode *cn = alloc_node<ConstantNode>(); Dictionary dict; - for(int i=0;i<dn->elements.size();i++) { - ConstantNode *key_c = static_cast<ConstantNode*>(dn->elements[i].key); - ConstantNode *value_c = static_cast<ConstantNode*>(dn->elements[i].value); - - dict[key_c->value]=value_c->value; + for (int i = 0; i < dn->elements.size(); i++) { + ConstantNode *key_c = static_cast<ConstantNode *>(dn->elements[i].key); + ConstantNode *value_c = static_cast<ConstantNode *>(dn->elements[i].value); + dict[key_c->value] = value_c->value; } - cn->value=dict; + cn->value = dict; return cn; } return dn; - } break; case Node::TYPE_OPERATOR: { - OperatorNode *op=static_cast<OperatorNode*>(p_node); + OperatorNode *op = static_cast<OperatorNode *>(p_node); - bool all_constants=true; - int last_not_constant=-1; + bool all_constants = true; + int last_not_constant = -1; - for(int i=0;i<op->arguments.size();i++) { + for (int i = 0; i < op->arguments.size(); i++) { - op->arguments[i]=_reduce_expression(op->arguments[i],p_to_const); - if (op->arguments[i]->type!=Node::TYPE_CONSTANT) { - all_constants=false; - last_not_constant=i; + op->arguments[i] = _reduce_expression(op->arguments[i], p_to_const); + if (op->arguments[i]->type != Node::TYPE_CONSTANT) { + all_constants = false; + last_not_constant = i; } } - if (op->op==OperatorNode::OP_EXTENDS) { + if (op->op == OperatorNode::OP_EXTENDS) { //nothing much return op; - - } if (op->op==OperatorNode::OP_PARENT_CALL) { + } + if (op->op == OperatorNode::OP_PARENT_CALL) { //nothing much return op; - } else if (op->op==OperatorNode::OP_CALL) { + } else if (op->op == OperatorNode::OP_CALL) { //can reduce base type constructors - if ((op->arguments[0]->type==Node::TYPE_TYPE || (op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && GDFunctions::is_deterministic( static_cast<BuiltInFunctionNode*>(op->arguments[0])->function))) && last_not_constant==0) { + if ((op->arguments[0]->type == Node::TYPE_TYPE || (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && GDFunctions::is_deterministic(static_cast<BuiltInFunctionNode *>(op->arguments[0])->function))) && last_not_constant == 0) { //native type constructor or intrinsic function - const Variant **vptr=NULL; - Vector<Variant*> ptrs; - if (op->arguments.size()>1) { - - ptrs.resize(op->arguments.size()-1); - for(int i=0;i<ptrs.size();i++) { + const Variant **vptr = NULL; + Vector<Variant *> ptrs; + if (op->arguments.size() > 1) { + ptrs.resize(op->arguments.size() - 1); + for (int i = 0; i < ptrs.size(); i++) { - ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[i+1]); - ptrs[i]=&cn->value; + ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i + 1]); + ptrs[i] = &cn->value; } - vptr=(const Variant**)&ptrs[0]; - - + vptr = (const Variant **)&ptrs[0]; } Variant::CallError ce; Variant v; - if (op->arguments[0]->type==Node::TYPE_TYPE) { - TypeNode *tn = static_cast<TypeNode*>(op->arguments[0]); - v = Variant::construct(tn->vtype,vptr,ptrs.size(),ce); + if (op->arguments[0]->type == Node::TYPE_TYPE) { + TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); + v = Variant::construct(tn->vtype, vptr, ptrs.size(), ce); } else { - GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function; - GDFunctions::call(func,vptr,ptrs.size(),v,ce); + GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; + GDFunctions::call(func, vptr, ptrs.size(), v, ce); } - - if (ce.error!=Variant::CallError::CALL_OK) { + if (ce.error != Variant::CallError::CALL_OK) { String errwhere; - if (op->arguments[0]->type==Node::TYPE_TYPE) { - TypeNode *tn = static_cast<TypeNode*>(op->arguments[0]); - errwhere="'"+Variant::get_type_name(tn->vtype)+"'' constructor"; + if (op->arguments[0]->type == Node::TYPE_TYPE) { + TypeNode *tn = static_cast<TypeNode *>(op->arguments[0]); + errwhere = "'" + Variant::get_type_name(tn->vtype) + "'' constructor"; } else { - GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function; - errwhere=String("'")+GDFunctions::get_func_name(func)+"'' intrinsic function"; - + GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function; + errwhere = String("'") + GDFunctions::get_func_name(func) + "'' intrinsic function"; } - switch(ce.error) { + switch (ce.error) { case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: { - _set_error("Invalid argument (#"+itos(ce.argument+1)+") for "+errwhere+"."); + _set_error("Invalid argument (#" + itos(ce.argument + 1) + ") for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { - _set_error("Too many arguments for "+errwhere+"."); + _set_error("Too many arguments for " + errwhere + "."); } break; case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: { - _set_error("Too few arguments for "+errwhere+"."); + _set_error("Too few arguments for " + errwhere + "."); } break; default: { - _set_error("Invalid arguments for "+errwhere+"."); + _set_error("Invalid arguments for " + errwhere + "."); } break; } - error_line=op->line; + error_line = op->line; return p_node; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; - } else if (op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && last_not_constant==0) { - - - - - + } else if (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && last_not_constant == 0) { } return op; //don't reduce yet - } else if (op->op==OperatorNode::OP_YIELD) { + } else if (op->op == OperatorNode::OP_YIELD) { return op; - } else if (op->op==OperatorNode::OP_INDEX) { + } else if (op->op == OperatorNode::OP_INDEX) { //can reduce indices into constant arrays or dictionaries if (all_constants) { - ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]); - ConstantNode *cb = static_cast<ConstantNode*>(op->arguments[1]); - - + ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); + ConstantNode *cb = static_cast<ConstantNode *>(op->arguments[1]); bool valid; - Variant v = ca->value.get(cb->value,&valid); + Variant v = ca->value.get(cb->value, &valid); if (!valid) { _set_error("invalid index in constant expression"); - error_line=op->line; + error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; } /*else if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { @@ -1573,32 +1535,31 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { return op; - } else if (op->op==OperatorNode::OP_INDEX_NAMED) { + } else if (op->op == OperatorNode::OP_INDEX_NAMED) { - if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { + if (op->arguments[0]->type == Node::TYPE_CONSTANT && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { - ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]); - IdentifierNode *ib = static_cast<IdentifierNode*>(op->arguments[1]); + ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]); + IdentifierNode *ib = static_cast<IdentifierNode *>(op->arguments[1]); bool valid; - Variant v = ca->value.get_named(ib->name,&valid); + Variant v = ca->value.get_named(ib->name, &valid); if (!valid) { - _set_error("invalid index '"+String(ib->name)+"' in constant expression"); - error_line=op->line; + _set_error("invalid index '" + String(ib->name) + "' in constant expression"); + error_line = op->line; return op; } ConstantNode *cn = alloc_node<ConstantNode>(); - cn->value=v; + cn->value = v; return cn; } return op; - } //validate assignment (don't assign to cosntant expression - switch(op->op) { + switch (op->op) { case OperatorNode::OP_ASSIGN: case OperatorNode::OP_ASSIGN_ADD: @@ -1612,17 +1573,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { case OperatorNode::OP_ASSIGN_BIT_OR: case OperatorNode::OP_ASSIGN_BIT_XOR: { - if (op->arguments[0]->type==Node::TYPE_CONSTANT) { - _set_error("Can't assign to constant",tokenizer->get_token_line()-1); - error_line=op->line; + if (op->arguments[0]->type == Node::TYPE_CONSTANT) { + _set_error("Can't assign to constant", tokenizer->get_token_line() - 1); + error_line = op->line; return op; } - if (op->arguments[0]->type==Node::TYPE_OPERATOR) { - OperatorNode *on = static_cast<OperatorNode*>(op->arguments[0]); + if (op->arguments[0]->type == Node::TYPE_OPERATOR) { + OperatorNode *on = static_cast<OperatorNode *>(op->arguments[0]); if (on->op != OperatorNode::OP_INDEX && on->op != OperatorNode::OP_INDEX_NAMED) { - _set_error("Can't assign to an expression",tokenizer->get_token_line()-1); - error_line=op->line; + _set_error("Can't assign to an expression", tokenizer->get_token_line() - 1); + error_line = op->line; return op; } } @@ -1633,59 +1594,105 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { //now se if all are constants if (!all_constants) return op; //nothing to reduce from here on -#define _REDUCE_UNARY(m_vop)\ - bool valid=false;\ - Variant res;\ - Variant::evaluate(m_vop,static_cast<ConstantNode*>(op->arguments[0])->value,Variant(),res,valid);\ - if (!valid) {\ - _set_error("Invalid operand for unary operator");\ - error_line=op->line;\ - return p_node;\ - }\ - ConstantNode *cn = alloc_node<ConstantNode>();\ - cn->value=res;\ +#define _REDUCE_UNARY(m_vop) \ + bool valid = false; \ + Variant res; \ + Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, Variant(), res, valid); \ + if (!valid) { \ + _set_error("Invalid operand for unary operator"); \ + error_line = op->line; \ + return p_node; \ + } \ + ConstantNode *cn = alloc_node<ConstantNode>(); \ + cn->value = res; \ return cn; -#define _REDUCE_BINARY(m_vop)\ - bool valid=false;\ - Variant res;\ - Variant::evaluate(m_vop,static_cast<ConstantNode*>(op->arguments[0])->value,static_cast<ConstantNode*>(op->arguments[1])->value,res,valid);\ - if (!valid) {\ - _set_error("Invalid operands for operator");\ - error_line=op->line;\ - return p_node;\ - }\ - ConstantNode *cn = alloc_node<ConstantNode>();\ - cn->value=res;\ +#define _REDUCE_BINARY(m_vop) \ + bool valid = false; \ + Variant res; \ + Variant::evaluate(m_vop, static_cast<ConstantNode *>(op->arguments[0])->value, static_cast<ConstantNode *>(op->arguments[1])->value, res, valid); \ + if (!valid) { \ + _set_error("Invalid operands for operator"); \ + error_line = op->line; \ + return p_node; \ + } \ + ConstantNode *cn = alloc_node<ConstantNode>(); \ + cn->value = res; \ return cn; - switch(op->op) { + switch (op->op) { //unary operators - case OperatorNode::OP_NEG: { _REDUCE_UNARY(Variant::OP_NEGATE); } break; - case OperatorNode::OP_POS: { _REDUCE_UNARY(Variant::OP_POSITIVE); } break; - case OperatorNode::OP_NOT: { _REDUCE_UNARY(Variant::OP_NOT); } break; - case OperatorNode::OP_BIT_INVERT: { _REDUCE_UNARY(Variant::OP_BIT_NEGATE); } break; + case OperatorNode::OP_NEG: { + _REDUCE_UNARY(Variant::OP_NEGATE); + } break; + case OperatorNode::OP_POS: { + _REDUCE_UNARY(Variant::OP_POSITIVE); + } break; + case OperatorNode::OP_NOT: { + _REDUCE_UNARY(Variant::OP_NOT); + } break; + case OperatorNode::OP_BIT_INVERT: { + _REDUCE_UNARY(Variant::OP_BIT_NEGATE); + } break; //binary operators (in precedence order) - case OperatorNode::OP_IN: { _REDUCE_BINARY(Variant::OP_IN); } break; - case OperatorNode::OP_EQUAL: { _REDUCE_BINARY(Variant::OP_EQUAL); } break; - case OperatorNode::OP_NOT_EQUAL: { _REDUCE_BINARY(Variant::OP_NOT_EQUAL); } break; - case OperatorNode::OP_LESS: { _REDUCE_BINARY(Variant::OP_LESS); } break; - case OperatorNode::OP_LESS_EQUAL: { _REDUCE_BINARY(Variant::OP_LESS_EQUAL); } break; - case OperatorNode::OP_GREATER: { _REDUCE_BINARY(Variant::OP_GREATER); } break; - case OperatorNode::OP_GREATER_EQUAL: { _REDUCE_BINARY(Variant::OP_GREATER_EQUAL); } break; - case OperatorNode::OP_AND: { _REDUCE_BINARY(Variant::OP_AND); } break; - case OperatorNode::OP_OR: { _REDUCE_BINARY(Variant::OP_OR); } break; - case OperatorNode::OP_ADD: { _REDUCE_BINARY(Variant::OP_ADD); } break; - case OperatorNode::OP_SUB: { _REDUCE_BINARY(Variant::OP_SUBSTRACT); } break; - case OperatorNode::OP_MUL: { _REDUCE_BINARY(Variant::OP_MULTIPLY); } break; - case OperatorNode::OP_DIV: { _REDUCE_BINARY(Variant::OP_DIVIDE); } break; - case OperatorNode::OP_MOD: { _REDUCE_BINARY(Variant::OP_MODULE); } break; - case OperatorNode::OP_SHIFT_LEFT: { _REDUCE_BINARY(Variant::OP_SHIFT_LEFT); } break; - case OperatorNode::OP_SHIFT_RIGHT: { _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT); } break; - case OperatorNode::OP_BIT_AND: { _REDUCE_BINARY(Variant::OP_BIT_AND); } break; - case OperatorNode::OP_BIT_OR: { _REDUCE_BINARY(Variant::OP_BIT_OR); } break; - case OperatorNode::OP_BIT_XOR: { _REDUCE_BINARY(Variant::OP_BIT_XOR); } break; + case OperatorNode::OP_IN: { + _REDUCE_BINARY(Variant::OP_IN); + } break; + case OperatorNode::OP_EQUAL: { + _REDUCE_BINARY(Variant::OP_EQUAL); + } break; + case OperatorNode::OP_NOT_EQUAL: { + _REDUCE_BINARY(Variant::OP_NOT_EQUAL); + } break; + case OperatorNode::OP_LESS: { + _REDUCE_BINARY(Variant::OP_LESS); + } break; + case OperatorNode::OP_LESS_EQUAL: { + _REDUCE_BINARY(Variant::OP_LESS_EQUAL); + } break; + case OperatorNode::OP_GREATER: { + _REDUCE_BINARY(Variant::OP_GREATER); + } break; + case OperatorNode::OP_GREATER_EQUAL: { + _REDUCE_BINARY(Variant::OP_GREATER_EQUAL); + } break; + case OperatorNode::OP_AND: { + _REDUCE_BINARY(Variant::OP_AND); + } break; + case OperatorNode::OP_OR: { + _REDUCE_BINARY(Variant::OP_OR); + } break; + case OperatorNode::OP_ADD: { + _REDUCE_BINARY(Variant::OP_ADD); + } break; + case OperatorNode::OP_SUB: { + _REDUCE_BINARY(Variant::OP_SUBSTRACT); + } break; + case OperatorNode::OP_MUL: { + _REDUCE_BINARY(Variant::OP_MULTIPLY); + } break; + case OperatorNode::OP_DIV: { + _REDUCE_BINARY(Variant::OP_DIVIDE); + } break; + case OperatorNode::OP_MOD: { + _REDUCE_BINARY(Variant::OP_MODULE); + } break; + case OperatorNode::OP_SHIFT_LEFT: { + _REDUCE_BINARY(Variant::OP_SHIFT_LEFT); + } break; + case OperatorNode::OP_SHIFT_RIGHT: { + _REDUCE_BINARY(Variant::OP_SHIFT_RIGHT); + } break; + case OperatorNode::OP_BIT_AND: { + _REDUCE_BINARY(Variant::OP_BIT_AND); + } break; + case OperatorNode::OP_BIT_OR: { + _REDUCE_BINARY(Variant::OP_BIT_OR); + } break; + case OperatorNode::OP_BIT_XOR: { + _REDUCE_BINARY(Variant::OP_BIT_XOR); + } break; default: { ERR_FAIL_V(op); } } @@ -1694,16 +1701,15 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) { default: { return p_node; } break; - } } -GDParser::Node* GDParser::_parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const,bool p_allow_assign) { +GDParser::Node *GDParser::_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const, bool p_allow_assign) { - Node* expr=_parse_expression(p_parent,p_static,p_allow_assign,p_reduce_const); + Node *expr = _parse_expression(p_parent, p_static, p_allow_assign, p_reduce_const); if (!expr || error_set) return NULL; - expr = _reduce_expression(expr,p_reduce_const); + expr = _reduce_expression(expr, p_reduce_const); if (!expr || error_set) return NULL; return expr; @@ -1715,43 +1721,42 @@ bool GDParser::_recover_from_completion() { return false; //can't recover if no completion } //skip stuff until newline - while(tokenizer->get_token()!=GDTokenizer::TK_NEWLINE && tokenizer->get_token()!=GDTokenizer::TK_EOF && tokenizer->get_token()!=GDTokenizer::TK_ERROR) { + while (tokenizer->get_token() != GDTokenizer::TK_NEWLINE && tokenizer->get_token() != GDTokenizer::TK_EOF && tokenizer->get_token() != GDTokenizer::TK_ERROR) { tokenizer->advance(); } - completion_found=false; - error_set=false; - if(tokenizer->get_token() == GDTokenizer::TK_ERROR){ + completion_found = false; + error_set = false; + if (tokenizer->get_token() == GDTokenizer::TK_ERROR) { error_set = true; } return true; } -GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) -{ - +GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) { + PatternNode *pattern = alloc_node<PatternNode>(); - + GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return NULL; - + if (token == GDTokenizer::TK_EOF) { return NULL; } - + switch (token) { // array case GDTokenizer::TK_BRACKET_OPEN: { tokenizer->advance(); pattern->pt_type = GDParser::PatternNode::PT_ARRAY; while (true) { - + if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_CLOSE) { tokenizer->advance(); break; } - + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) { // match everything tokenizer->advance(2); @@ -1769,14 +1774,14 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) return NULL; } } - + PatternNode *sub_pattern = _parse_pattern(p_static); if (!sub_pattern) { return NULL; } - + pattern->array.push_back(sub_pattern); - + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; @@ -1801,12 +1806,12 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) tokenizer->advance(); pattern->pt_type = GDParser::PatternNode::PT_DICTIONARY; while (true) { - + if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) { tokenizer->advance(); break; } - + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) { // match everything tokenizer->advance(2); @@ -1824,33 +1829,32 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) return NULL; } } - + Node *key = _parse_and_reduce_expression(pattern, p_static); if (!key) { _set_error("Not a valid key in pattern"); return NULL; } - + if (key->type != GDParser::Node::TYPE_CONSTANT) { _set_error("Not a constant expression as key"); return NULL; } - + if (tokenizer->get_token() == GDTokenizer::TK_COLON) { tokenizer->advance(); - + PatternNode *value = _parse_pattern(p_static); if (!value) { _set_error("Expected pattern in dictionary value"); return NULL; } - - pattern->dictionary.insert(static_cast<ConstantNode*>(key), value); + + pattern->dictionary.insert(static_cast<ConstantNode *>(key), value); } else { - pattern->dictionary.insert(static_cast<ConstantNode*>(key), NULL); + pattern->dictionary.insert(static_cast<ConstantNode *>(key), NULL); } - - + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; @@ -1873,47 +1877,47 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) if (error_set) { return NULL; } - + if (value->type != Node::TYPE_IDENTIFIER && value->type != Node::TYPE_CONSTANT) { _set_error("Only constant expressions or variables allowed in a pattern"); return NULL; } - + pattern->pt_type = PatternNode::PT_CONSTANT; pattern->constant = value; } break; } - + return pattern; } -void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode*> &p_branches, bool p_static) -{ +void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static) { int indent_level = tab_level.back()->get(); - + while (true) { - - while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE && _parse_newline()); - + + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE && _parse_newline()) + ; + // GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return; - + if (indent_level > tab_level.back()->get()) { return; // go back a level } - - if (pending_newline!=-1) { - pending_newline=-1; + + if (pending_newline != -1) { + pending_newline = -1; } - + PatternBranchNode *branch = alloc_node<PatternBranchNode>(); - + branch->patterns.push_back(_parse_pattern(p_static)); if (!branch->patterns[0]) { return; } - + while (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); branch->patterns.push_back(_parse_pattern(p_static)); @@ -1921,263 +1925,249 @@ void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode return; } } - - if(!_enter_indent_block()) { + + if (!_enter_indent_block()) { _set_error("Expected block in pattern branch"); return; } - + branch->body = alloc_node<BlockNode>(); branch->body->parent_block = p_block; p_block->sub_blocks.push_back(branch->body); current_block = branch->body; - + _parse_block(branch->body, p_static); - + current_block = p_block; - + p_branches.push_back(branch); } } - -void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node*> &p_bindings) -{ +void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) { switch (p_pattern->pt_type) { case PatternNode::PT_CONSTANT: { - + // typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDFunctions::TYPE_OF; - + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); - + OperatorNode *typeof_pattern_value = alloc_node<OperatorNode>(); typeof_pattern_value->op = OperatorNode::OP_CALL; typeof_pattern_value->arguments.push_back(typeof_node); typeof_pattern_value->arguments.push_back(p_pattern->constant); - + OperatorNode *type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_pattern_value); - - + // comare the actual values OperatorNode *value_comp = alloc_node<OperatorNode>(); value_comp->op = OperatorNode::OP_EQUAL; value_comp->arguments.push_back(p_pattern->constant); value_comp->arguments.push_back(p_node_to_match); - - + OperatorNode *comparison = alloc_node<OperatorNode>(); comparison->op = OperatorNode::OP_AND; comparison->arguments.push_back(type_comp); comparison->arguments.push_back(value_comp); - + p_resulting_node = comparison; - + } break; case PatternNode::PT_BIND: { p_bindings[p_pattern->bind] = p_node_to_match; - + // a bind always matches ConstantNode *true_value = alloc_node<ConstantNode>(); true_value->value = Variant(true); p_resulting_node = true_value; } break; case PatternNode::PT_ARRAY: { - + bool open_ended = false; - + if (p_pattern->array.size() > 0) { if (p_pattern->array[p_pattern->array.size() - 1]->pt_type == PatternNode::PT_IGNORE_REST) { open_ended = true; } } - + // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() >= length // typeof(value_to_match) == TYPE_ARRAY && value_to_match.size() == length - + { // typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDFunctions::TYPE_OF; - + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); - + IdentifierNode *typeof_array = alloc_node<IdentifierNode>(); typeof_array->name = "TYPE_ARRAY"; - + OperatorNode *type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_array); - - + // size ConstantNode *length = alloc_node<ConstantNode>(); length->value = Variant(open_ended ? p_pattern->array.size() - 1 : p_pattern->array.size()); - + OperatorNode *call = alloc_node<OperatorNode>(); call->op = OperatorNode::OP_CALL; call->arguments.push_back(p_node_to_match); - + IdentifierNode *size = alloc_node<IdentifierNode>(); size->name = "size"; call->arguments.push_back(size); - + OperatorNode *length_comparison = alloc_node<OperatorNode>(); length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL; length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); - + OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); type_and_length_comparison->op = OperatorNode::OP_AND; type_and_length_comparison->arguments.push_back(type_comp); type_and_length_comparison->arguments.push_back(length_comparison); - + p_resulting_node = type_and_length_comparison; } - - - + for (int i = 0; i < p_pattern->array.size(); i++) { PatternNode *pattern = p_pattern->array[i]; - + Node *condition = NULL; - + ConstantNode *index = alloc_node<ConstantNode>(); index->value = Variant(i); - + OperatorNode *indexed_value = alloc_node<OperatorNode>(); indexed_value->op = OperatorNode::OP_INDEX; indexed_value->arguments.push_back(p_node_to_match); indexed_value->arguments.push_back(index); - + _generate_pattern(pattern, indexed_value, condition, p_bindings); - + // concatenate all the patterns with && OperatorNode *and_node = alloc_node<OperatorNode>(); and_node->op = OperatorNode::OP_AND; and_node->arguments.push_back(p_resulting_node); and_node->arguments.push_back(condition); - + p_resulting_node = and_node; } - - + } break; case PatternNode::PT_DICTIONARY: { - + bool open_ended = false; - + if (p_pattern->array.size() > 0) { open_ended = true; } - + // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() >= length // typeof(value_to_match) == TYPE_DICTIONARY && value_to_match.size() == length - - + { // typecheck BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>(); typeof_node->function = GDFunctions::TYPE_OF; - + OperatorNode *typeof_match_value = alloc_node<OperatorNode>(); typeof_match_value->op = OperatorNode::OP_CALL; typeof_match_value->arguments.push_back(typeof_node); typeof_match_value->arguments.push_back(p_node_to_match); - + IdentifierNode *typeof_dictionary = alloc_node<IdentifierNode>(); typeof_dictionary->name = "TYPE_DICTIONARY"; - + OperatorNode *type_comp = alloc_node<OperatorNode>(); type_comp->op = OperatorNode::OP_EQUAL; type_comp->arguments.push_back(typeof_match_value); type_comp->arguments.push_back(typeof_dictionary); - + // size ConstantNode *length = alloc_node<ConstantNode>(); length->value = Variant(open_ended ? p_pattern->dictionary.size() - 1 : p_pattern->dictionary.size()); - + OperatorNode *call = alloc_node<OperatorNode>(); call->op = OperatorNode::OP_CALL; call->arguments.push_back(p_node_to_match); - + IdentifierNode *size = alloc_node<IdentifierNode>(); size->name = "size"; call->arguments.push_back(size); - + OperatorNode *length_comparison = alloc_node<OperatorNode>(); length_comparison->op = open_ended ? OperatorNode::OP_GREATER_EQUAL : OperatorNode::OP_EQUAL; length_comparison->arguments.push_back(call); length_comparison->arguments.push_back(length); - + OperatorNode *type_and_length_comparison = alloc_node<OperatorNode>(); type_and_length_comparison->op = OperatorNode::OP_AND; type_and_length_comparison->arguments.push_back(type_comp); type_and_length_comparison->arguments.push_back(length_comparison); - + p_resulting_node = type_and_length_comparison; } - - - - for (Map<ConstantNode*, PatternNode*>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) { - + + for (Map<ConstantNode *, PatternNode *>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) { + Node *condition = NULL; - + // chech for has, then for pattern - + IdentifierNode *has = alloc_node<IdentifierNode>(); has->name = "has"; - + OperatorNode *has_call = alloc_node<OperatorNode>(); has_call->op = OperatorNode::OP_CALL; has_call->arguments.push_back(p_node_to_match); has_call->arguments.push_back(has); has_call->arguments.push_back(e->key()); - - + if (e->value()) { - + OperatorNode *indexed_value = alloc_node<OperatorNode>(); indexed_value->op = OperatorNode::OP_INDEX; indexed_value->arguments.push_back(p_node_to_match); indexed_value->arguments.push_back(e->key()); - + _generate_pattern(e->value(), indexed_value, condition, p_bindings); - + OperatorNode *has_and_pattern = alloc_node<OperatorNode>(); has_and_pattern->op = OperatorNode::OP_AND; has_and_pattern->arguments.push_back(has_call); has_and_pattern->arguments.push_back(condition); - + condition = has_and_pattern; } else { condition = has_call; } - - - + // concatenate all the patterns with && OperatorNode *and_node = alloc_node<OperatorNode>(); and_node->op = OperatorNode::OP_AND; and_node->arguments.push_back(p_resulting_node); and_node->arguments.push_back(condition); - + p_resulting_node = and_node; } - + } break; case PatternNode::PT_IGNORE_REST: case PatternNode::PT_WILDCARD: { @@ -2187,119 +2177,110 @@ void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, p_resulting_node = true_value; } break; default: { - + } break; } } -void GDParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement) -{ +void GDParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement) { IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = "#match_value"; - + for (int i = 0; i < p_match_statement->branches.size(); i++) { - + PatternBranchNode *branch = p_match_statement->branches[i]; - + MatchNode::CompiledPatternBranch compiled_branch; compiled_branch.compiled_pattern = NULL; - - Map<StringName, Node*> binding; - + + Map<StringName, Node *> binding; + for (int j = 0; j < branch->patterns.size(); j++) { PatternNode *pattern = branch->patterns[j]; - - Map<StringName, Node*> bindings; + + Map<StringName, Node *> bindings; Node *resulting_node; _generate_pattern(pattern, id, resulting_node, bindings); - + if (!binding.empty() && !bindings.empty()) { _set_error("Multipatterns can't contain bindings"); return; } else { binding = bindings; } - + if (compiled_branch.compiled_pattern) { OperatorNode *or_node = alloc_node<OperatorNode>(); or_node->op = OperatorNode::OP_OR; or_node->arguments.push_back(compiled_branch.compiled_pattern); or_node->arguments.push_back(resulting_node); - + compiled_branch.compiled_pattern = or_node; } else { // single pattern | first one compiled_branch.compiled_pattern = resulting_node; } - } - - + // prepare the body ...hehe - for (Map<StringName, Node*>::Element *e = binding.front(); e; e = e->next()) { + for (Map<StringName, Node *>::Element *e = binding.front(); e; e = e->next()) { LocalVarNode *local_var = alloc_node<LocalVarNode>(); local_var->name = e->key(); local_var->assign = e->value(); - IdentifierNode *id = alloc_node<IdentifierNode>(); id->name = local_var->name; OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_ASSIGN; + op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(local_var->assign); - + branch->body->statements.push_front(op); branch->body->statements.push_front(local_var); } - + compiled_branch.body = branch->body; - - + p_match_statement->compiled_pattern_branches.push_back(compiled_branch); } - } -void GDParser::_parse_block(BlockNode *p_block,bool p_static) { +void GDParser::_parse_block(BlockNode *p_block, bool p_static) { int indent_level = tab_level.back()->get(); - #ifdef DEBUG_ENABLED NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); #endif - while(true) { + while (true) { GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return; - if (indent_level>tab_level.back()->get()) { - p_block->end_line=tokenizer->get_token_line(); + if (indent_level > tab_level.back()->get()) { + p_block->end_line = tokenizer->get_token_line(); return; //go back a level } - if (pending_newline!=-1) { + if (pending_newline != -1) { NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=pending_newline; + nl->line = pending_newline; p_block->statements.push_back(nl); - pending_newline=-1; - + pending_newline = -1; } - switch(token) { - + switch (token) { case GDTokenizer::TK_EOF: - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); case GDTokenizer::TK_ERROR: { return; //go back @@ -2310,26 +2291,25 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { if (!_parse_newline()) { if (!error_set) { - p_block->end_line=tokenizer->get_token_line(); - pending_newline=p_block->end_line; - + p_block->end_line = tokenizer->get_token_line(); + pending_newline = p_block->end_line; } return; } NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=tokenizer->get_token_line(); + nl->line = tokenizer->get_token_line(); p_block->statements.push_back(nl); } break; case GDTokenizer::TK_CF_PASS: { - if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE && tokenizer->get_token(1)!=GDTokenizer::TK_EOF) { + if (tokenizer->get_token(1) != GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDTokenizer::TK_EOF) { _set_error("Expected ';' or <NewLine>."); return; } tokenizer->advance(); - if(tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) { // Ignore semicolon after 'pass' tokenizer->advance(); } @@ -2338,26 +2318,26 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { //variale declaration and (eventual) initialization tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for local variable name."); return; } StringName n = tokenizer->get_token_identifier(); tokenizer->advance(); - if (current_function){ - for (int i=0;i<current_function->arguments.size();i++){ - if (n == current_function->arguments[i]){ - _set_error("Variable '"+String(n)+"' already defined in the scope (at line: "+itos(current_function->line)+")."); + if (current_function) { + for (int i = 0; i < current_function->arguments.size(); i++) { + if (n == current_function->arguments[i]) { + _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(current_function->line) + ")."); return; } } } BlockNode *check_block = p_block; - while (check_block){ - for (int i=0;i<check_block->variables.size();i++){ - if (n == check_block->variables[i]){ - _set_error("Variable '"+String(n)+"' already defined in the scope (at line: "+itos(check_block->variable_lines[i])+")."); + while (check_block) { + for (int i = 0; i < check_block->variables.size(); i++) { + if (n == check_block->variables[i]) { + _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variable_lines[i]) + ")."); return; } } @@ -2367,20 +2347,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { p_block->variables.push_back(n); //line? p_block->variable_lines.push_back(tokenizer->get_token_line()); - //must know when the local variable is declared LocalVarNode *lv = alloc_node<LocalVarNode>(); - lv->name=n; + lv->name = n; p_block->statements.push_back(lv); - Node *assigned=NULL; + Node *assigned = NULL; - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_block,p_static); + subexpr = _parse_and_reduce_expression(p_block, p_static); if (!subexpr) { if (_recover_from_completion()) { break; @@ -2388,23 +2367,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } - - - lv->assign=subexpr; - assigned=subexpr; + lv->assign = subexpr; + assigned = subexpr; } else { ConstantNode *c = alloc_node<ConstantNode>(); - c->value=Variant(); + c->value = Variant(); assigned = c; - } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=n; - + id->name = n; OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_ASSIGN; + op->op = OperatorNode::OP_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(assigned); p_block->statements.push_back(op); @@ -2418,8 +2393,8 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { case GDTokenizer::TK_CF_IF: { tokenizer->advance(); - - Node *condition = _parse_and_reduce_expression(p_block,p_static); + + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -2429,39 +2404,39 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { ControlFlowNode *cf_if = alloc_node<ControlFlowNode>(); - cf_if->cf_type=ControlFlowNode::CF_IF; + cf_if->cf_type = ControlFlowNode::CF_IF; cf_if->arguments.push_back(condition); cf_if->body = alloc_node<BlockNode>(); - cf_if->body->parent_block=p_block; + cf_if->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body); if (!_enter_indent_block(cf_if->body)) { _set_error("Expected intended block after 'if'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_if->body; - _parse_block(cf_if->body,p_static); - current_block=p_block; + current_block = cf_if->body; + _parse_block(cf_if->body, p_static); + current_block = p_block; if (error_set) return; p_block->statements.push_back(cf_if); - while(true) { + while (true) { - while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } if (tab_level.back()->get() < indent_level) { //not at current indent level - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - if (tokenizer->get_token()==GDTokenizer::TK_CF_ELIF) { + if (tokenizer->get_token() == GDTokenizer::TK_CF_ELIF) { if (tab_level.back()->get() > indent_level) { @@ -2471,15 +2446,15 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); - cf_if->body_else=alloc_node<BlockNode>(); - cf_if->body_else->parent_block=p_block; + cf_if->body_else = alloc_node<BlockNode>(); + cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); ControlFlowNode *cf_else = alloc_node<ControlFlowNode>(); - cf_else->cf_type=ControlFlowNode::CF_IF; + cf_else->cf_type = ControlFlowNode::CF_IF; //condition - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -2487,66 +2462,60 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } cf_else->arguments.push_back(condition); - cf_else->cf_type=ControlFlowNode::CF_IF; + cf_else->cf_type = ControlFlowNode::CF_IF; cf_if->body_else->statements.push_back(cf_else); - cf_if=cf_else; - cf_if->body=alloc_node<BlockNode>(); - cf_if->body->parent_block=p_block; + cf_if = cf_else; + cf_if->body = alloc_node<BlockNode>(); + cf_if->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body); - if (!_enter_indent_block(cf_if->body)) { _set_error("Expected indented block after 'elif'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_else->body; - _parse_block(cf_else->body,p_static); - current_block=p_block; + current_block = cf_else->body; + _parse_block(cf_else->body, p_static); + current_block = p_block; if (error_set) return; - - } else if (tokenizer->get_token()==GDTokenizer::TK_CF_ELSE) { + } else if (tokenizer->get_token() == GDTokenizer::TK_CF_ELSE) { if (tab_level.back()->get() > indent_level) { _set_error("Invalid indent"); return; } - tokenizer->advance(); - cf_if->body_else=alloc_node<BlockNode>(); - cf_if->body_else->parent_block=p_block; + cf_if->body_else = alloc_node<BlockNode>(); + cf_if->body_else->parent_block = p_block; p_block->sub_blocks.push_back(cf_if->body_else); if (!_enter_indent_block(cf_if->body_else)) { _set_error("Expected indented block after 'else'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_if->body_else; - _parse_block(cf_if->body_else,p_static); - current_block=p_block; + current_block = cf_if->body_else; + _parse_block(cf_if->body_else, p_static); + current_block = p_block; if (error_set) return; - break; //after else, exit } else break; - } - } break; case GDTokenizer::TK_CF_WHILE: { tokenizer->advance(); - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -2556,22 +2525,22 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { ControlFlowNode *cf_while = alloc_node<ControlFlowNode>(); - cf_while->cf_type=ControlFlowNode::CF_WHILE; + cf_while->cf_type = ControlFlowNode::CF_WHILE; cf_while->arguments.push_back(condition); cf_while->body = alloc_node<BlockNode>(); - cf_while->body->parent_block=p_block; + cf_while->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_while->body); if (!_enter_indent_block(cf_while->body)) { _set_error("Expected indented block after 'while'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_while->body; - _parse_block(cf_while->body,p_static); - current_block=p_block; + current_block = cf_while->body; + _parse_block(cf_while->body, p_static); + current_block = p_block; if (error_set) return; p_block->statements.push_back(cf_while); @@ -2580,24 +2549,24 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("identifier expected after 'for'"); } IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=tokenizer->get_token_identifier(); + id->name = tokenizer->get_token_identifier(); tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_OP_IN) { + if (tokenizer->get_token() != GDTokenizer::TK_OP_IN) { _set_error("'in' expected after identifier"); return; } tokenizer->advance(); - Node *container = _parse_and_reduce_expression(p_block,p_static); + Node *container = _parse_and_reduce_expression(p_block, p_static); if (!container) { if (_recover_from_completion()) { break; @@ -2605,91 +2574,90 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } - if (container->type==Node::TYPE_OPERATOR) { + if (container->type == Node::TYPE_OPERATOR) { - OperatorNode* op = static_cast<OperatorNode*>(container); - if (op->op==OperatorNode::OP_CALL && op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && static_cast<BuiltInFunctionNode*>(op->arguments[0])->function==GDFunctions::GEN_RANGE) { + OperatorNode *op = static_cast<OperatorNode *>(container); + if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && static_cast<BuiltInFunctionNode *>(op->arguments[0])->function == GDFunctions::GEN_RANGE) { //iterating a range, so see if range() can be optimized without allocating memory, by replacing it by vectors (which can work as iterable too!) - Vector<Node*> args; + Vector<Node *> args; Vector<double> constants; - bool constant=false; + bool constant = false; - for(int i=1;i<op->arguments.size();i++) { + for (int i = 1; i < op->arguments.size(); i++) { args.push_back(op->arguments[i]); - if (constant && op->arguments[i]->type==Node::TYPE_CONSTANT) { - ConstantNode *c = static_cast<ConstantNode*>(op->arguments[i]); - if (c->value.get_type()==Variant::REAL || c->value.get_type()==Variant::INT) { + if (constant && op->arguments[i]->type == Node::TYPE_CONSTANT) { + ConstantNode *c = static_cast<ConstantNode *>(op->arguments[i]); + if (c->value.get_type() == Variant::REAL || c->value.get_type() == Variant::INT) { constants.push_back(c->value); - constant=true; + constant = true; } } else { - constant=false; + constant = false; } } - if (args.size()>0 && args.size()<4) { + if (args.size() > 0 && args.size() < 4) { if (constant) { ConstantNode *cn = alloc_node<ConstantNode>(); - switch(args.size()) { - case 1: cn->value=constants[0]; break; - case 2: cn->value=Vector2(constants[0],constants[1]); break; - case 3: cn->value=Vector3(constants[0],constants[1],constants[2]); break; + switch (args.size()) { + case 1: cn->value = constants[0]; break; + case 2: cn->value = Vector2(constants[0], constants[1]); break; + case 3: cn->value = Vector3(constants[0], constants[1], constants[2]); break; } - container=cn; + container = cn; } else { OperatorNode *on = alloc_node<OperatorNode>(); - on->op=OperatorNode::OP_CALL; + on->op = OperatorNode::OP_CALL; TypeNode *tn = alloc_node<TypeNode>(); on->arguments.push_back(tn); - switch(args.size()) { - case 1: tn->vtype=Variant::REAL; break; - case 2: tn->vtype=Variant::VECTOR2; break; - case 3: tn->vtype=Variant::VECTOR3; break; + switch (args.size()) { + case 1: tn->vtype = Variant::REAL; break; + case 2: tn->vtype = Variant::VECTOR2; break; + case 3: tn->vtype = Variant::VECTOR3; break; } - for(int i=0;i<args.size();i++) { + for (int i = 0; i < args.size(); i++) { on->arguments.push_back(args[i]); } - container=on; + container = on; } } } - } ControlFlowNode *cf_for = alloc_node<ControlFlowNode>(); - cf_for->cf_type=ControlFlowNode::CF_FOR; + cf_for->cf_type = ControlFlowNode::CF_FOR; cf_for->arguments.push_back(id); cf_for->arguments.push_back(container); cf_for->body = alloc_node<BlockNode>(); - cf_for->body->parent_block=p_block; + cf_for->body->parent_block = p_block; p_block->sub_blocks.push_back(cf_for->body); if (!_enter_indent_block(cf_for->body)) { _set_error("Expected indented block after 'for'"); - p_block->end_line=tokenizer->get_token_line(); + p_block->end_line = tokenizer->get_token_line(); return; } - current_block=cf_for->body; + current_block = cf_for->body; // this is for checking variable for redefining // inside this _parse_block cf_for->body->variables.push_back(id->name); cf_for->body->variable_lines.push_back(id->line); - _parse_block(cf_for->body,p_static); + _parse_block(cf_for->body, p_static); cf_for->body->variables.remove(0); cf_for->body->variable_lines.remove(0); - current_block=p_block; + current_block = p_block; if (error_set) return; @@ -2699,7 +2667,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>(); - cf_continue->cf_type=ControlFlowNode::CF_CONTINUE; + cf_continue->cf_type = ControlFlowNode::CF_CONTINUE; p_block->statements.push_back(cf_continue); if (!_end_statement()) { _set_error("Expected end of statement (continue)"); @@ -2710,7 +2678,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_break = alloc_node<ControlFlowNode>(); - cf_break->cf_type=ControlFlowNode::CF_BREAK; + cf_break->cf_type = ControlFlowNode::CF_BREAK; p_block->statements.push_back(cf_break); if (!_end_statement()) { _set_error("Expected end of statement (break)"); @@ -2721,11 +2689,9 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); ControlFlowNode *cf_return = alloc_node<ControlFlowNode>(); - cf_return->cf_type=ControlFlowNode::CF_RETURN; + cf_return->cf_type = ControlFlowNode::CF_RETURN; - - - if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON || tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) { + if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) { //expect end of statement p_block->statements.push_back(cf_return); if (!_end_statement()) { @@ -2733,7 +2699,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } else { //expect expression - Node *retexpr = _parse_and_reduce_expression(p_block,p_static); + Node *retexpr = _parse_and_reduce_expression(p_block, p_static); if (!retexpr) { if (_recover_from_completion()) { break; @@ -2748,52 +2714,51 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } - } break; case GDTokenizer::TK_CF_MATCH: { - + tokenizer->advance(); - + MatchNode *match_node = alloc_node<MatchNode>(); - + Node *val_to_match = _parse_and_reduce_expression(p_block, p_static); - + if (!val_to_match) { if (_recover_from_completion()) { break; } return; } - + match_node->val_to_match = val_to_match; - + if (!_enter_indent_block()) { _set_error("Expected indented pattern matching block after 'match'"); return; } - + BlockNode *compiled_branches = alloc_node<BlockNode>(); compiled_branches->parent_block = p_block; compiled_branches->parent_class = p_block->parent_class; - + p_block->sub_blocks.push_back(compiled_branches); - + _parse_pattern_block(compiled_branches, match_node->branches, p_static); - + _transform_match_statment(compiled_branches, match_node); - + ControlFlowNode *match_cf_node = alloc_node<ControlFlowNode>(); match_cf_node->cf_type = ControlFlowNode::CF_MATCH; match_cf_node->match = match_node; - + p_block->statements.push_back(match_cf_node); - + _end_statement(); } break; case GDTokenizer::TK_PR_ASSERT: { tokenizer->advance(); - Node *condition = _parse_and_reduce_expression(p_block,p_static); + Node *condition = _parse_and_reduce_expression(p_block, p_static); if (!condition) { if (_recover_from_completion()) { break; @@ -2801,7 +2766,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { return; } AssertNode *an = alloc_node<AssertNode>(); - an->condition=condition; + an->condition = condition; p_block->statements.push_back(an); if (!_end_statement()) { @@ -2822,7 +2787,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } break; default: { - Node *expression = _parse_and_reduce_expression(p_block,p_static,false,true); + Node *expression = _parse_and_reduce_expression(p_block, p_static, false, true); if (!expression) { if (_recover_from_completion()) { break; @@ -2836,7 +2801,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { } } break; - /* + /* case GDTokenizer::TK_CF_LOCAL: { if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE ) { @@ -2846,37 +2811,35 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) { tokenizer->advance(); } break; */ - } } - } bool GDParser::_parse_newline() { - if (tokenizer->get_token(1)!=GDTokenizer::TK_EOF && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token(1) != GDTokenizer::TK_EOF && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) { int indent = tokenizer->get_token_line_indent(); int current_indent = tab_level.back()->get(); - if (indent>current_indent) { + if (indent > current_indent) { _set_error("Unexpected indent."); return false; } - if (indent<current_indent) { + if (indent < current_indent) { - while(indent<current_indent) { + while (indent < current_indent) { //exit block - if (tab_level.size()==1) { + if (tab_level.size() == 1) { _set_error("Invalid indent. BUG?"); return false; } tab_level.pop_back(); - if (tab_level.back()->get()<indent) { + if (tab_level.back()->get() < indent) { _set_error("Unindent does not match any outer indentation level."); return false; @@ -2891,13 +2854,10 @@ bool GDParser::_parse_newline() { tokenizer->advance(); return true; - } - void GDParser::_parse_extends(ClassNode *p_class) { - if (p_class->extends_used) { _set_error("'extends' already used for this class."); @@ -2910,73 +2870,70 @@ void GDParser::_parse_extends(ClassNode *p_class) { return; } - p_class->extends_used=true; + p_class->extends_used = true; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type()==Variant::OBJECT) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type() == Variant::OBJECT) { p_class->extends_class.push_back(Variant::get_type_name(Variant::OBJECT)); tokenizer->advance(); return; } // see if inheritance happens from a file - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) { Variant constant = tokenizer->get_token_constant(); - if (constant.get_type()!=Variant::STRING) { + if (constant.get_type() != Variant::STRING) { _set_error("'extends' constant must be a string."); return; } - p_class->extends_file=constant; + p_class->extends_file = constant; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() != GDTokenizer::TK_PERIOD) { return; } else tokenizer->advance(); - } - while(true) { - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + while (true) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Invalid 'extends' syntax, expected string constant (path) and/or identifier (parent class)."); return; } - StringName identifier=tokenizer->get_token_identifier(); + StringName identifier = tokenizer->get_token_identifier(); p_class->extends_class.push_back(identifier); tokenizer->advance(1); - if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD) + if (tokenizer->get_token() != GDTokenizer::TK_PERIOD) return; } - } void GDParser::_parse_class(ClassNode *p_class) { int indent_level = tab_level.back()->get(); - while(true) { + while (true) { GDTokenizer::Token token = tokenizer->get_token(); if (error_set) return; - - if (indent_level>tab_level.back()->get()) { - p_class->end_line=tokenizer->get_token_line(); + if (indent_level > tab_level.back()->get()) { + p_class->end_line = tokenizer->get_token_line(); return; //go back a level } - switch(token) { + switch (token) { case GDTokenizer::TK_EOF: - p_class->end_line=tokenizer->get_token_line(); + p_class->end_line = tokenizer->get_token_line(); case GDTokenizer::TK_ERROR: { return; //go back //end of file! @@ -2984,7 +2941,7 @@ void GDParser::_parse_class(ClassNode *p_class) { case GDTokenizer::TK_NEWLINE: { if (!_parse_newline()) { if (!error_set) { - p_class->end_line=tokenizer->get_token_line(); + p_class->end_line = tokenizer->get_token_line(); } return; } @@ -3008,7 +2965,7 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - p_class->tool=true; + p_class->tool = true; tokenizer->advance(); } break; @@ -3018,7 +2975,7 @@ void GDParser::_parse_class(ClassNode *p_class) { StringName name; StringName extends; - if (tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER) { _set_error("'class' syntax: 'class <Name>:' or 'class <Name> extends <BaseClass>:'"); return; @@ -3028,16 +2985,15 @@ void GDParser::_parse_class(ClassNode *p_class) { ClassNode *newclass = alloc_node<ClassNode>(); newclass->initializer = alloc_node<BlockNode>(); - newclass->initializer->parent_class=newclass; + newclass->initializer->parent_class = newclass; newclass->ready = alloc_node<BlockNode>(); - newclass->ready->parent_class=newclass; - newclass->name=name; - newclass->owner=p_class; + newclass->ready->parent_class = newclass; + newclass->name = name; + newclass->owner = p_class; p_class->subclasses.push_back(newclass); - - if (tokenizer->get_token()==GDTokenizer::TK_PR_EXTENDS) { + if (tokenizer->get_token() == GDTokenizer::TK_PR_EXTENDS) { _parse_extends(newclass); if (error_set) @@ -3049,9 +3005,9 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Indented block expected."); return; } - current_class=newclass; + current_class = newclass; _parse_class(newclass); - current_class=p_class; + current_class = p_class; } break; /* this is for functions.... @@ -3062,7 +3018,7 @@ void GDParser::_parse_class(ClassNode *p_class) { */ case GDTokenizer::TK_PR_STATIC: { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { _set_error("Expected 'func'."); return; @@ -3071,42 +3027,38 @@ void GDParser::_parse_class(ClassNode *p_class) { }; //fallthrough to function case GDTokenizer::TK_PR_FUNCTION: { - bool _static=false; - pending_newline=-1; + bool _static = false; + pending_newline = -1; - if (tokenizer->get_token(-1)==GDTokenizer::TK_PR_STATIC) { + if (tokenizer->get_token(-1) == GDTokenizer::TK_PR_STATIC) { - _static=true; + _static = true; } - tokenizer->advance(); StringName name; - if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC,name)) { - + if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC, name)) { } - - if (name==StringName()) { + if (name == StringName()) { _set_error("Expected identifier after 'func' (syntax: 'func <identifier>([arguments]):' )."); return; } - for(int i=0;i<p_class->functions.size();i++) { - if (p_class->functions[i]->name==name) { - _set_error("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->functions[i]->line)+")."); + for (int i = 0; i < p_class->functions.size(); i++) { + if (p_class->functions[i]->name == name) { + _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->functions[i]->line) + ")."); } } - for(int i=0;i<p_class->static_functions.size();i++) { - if (p_class->static_functions[i]->name==name) { - _set_error("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->static_functions[i]->line)+")."); + for (int i = 0; i < p_class->static_functions.size(); i++) { + if (p_class->static_functions[i]->name == name) { + _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->static_functions[i]->line) + ")."); } } - - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after identifier (syntax: 'func <identifier>([arguments]):' )."); return; @@ -3115,39 +3067,37 @@ void GDParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); Vector<StringName> arguments; - Vector<Node*> default_values; + Vector<Node *> default_values; int fnline = tokenizer->get_token_line(); - - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments - bool defaulting=false; - while(true) { + bool defaulting = false; + while (true) { - if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } - if (tokenizer->get_token()==GDTokenizer::TK_PR_VAR) { + if (tokenizer->get_token() == GDTokenizer::TK_PR_VAR) { tokenizer->advance(); //var before the identifier is allowed } - - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for argument."); return; } - StringName argname=tokenizer->get_token_identifier(); + StringName argname = tokenizer->get_token_identifier(); arguments.push_back(argname); tokenizer->advance(); - if (defaulting && tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) { + if (defaulting && tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) { _set_error("Default parameter expected."); return; @@ -3155,21 +3105,20 @@ void GDParser::_parse_class(ClassNode *p_class) { //tokenizer->advance(); - - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { - defaulting=true; + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { + defaulting = true; tokenizer->advance(1); - Node *defval=NULL; + Node *defval = NULL; - defval=_parse_and_reduce_expression(p_class,_static); + defval = _parse_and_reduce_expression(p_class, _static); if (!defval || error_set) return; OperatorNode *on = alloc_node<OperatorNode>(); - on->op=OperatorNode::OP_ASSIGN; + on->op = OperatorNode::OP_ASSIGN; IdentifierNode *in = alloc_node<IdentifierNode>(); - in->name=argname; + in->name = argname; on->arguments.push_back(in); on->arguments.push_back(defval); @@ -3182,14 +3131,14 @@ void GDParser::_parse_class(ClassNode *p_class) { default_values.push_back(on); } - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')'."); return; @@ -3197,68 +3146,63 @@ void GDParser::_parse_class(ClassNode *p_class) { break; } - - } tokenizer->advance(); BlockNode *block = alloc_node<BlockNode>(); - block->parent_class=p_class; + block->parent_class = p_class; - if (name=="_init") { + if (name == "_init") { if (p_class->extends_used) { OperatorNode *cparent = alloc_node<OperatorNode>(); - cparent->op=OperatorNode::OP_PARENT_CALL; + cparent->op = OperatorNode::OP_PARENT_CALL; block->statements.push_back(cparent); IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name="_init"; + id->name = "_init"; cparent->arguments.push_back(id); - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) { _set_error("expected '(' for parent constructor arguments."); } tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { //has arguments - parenthesis ++; - while(true) { + parenthesis++; + while (true) { - Node *arg = _parse_and_reduce_expression(p_class,_static); + Node *arg = _parse_and_reduce_expression(p_class, _static); cparent->arguments.push_back(arg); - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); continue; - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')'."); return; } break; - } - parenthesis --; + parenthesis--; } tokenizer->advance(); } } else { - - if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) { + if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) { _set_error("Parent constructor call found for a class without inheritance."); return; } - } } @@ -3269,34 +3213,32 @@ void GDParser::_parse_class(ClassNode *p_class) { } FunctionNode *function = alloc_node<FunctionNode>(); - function->name=name; - function->arguments=arguments; - function->default_values=default_values; - function->_static=_static; - function->line=fnline; - - function->rpc_mode=rpc_mode; - rpc_mode=ScriptInstance::RPC_MODE_DISABLED; + function->name = name; + function->arguments = arguments; + function->default_values = default_values; + function->_static = _static; + function->line = fnline; + function->rpc_mode = rpc_mode; + rpc_mode = ScriptInstance::RPC_MODE_DISABLED; if (_static) p_class->static_functions.push_back(function); else p_class->functions.push_back(function); - - current_function=function; - function->body=block; - current_block=block; - _parse_block(block,_static); - current_block=NULL; + current_function = function; + function->body = block; + current_block = block; + _parse_block(block, _static); + current_block = NULL; //arguments } break; case GDTokenizer::TK_PR_SIGNAL: { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier after 'signal'."); return; } @@ -3305,22 +3247,20 @@ void GDParser::_parse_class(ClassNode *p_class) { sig.name = tokenizer->get_token_identifier(); tokenizer->advance(); - - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { tokenizer->advance(); - while(true) { - if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (true) { + if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); continue; } - - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { tokenizer->advance(); break; } - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier in signal argument."); return; } @@ -3328,13 +3268,13 @@ void GDParser::_parse_class(ClassNode *p_class) { sig.arguments.push_back(tokenizer->get_token_identifier()); tokenizer->advance(); - while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { + while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')' after signal parameter identifier."); return; } @@ -3352,33 +3292,33 @@ void GDParser::_parse_class(ClassNode *p_class) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) { + if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) { Variant::Type type = tokenizer->get_token_type(); - if (type==Variant::NIL) { + if (type == Variant::NIL) { _set_error("Can't export null type."); return; } - current_export.type=type; - current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; + current_export.type = type; + current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; tokenizer->advance(); - - String hint_prefix =""; - - if(type == Variant::ARRAY && tokenizer->get_token()==GDTokenizer::TK_COMMA) { + + String hint_prefix = ""; + + if (type == Variant::ARRAY && tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - while(tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) { + while (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) { type = tokenizer->get_token_type(); - + tokenizer->advance(); - if(type == Variant::ARRAY) { - hint_prefix += itos(Variant::ARRAY)+":"; - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (type == Variant::ARRAY) { + hint_prefix += itos(Variant::ARRAY) + ":"; + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); } } else { @@ -3387,56 +3327,54 @@ void GDParser::_parse_class(ClassNode *p_class) { } } } - - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { // hint expected next! tokenizer->advance(); - switch(type) { - + switch (type) { case Variant::INT: { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FLAGS") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") { //current_export.hint=PROPERTY_HINT_ALL_FLAGS; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { break; } - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) - { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ')' or ',' in bit flags hint."); return; } - current_export.hint=PROPERTY_HINT_FLAGS; + current_export.hint = PROPERTY_HINT_FLAGS; tokenizer->advance(); bool first = true; - while(true) { + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { + current_export = PropertyInfo(); _set_error("Expected a string constant in named bit flags hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in named bit flags hint."); return; } @@ -3446,39 +3384,38 @@ void GDParser::_parse_class(ClassNode *p_class) { break; } - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration - current_export.hint=PROPERTY_HINT_ENUM; - bool first=true; - while(true) { + current_export.hint = PROPERTY_HINT_ENUM; + bool first = true; + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a string constant in enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in enumeration hint."); return; } tokenizer->advance(); - } break; @@ -3487,10 +3424,10 @@ void GDParser::_parse_class(ClassNode *p_class) { }; //fallthrough to use the same case Variant::REAL: { - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EASE") { - current_export.hint=PROPERTY_HINT_EXP_EASING; + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EASE") { + current_export.hint = PROPERTY_HINT_EXP_EASING; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } @@ -3498,146 +3435,143 @@ void GDParser::_parse_class(ClassNode *p_class) { } // range - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EXP") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EXP") { - current_export.hint=PROPERTY_HINT_EXP_RANGE; + current_export.hint = PROPERTY_HINT_EXP_RANGE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - else if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + else if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { _set_error("Expected ')' or ',' in exponential range hint."); return; } tokenizer->advance(); - } - else - current_export.hint=PROPERTY_HINT_RANGE; + } else + current_export.hint = PROPERTY_HINT_RANGE; - float sign=1.0; + float sign = 1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a range in numeric hint."); return; - } - current_export.hint_string=rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string = rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) { - current_export.hint_string="0,"+current_export.hint_string; + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) { + current_export.hint_string = "0," + current_export.hint_string; break; } - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ',' or ')' in numeric range hint."); return; } tokenizer->advance(); - sign=1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + sign = 1.0; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a number as upper bound in numeric range hint."); return; } - current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ',' or ')' in numeric range hint."); return; } tokenizer->advance(); - sign=1.0; - if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) { - sign=-1; + sign = 1.0; + if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) { + sign = -1; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a number as step in numeric range hint."); return; } - current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant())); + current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant())); tokenizer->advance(); } break; case Variant::STRING: { - if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) { + if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) { //enumeration - current_export.hint=PROPERTY_HINT_ENUM; - bool first=true; - while(true) { + current_export.hint = PROPERTY_HINT_ENUM; + bool first = true; + while (true) { - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected a string constant in enumeration hint."); return; } String c = tokenizer->get_token_constant(); if (!first) - current_export.hint_string+=","; + current_export.hint_string += ","; else - first=false; + first = false; - current_export.hint_string+=c.xml_escape(); + current_export.hint_string += c.xml_escape(); tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { - current_export=PropertyInfo(); + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { + current_export = PropertyInfo(); _set_error("Expected ')' or ',' in enumeration hint."); return; } tokenizer->advance(); - } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="DIR") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "DIR") { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) - current_export.hint=PROPERTY_HINT_DIR; - else if (tokenizer->get_token()==GDTokenizer::TK_COMMA ) { + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) + current_export.hint = PROPERTY_HINT_DIR; + else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier()=="GLOBAL")) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) { _set_error("Expected 'GLOBAL' after comma in directory hint."); return; } @@ -3645,42 +3579,41 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } - current_export.hint=PROPERTY_HINT_GLOBAL_DIR; + current_export.hint = PROPERTY_HINT_GLOBAL_DIR; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } - } - else { + } else { _set_error("Expected ')' or ',' in hint."); return; } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FILE") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FILE") { - current_export.hint=PROPERTY_HINT_FILE; + current_export.hint = PROPERTY_HINT_FILE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="GLOBAL") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "GLOBAL") { if (!p_class->tool) { _set_error("Global filesystem hints may only be used in tool scripts."); return; } - current_export.hint=PROPERTY_HINT_GLOBAL_FILE; + current_export.hint = PROPERTY_HINT_GLOBAL_FILE; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) + if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) break; - else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) + else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) tokenizer->advance(); else { _set_error("Expected ')' or ',' in hint."); @@ -3688,31 +3621,30 @@ void GDParser::_parse_class(ClassNode *p_class) { } } - if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) { + if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) { - if (current_export.hint==PROPERTY_HINT_GLOBAL_FILE) + if (current_export.hint == PROPERTY_HINT_GLOBAL_FILE) _set_error("Expected string constant with filter"); else _set_error("Expected 'GLOBAL' or string constant with filter"); return; } - current_export.hint_string=tokenizer->get_token_constant(); + current_export.hint_string = tokenizer->get_token_constant(); tokenizer->advance(); - } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } break; } - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="MULTILINE") { + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "MULTILINE") { - current_export.hint=PROPERTY_HINT_MULTILINE_TEXT; + current_export.hint = PROPERTY_HINT_MULTILINE_TEXT; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in hint."); return; } @@ -3721,20 +3653,20 @@ void GDParser::_parse_class(ClassNode *p_class) { } break; case Variant::COLOR: { - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER ) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints"); return; } String identifier = tokenizer->get_token_identifier(); - if (identifier=="RGB") { - current_export.hint=PROPERTY_HINT_COLOR_NO_ALPHA; - } else if (identifier=="RGBA") { + if (identifier == "RGB") { + current_export.hint = PROPERTY_HINT_COLOR_NO_ALPHA; + } else if (identifier == "RGBA") { //none } else { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Color type hint expects RGB or RGBA as hints"); return; } @@ -3743,54 +3675,51 @@ void GDParser::_parse_class(ClassNode *p_class) { } break; default: { - current_export=PropertyInfo(); - _set_error("Type '"+Variant::get_type_name(type)+"' can't take hints."); + current_export = PropertyInfo(); + _set_error("Type '" + Variant::get_type_name(type) + "' can't take hints."); return; } break; } - } - if(current_export.type == Variant::ARRAY && !hint_prefix.empty()) { - if(current_export.hint) { - hint_prefix += "/"+itos(current_export.hint); + if (current_export.type == Variant::ARRAY && !hint_prefix.empty()) { + if (current_export.hint) { + hint_prefix += "/" + itos(current_export.hint); } - current_export.hint_string=hint_prefix+":"+current_export.hint_string; - current_export.hint=PROPERTY_HINT_NONE; + current_export.hint_string = hint_prefix + ":" + current_export.hint_string; + current_export.hint = PROPERTY_HINT_NONE; } - } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { + } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { String identifier = tokenizer->get_token_identifier(); - if (!ClassDB::is_parent_class(identifier,"Resource")) { + if (!ClassDB::is_parent_class(identifier, "Resource")) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Export hint not a type or resource."); } - current_export.type=Variant::OBJECT; - current_export.hint=PROPERTY_HINT_RESOURCE_TYPE; - current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; + current_export.type = Variant::OBJECT; + current_export.hint = PROPERTY_HINT_RESOURCE_TYPE; + current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; - current_export.hint_string=identifier; + current_export.hint_string = identifier; tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) { + if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected ')' or ',' after export hint."); return; - } tokenizer->advance(); - } - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_ONREADY && tokenizer->get_token()!=GDTokenizer::TK_PR_REMOTE && tokenizer->get_token()!=GDTokenizer::TK_PR_MASTER && tokenizer->get_token()!=GDTokenizer::TK_PR_SLAVE && tokenizer->get_token()!=GDTokenizer::TK_PR_SYNC) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDTokenizer::TK_PR_SLAVE && tokenizer->get_token() != GDTokenizer::TK_PR_SYNC) { - current_export=PropertyInfo(); + current_export = PropertyInfo(); _set_error("Expected 'var', 'onready', 'remote', 'master', 'slave' or 'sync'."); return; } @@ -3801,7 +3730,7 @@ void GDParser::_parse_class(ClassNode *p_class) { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { _set_error("Expected 'var'."); return; } @@ -3812,19 +3741,19 @@ void GDParser::_parse_class(ClassNode *p_class) { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (current_export.type) { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (current_export.type) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { _set_error("Expected 'var'."); return; } } else { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { _set_error("Expected 'var' or 'func'."); return; } } - rpc_mode=ScriptInstance::RPC_MODE_REMOTE; + rpc_mode = ScriptInstance::RPC_MODE_REMOTE; continue; } break; @@ -3832,47 +3761,47 @@ void GDParser::_parse_class(ClassNode *p_class) { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (current_export.type) { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (current_export.type) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { _set_error("Expected 'var'."); return; } } else { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { _set_error("Expected 'var' or 'func'."); return; } } - rpc_mode=ScriptInstance::RPC_MODE_MASTER; + rpc_mode = ScriptInstance::RPC_MODE_MASTER; continue; } break; case GDTokenizer::TK_PR_SLAVE: { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (current_export.type) { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) { + if (current_export.type) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) { _set_error("Expected 'var'."); return; } } else { - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { _set_error("Expected 'var' or 'func'."); return; } } - rpc_mode=ScriptInstance::RPC_MODE_SLAVE; + rpc_mode = ScriptInstance::RPC_MODE_SLAVE; continue; } break; case GDTokenizer::TK_PR_SYNC: { //may be fallthrough from export, ignore if so tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) { + if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) { if (current_export.type) _set_error("Expected 'var'."); else @@ -3880,48 +3809,48 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - rpc_mode=ScriptInstance::RPC_MODE_SYNC; + rpc_mode = ScriptInstance::RPC_MODE_SYNC; continue; } break; case GDTokenizer::TK_PR_VAR: { //variale declaration and (eventual) initialization ClassNode::Member member; - bool autoexport = tokenizer->get_token(-1)==GDTokenizer::TK_PR_EXPORT; - if (current_export.type!=Variant::NIL) { - member._export=current_export; - current_export=PropertyInfo(); + bool autoexport = tokenizer->get_token(-1) == GDTokenizer::TK_PR_EXPORT; + if (current_export.type != Variant::NIL) { + member._export = current_export; + current_export = PropertyInfo(); } - bool onready = tokenizer->get_token(-1)==GDTokenizer::TK_PR_ONREADY; + bool onready = tokenizer->get_token(-1) == GDTokenizer::TK_PR_ONREADY; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for member variable name."); return; } - member.identifier=tokenizer->get_token_identifier(); - member.expression=NULL; - member._export.name=member.identifier; - member.line=tokenizer->get_token_line(); - member.rpc_mode=rpc_mode; + member.identifier = tokenizer->get_token_identifier(); + member.expression = NULL; + member._export.name = member.identifier; + member.line = tokenizer->get_token_line(); + member.rpc_mode = rpc_mode; tokenizer->advance(); - rpc_mode=ScriptInstance::RPC_MODE_DISABLED; + rpc_mode = ScriptInstance::RPC_MODE_DISABLED; - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { #ifdef DEBUG_ENABLED int line = tokenizer->get_token_line(); #endif tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_class,false,autoexport); + subexpr = _parse_and_reduce_expression(p_class, false, autoexport); if (!subexpr) { if (_recover_from_completion()) { break; @@ -3930,24 +3859,23 @@ void GDParser::_parse_class(ClassNode *p_class) { } //discourage common error - if (!onready && subexpr->type==Node::TYPE_OPERATOR) { + if (!onready && subexpr->type == Node::TYPE_OPERATOR) { - OperatorNode *op=static_cast<OperatorNode*>(subexpr); - if (op->op==OperatorNode::OP_CALL && op->arguments[0]->type==Node::TYPE_SELF && op->arguments[1]->type==Node::TYPE_IDENTIFIER) { - IdentifierNode *id=static_cast<IdentifierNode*>(op->arguments[1]); - if (id->name=="get_node") { + OperatorNode *op = static_cast<OperatorNode *>(subexpr); + if (op->op == OperatorNode::OP_CALL && op->arguments[0]->type == Node::TYPE_SELF && op->arguments[1]->type == Node::TYPE_IDENTIFIER) { + IdentifierNode *id = static_cast<IdentifierNode *>(op->arguments[1]); + if (id->name == "get_node") { - _set_error("Use 'onready var "+String(member.identifier)+" = get_node(..)' instead"); + _set_error("Use 'onready var " + String(member.identifier) + " = get_node(..)' instead"); return; - } } } - member.expression=subexpr; + member.expression = subexpr; if (autoexport) { - if (1)/*(subexpr->type==Node::TYPE_ARRAY) { + if (1) /*(subexpr->type==Node::TYPE_ARRAY) { member._export.type=Variant::ARRAY; @@ -3957,54 +3885,53 @@ void GDParser::_parse_class(ClassNode *p_class) { } else*/ { - if (subexpr->type!=Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } - ConstantNode *cn = static_cast<ConstantNode*>(subexpr); - if (cn->value.get_type()==Variant::NIL) { + ConstantNode *cn = static_cast<ConstantNode *>(subexpr); + if (cn->value.get_type() == Variant::NIL) { _set_error("Can't accept a null constant expression for infering export type."); return; } - member._export.type=cn->value.get_type(); - member._export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE; - if (cn->value.get_type()==Variant::OBJECT) { + member._export.type = cn->value.get_type(); + member._export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; + if (cn->value.get_type() == Variant::OBJECT) { Object *obj = cn->value; Resource *res = obj->cast_to<Resource>(); - if(res==NULL) { + if (res == NULL) { _set_error("Exported constant not a type or resource."); return; } - member._export.hint=PROPERTY_HINT_RESOURCE_TYPE; - member._export.hint_string=res->get_class(); + member._export.hint = PROPERTY_HINT_RESOURCE_TYPE; + member._export.hint_string = res->get_class(); } } } #ifdef TOOLS_ENABLED - if (subexpr->type==Node::TYPE_CONSTANT && member._export.type!=Variant::NIL) { + if (subexpr->type == Node::TYPE_CONSTANT && member._export.type != Variant::NIL) { - ConstantNode *cn = static_cast<ConstantNode*>(subexpr); - if (cn->value.get_type()!=Variant::NIL) { - member.default_value=cn->value; + ConstantNode *cn = static_cast<ConstantNode *>(subexpr); + if (cn->value.get_type() != Variant::NIL) { + member.default_value = cn->value; } } #endif IdentifierNode *id = alloc_node<IdentifierNode>(); - id->name=member.identifier; + id->name = member.identifier; OperatorNode *op = alloc_node<OperatorNode>(); - op->op=OperatorNode::OP_INIT_ASSIGN; + op->op = OperatorNode::OP_INIT_ASSIGN; op->arguments.push_back(id); op->arguments.push_back(subexpr); - #ifdef DEBUG_ENABLED NewLineNode *nl = alloc_node<NewLineNode>(); - nl->line=line; + nl->line = line; if (onready) p_class->ready->statements.push_back(nl); else @@ -4015,8 +3942,6 @@ void GDParser::_parse_class(ClassNode *p_class) { else p_class->initializer->statements.push_back(op); - - } else { if (autoexport) { @@ -4024,36 +3949,33 @@ void GDParser::_parse_class(ClassNode *p_class) { _set_error("Type-less export needs a constant expression assigned to infer type."); return; } - } - if (tokenizer->get_token()==GDTokenizer::TK_PR_SETGET) { - + if (tokenizer->get_token() == GDTokenizer::TK_PR_SETGET) { tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() != GDTokenizer::TK_COMMA) { //just comma means using only getter - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for setter function after 'notify'."); } - member.setter=tokenizer->get_token_identifier(); + member.setter = tokenizer->get_token_identifier(); tokenizer->advance(); } - if (tokenizer->get_token()==GDTokenizer::TK_COMMA) { + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { //there is a getter tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected identifier for getter function after ','."); } - member.getter=tokenizer->get_token_identifier(); + member.getter = tokenizer->get_token_identifier(); tokenizer->advance(); - } } @@ -4070,25 +3992,25 @@ void GDParser::_parse_class(ClassNode *p_class) { ClassNode::Constant constant; tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { + if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { _set_error("Expected name (identifier) for constant."); return; } - constant.identifier=tokenizer->get_token_identifier(); + constant.identifier = tokenizer->get_token_identifier(); tokenizer->advance(); - if (tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) { + if (tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) { _set_error("Constant expects assignment."); return; } tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_class,true,true); + subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; @@ -4096,10 +4018,10 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - if (subexpr->type!=Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected constant expression"); } - constant.expression=subexpr; + constant.expression = subexpr; p_class->constant_expressions.push_back(constant); @@ -4117,46 +4039,46 @@ void GDParser::_parse_class(ClassNode *p_class) { Dictionary enum_dict; tokenizer->advance(); - if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) { - enum_name=tokenizer->get_token_identifier(); + if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) { + enum_name = tokenizer->get_token_identifier(); tokenizer->advance(); } - if (tokenizer->get_token()!=GDTokenizer::TK_CURLY_BRACKET_OPEN) { + if (tokenizer->get_token() != GDTokenizer::TK_CURLY_BRACKET_OPEN) { _set_error("Expected '{' in enum declaration"); return; } tokenizer->advance(); - - while(true) { - if(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) { - + + while (true) { + if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) { + tokenizer->advance(); // Ignore newlines - } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_CLOSE) { - + } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) { + tokenizer->advance(); break; // End of enum - } else if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) { - - if(tokenizer->get_token()==GDTokenizer::TK_EOF) { + } else if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) { + + if (tokenizer->get_token() == GDTokenizer::TK_EOF) { _set_error("Unexpected end of file."); } else { _set_error(String("Unexpected ") + GDTokenizer::get_token_name(tokenizer->get_token()) + ", expected identifier"); } - + return; } else { // tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER ClassNode::Constant constant; - - constant.identifier=tokenizer->get_token_identifier(); - + + constant.identifier = tokenizer->get_token_identifier(); + tokenizer->advance(); - - if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) { + + if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) { tokenizer->advance(); - Node *subexpr=NULL; + Node *subexpr = NULL; - subexpr = _parse_and_reduce_expression(p_class,true,true); + subexpr = _parse_and_reduce_expression(p_class, true, true); if (!subexpr) { if (_recover_from_completion()) { break; @@ -4164,19 +4086,19 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - if (subexpr->type!=Node::TYPE_CONSTANT) { + if (subexpr->type != Node::TYPE_CONSTANT) { _set_error("Expected constant expression"); } - - const ConstantNode *subexpr_const = static_cast<const ConstantNode*>(subexpr); - - if(subexpr_const->value.get_type() != Variant::INT) { + + const ConstantNode *subexpr_const = static_cast<const ConstantNode *>(subexpr); + + if (subexpr_const->value.get_type() != Variant::INT) { _set_error("Expected an int value for enum"); } - + last_assign = subexpr_const->value; - - constant.expression=subexpr; + + constant.expression = subexpr; } else { last_assign = last_assign + 1; @@ -4184,27 +4106,26 @@ void GDParser::_parse_class(ClassNode *p_class) { cn->value = last_assign; constant.expression = cn; } - - if(tokenizer->get_token()==GDTokenizer::TK_COMMA) { + + if (tokenizer->get_token() == GDTokenizer::TK_COMMA) { tokenizer->advance(); } - if(enum_name != "") { - const ConstantNode *cn = static_cast<const ConstantNode*>(constant.expression); + if (enum_name != "") { + const ConstantNode *cn = static_cast<const ConstantNode *>(constant.expression); enum_dict[constant.identifier] = cn->value; } p_class->constant_expressions.push_back(constant); } - } - - if(enum_name != "") { + + if (enum_name != "") { ClassNode::Constant enum_constant; - enum_constant.identifier=enum_name; + enum_constant.identifier = enum_name; ConstantNode *cn = alloc_node<ConstantNode>(); cn->value = enum_dict; - enum_constant.expression=cn; + enum_constant.expression = cn; p_class->constant_expressions.push_back(enum_constant); } @@ -4213,46 +4134,37 @@ void GDParser::_parse_class(ClassNode *p_class) { return; } - - - } break; - + case GDTokenizer::TK_CONSTANT: { - if(tokenizer->get_token_constant().get_type() == Variant::STRING) { + if (tokenizer->get_token_constant().get_type() == Variant::STRING) { tokenizer->advance(); // Ignore } else { - _set_error(String()+"Unexpected constant of type: "+Variant::get_type_name(tokenizer->get_token_constant().get_type())); + _set_error(String() + "Unexpected constant of type: " + Variant::get_type_name(tokenizer->get_token_constant().get_type())); return; } } break; default: { - _set_error(String()+"Unexpected token: "+tokenizer->get_token_name(tokenizer->get_token())+":"+tokenizer->get_token_identifier()); + _set_error(String() + "Unexpected token: " + tokenizer->get_token_name(tokenizer->get_token()) + ":" + tokenizer->get_token_identifier()); return; } break; - } - } - - } - -void GDParser::_set_error(const String& p_error, int p_line, int p_column) { - +void GDParser::_set_error(const String &p_error, int p_line, int p_column) { if (error_set) return; //allow no further errors - error=p_error; - error_line=p_line<0?tokenizer->get_token_line():p_line; - error_column=p_column<0?tokenizer->get_token_column():p_column; - error_set=true; + error = p_error; + error_line = p_line < 0 ? tokenizer->get_token_line() : p_line; + error_column = p_column < 0 ? tokenizer->get_token_column() : p_column; + error_set = true; } String GDParser::get_error() const { @@ -4269,27 +4181,25 @@ int GDParser::get_error_column() const { return error_column; } +Error GDParser::_parse(const String &p_base_path) { -Error GDParser::_parse(const String& p_base_path) { - - - base_path=p_base_path; + base_path = p_base_path; clear(); //assume class ClassNode *main_class = alloc_node<ClassNode>(); main_class->initializer = alloc_node<BlockNode>(); - main_class->initializer->parent_class=main_class; + main_class->initializer->parent_class = main_class; main_class->ready = alloc_node<BlockNode>(); - main_class->ready->parent_class=main_class; - current_class=main_class; + main_class->ready->parent_class = main_class; + current_class = main_class; _parse_class(main_class); - if (tokenizer->get_token()==GDTokenizer::TK_ERROR) { - error_set=false; - _set_error("Parse Error: "+tokenizer->get_token_error()); + if (tokenizer->get_token() == GDTokenizer::TK_ERROR) { + error_set = false; + _set_error("Parse Error: " + tokenizer->get_token_error()); } if (error_set) { @@ -4299,60 +4209,59 @@ Error GDParser::_parse(const String& p_base_path) { return OK; } -Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path, const String &p_self_path) { - - for_completion=false; - validating=false; - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - completion_found=false; - current_block=NULL; - current_class=NULL; - current_function=NULL; - - self_path=p_self_path; - GDTokenizerBuffer *tb = memnew( GDTokenizerBuffer ); +Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path, const String &p_self_path) { + + for_completion = false; + validating = false; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + completion_found = false; + current_block = NULL; + current_class = NULL; + current_function = NULL; + + self_path = p_self_path; + GDTokenizerBuffer *tb = memnew(GDTokenizerBuffer); tb->set_code_buffer(p_bytecode); - tokenizer=tb; + tokenizer = tb; Error ret = _parse(p_base_path); memdelete(tb); - tokenizer=NULL; + tokenizer = NULL; return ret; } +Error GDParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion) { -Error GDParser::parse(const String& p_code, const String& p_base_path, bool p_just_validate, const String &p_self_path,bool p_for_completion) { - - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - completion_found=false; - current_block=NULL; - current_class=NULL; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + completion_found = false; + current_block = NULL; + current_class = NULL; - current_function=NULL; + current_function = NULL; - self_path=p_self_path; - GDTokenizerText *tt = memnew( GDTokenizerText ); + self_path = p_self_path; + GDTokenizerText *tt = memnew(GDTokenizerText); tt->set_code(p_code); - validating=p_just_validate; - for_completion=p_for_completion; - tokenizer=tt; + validating = p_just_validate; + for_completion = p_for_completion; + tokenizer = tt; Error ret = _parse(p_base_path); memdelete(tt); - tokenizer=NULL; + tokenizer = NULL; return ret; } bool GDParser::is_tool_script() const { - return (head && head->type==Node::TYPE_CLASS && static_cast<const ClassNode*>(head)->tool); + return (head && head->type == Node::TYPE_CLASS && static_cast<const ClassNode *>(head)->tool); } const GDParser::Node *GDParser::get_parse_tree() const { @@ -4362,44 +4271,42 @@ const GDParser::Node *GDParser::get_parse_tree() const { void GDParser::clear() { - while(list) { + while (list) { - Node *l=list; - list=list->next; + Node *l = list; + list = list->next; memdelete(l); } - head=NULL; - list=NULL; + head = NULL; + list = NULL; - completion_type=COMPLETION_NONE; - completion_node=NULL; - completion_class=NULL; - completion_function=NULL; - completion_block=NULL; - current_block=NULL; - current_class=NULL; + completion_type = COMPLETION_NONE; + completion_node = NULL; + completion_class = NULL; + completion_function = NULL; + completion_block = NULL; + current_block = NULL; + current_class = NULL; - completion_found=false; - rpc_mode=ScriptInstance::RPC_MODE_DISABLED; + completion_found = false; + rpc_mode = ScriptInstance::RPC_MODE_DISABLED; - current_function=NULL; + current_function = NULL; - validating=false; - for_completion=false; - error_set=false; + validating = false; + for_completion = false; + error_set = false; tab_level.clear(); tab_level.push_back(0); - error_line=0; - error_column=0; - pending_newline=-1; - parenthesis=0; - current_export.type=Variant::NIL; - error=""; - + error_line = 0; + error_column = 0; + pending_newline = -1; + parenthesis = 0; + current_export.type = Variant::NIL; + error = ""; } - GDParser::CompletionType GDParser::get_completion_type() { return completion_type; @@ -4415,12 +4322,12 @@ int GDParser::get_completion_line() { return completion_line; } -Variant::Type GDParser::get_completion_built_in_constant(){ +Variant::Type GDParser::get_completion_built_in_constant() { return completion_built_in_constant; } -GDParser::Node *GDParser::get_completion_node(){ +GDParser::Node *GDParser::get_completion_node() { return completion_node; } @@ -4430,12 +4337,12 @@ GDParser::BlockNode *GDParser::get_completion_block() { return completion_block; } -GDParser::ClassNode *GDParser::get_completion_class(){ +GDParser::ClassNode *GDParser::get_completion_class() { return completion_class; } -GDParser::FunctionNode *GDParser::get_completion_function(){ +GDParser::FunctionNode *GDParser::get_completion_function() { return completion_function; } @@ -4452,12 +4359,11 @@ int GDParser::get_completion_identifier_is_function() { GDParser::GDParser() { - head=NULL; - list=NULL; - tokenizer=NULL; - pending_newline=-1; + head = NULL; + list = NULL; + tokenizer = NULL; + pending_newline = -1; clear(); - } GDParser::~GDParser() { diff --git a/modules/gdscript/gd_parser.h b/modules/gdscript/gd_parser.h index 7968bf85df..8d2c136818 100644 --- a/modules/gdscript/gd_parser.h +++ b/modules/gdscript/gd_parser.h @@ -29,15 +29,14 @@ #ifndef GD_PARSER_H #define GD_PARSER_H -#include "gd_tokenizer.h" #include "gd_functions.h" +#include "gd_tokenizer.h" #include "map.h" #include "object.h" #include "script_language.h" class GDParser { public: - struct Node { enum Type { @@ -59,7 +58,7 @@ public: TYPE_NEWLINE, }; - Node * next; + Node *next; int line; int column; Type type; @@ -78,7 +77,6 @@ public: StringName extends_file; Vector<StringName> extends_class; - struct Member { PropertyInfo _export; #ifdef TOOLS_ENABLED @@ -101,11 +99,11 @@ public: Vector<StringName> arguments; }; - Vector<ClassNode*> subclasses; + Vector<ClassNode *> subclasses; Vector<Member> variables; Vector<Constant> constant_expressions; - Vector<FunctionNode*> functions; - Vector<FunctionNode*> static_functions; + Vector<FunctionNode *> functions; + Vector<FunctionNode *> static_functions; Vector<Signal> _signals; BlockNode *initializer; BlockNode *ready; @@ -113,74 +111,88 @@ public: //Vector<Node*> initializers; int end_line; - ClassNode() { tool=false; type=TYPE_CLASS; extends_used=false; end_line=-1; owner=NULL;} + ClassNode() { + tool = false; + type = TYPE_CLASS; + extends_used = false; + end_line = -1; + owner = NULL; + } }; - - struct FunctionNode : public Node { bool _static; ScriptInstance::RPCMode rpc_mode; StringName name; Vector<StringName> arguments; - Vector<Node*> default_values; + Vector<Node *> default_values; BlockNode *body; - FunctionNode() { type=TYPE_FUNCTION; _static=false; rpc_mode=ScriptInstance::RPC_MODE_DISABLED; } - + FunctionNode() { + type = TYPE_FUNCTION; + _static = false; + rpc_mode = ScriptInstance::RPC_MODE_DISABLED; + } }; struct BlockNode : public Node { ClassNode *parent_class; BlockNode *parent_block; - Map<StringName,int> locals; - List<Node*> statements; + Map<StringName, int> locals; + List<Node *> statements; Vector<StringName> variables; Vector<int> variable_lines; //the following is useful for code completion - List<BlockNode*> sub_blocks; + List<BlockNode *> sub_blocks; int end_line; - BlockNode() { type=TYPE_BLOCK; end_line=-1; parent_block=NULL; parent_class=NULL; } + BlockNode() { + type = TYPE_BLOCK; + end_line = -1; + parent_block = NULL; + parent_class = NULL; + } }; struct TypeNode : public Node { Variant::Type vtype; - TypeNode() { type=TYPE_TYPE; } + TypeNode() { type = TYPE_TYPE; } }; struct BuiltInFunctionNode : public Node { GDFunctions::Function function; - BuiltInFunctionNode() { type=TYPE_BUILT_IN_FUNCTION; } + BuiltInFunctionNode() { type = TYPE_BUILT_IN_FUNCTION; } }; struct IdentifierNode : public Node { StringName name; - IdentifierNode() { type=TYPE_IDENTIFIER; } + IdentifierNode() { type = TYPE_IDENTIFIER; } }; struct LocalVarNode : public Node { StringName name; Node *assign; - LocalVarNode() { type=TYPE_LOCAL_VAR; assign=NULL;} + LocalVarNode() { + type = TYPE_LOCAL_VAR; + assign = NULL; + } }; struct ConstantNode : public Node { Variant value; - ConstantNode() { type=TYPE_CONSTANT; } + ConstantNode() { type = TYPE_CONSTANT; } }; struct ArrayNode : public Node { - Vector<Node*> elements; - ArrayNode() { type=TYPE_ARRAY; } + Vector<Node *> elements; + ArrayNode() { type = TYPE_ARRAY; } }; - struct DictionaryNode : public Node { struct Pair { @@ -190,11 +202,11 @@ public: }; Vector<Pair> elements; - DictionaryNode() { type=TYPE_DICTIONARY; } + DictionaryNode() { type = TYPE_DICTIONARY; } }; struct SelfNode : public Node { - SelfNode() { type=TYPE_SELF; } + SelfNode() { type = TYPE_SELF; } }; struct OperatorNode : public Node { @@ -255,13 +267,12 @@ public: Operator op; - Vector<Node*> arguments; - OperatorNode() { type=TYPE_OPERATOR; } + Vector<Node *> arguments; + OperatorNode() { type = TYPE_OPERATOR; } }; - - + struct PatternNode : public Node { - + enum PatternType { PT_CONSTANT, PT_BIND, @@ -270,30 +281,29 @@ public: PT_IGNORE_REST, PT_WILDCARD }; - + PatternType pt_type; - + Node *constant; StringName bind; - Map<ConstantNode*, PatternNode*> dictionary; - Vector<PatternNode*> array; - + Map<ConstantNode *, PatternNode *> dictionary; + Vector<PatternNode *> array; }; - + struct PatternBranchNode : public Node { - Vector<PatternNode*> patterns; + Vector<PatternNode *> patterns; BlockNode *body; }; - + struct MatchNode : public Node { Node *val_to_match; - Vector<PatternBranchNode*> branches; - + Vector<PatternBranchNode *> branches; + struct CompiledPatternBranch { Node *compiled_pattern; BlockNode *body; }; - + Vector<CompiledPatternBranch> compiled_pattern_branches; }; @@ -310,30 +320,34 @@ public: }; CFType cf_type; - Vector<Node*> arguments; + Vector<Node *> arguments; BlockNode *body; BlockNode *body_else; - + MatchNode *match; ControlFlowNode *_else; //used for if - ControlFlowNode() { type=TYPE_CONTROL_FLOW; cf_type=CF_IF; body=NULL; body_else=NULL;} + ControlFlowNode() { + type = TYPE_CONTROL_FLOW; + cf_type = CF_IF; + body = NULL; + body_else = NULL; + } }; struct AssertNode : public Node { - Node* condition; - AssertNode() { type=TYPE_ASSERT; } + Node *condition; + AssertNode() { type = TYPE_ASSERT; } }; struct BreakpointNode : public Node { - BreakpointNode() { type=TYPE_BREAKPOINT; } + BreakpointNode() { type = TYPE_BREAKPOINT; } }; struct NewLineNode : public Node { - NewLineNode() { type=TYPE_NEWLINE; } + NewLineNode() { type = TYPE_NEWLINE; } }; - struct Expression { bool is_op; @@ -343,8 +357,7 @@ public: }; }; - -/* + /* struct OperatorNode : public Node { DataType return_cache; @@ -428,18 +441,13 @@ public: COMPLETION_YIELD, }; - - private: - - GDTokenizer *tokenizer; - Node *head; Node *list; - template<class T> - T* alloc_node(); + template <class T> + T *alloc_node(); bool validating; bool for_completion; @@ -456,12 +464,11 @@ private: String base_path; String self_path; - ClassNode *current_class; FunctionNode *current_function; BlockNode *current_block; - bool _get_completable_identifier(CompletionType p_type,StringName& identifier); + bool _get_completable_identifier(CompletionType p_type, StringName &identifier); void _make_completable_call(int p_arg); CompletionType completion_type; @@ -481,41 +488,34 @@ private: ScriptInstance::RPCMode rpc_mode; - - void _set_error(const String& p_error, int p_line=-1, int p_column=-1); + void _set_error(const String &p_error, int p_line = -1, int p_column = -1); bool _recover_from_completion(); - - bool _parse_arguments(Node* p_parent, Vector<Node*>& p_args, bool p_static, bool p_can_codecomplete=false); - bool _enter_indent_block(BlockNode *p_block=NULL); + bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false); + bool _enter_indent_block(BlockNode *p_block = NULL); bool _parse_newline(); - Node* _parse_expression(Node *p_parent, bool p_static, bool p_allow_assign=false, bool p_parsing_constant=false); - Node* _reduce_expression(Node *p_node,bool p_to_const=false); - Node* _parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const=false,bool p_allow_assign=false); + Node *_parse_expression(Node *p_parent, bool p_static, bool p_allow_assign = false, bool p_parsing_constant = false); + Node *_reduce_expression(Node *p_node, bool p_to_const = false); + Node *_parse_and_reduce_expression(Node *p_parent, bool p_static, bool p_reduce_const = false, bool p_allow_assign = false); - - - PatternNode *_parse_pattern(bool p_static); - void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode*> &p_branches, bool p_static); + void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static); void _transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement); - void _generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node*> &p_bindings); - - - void _parse_block(BlockNode *p_block,bool p_static); + void _generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings); + + void _parse_block(BlockNode *p_block, bool p_static); void _parse_extends(ClassNode *p_class); void _parse_class(ClassNode *p_class); bool _end_statement(); - Error _parse(const String& p_base_path); + Error _parse(const String &p_base_path); public: - String get_error() const; int get_error_line() const; int get_error_column() const; - Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); - Error parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path="",const String& p_self_path=""); + Error parse(const String &p_code, const String &p_base_path = "", bool p_just_validate = false, const String &p_self_path = "", bool p_for_completion = false); + Error parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path = "", const String &p_self_path = ""); bool is_tool_script() const; const Node *get_parse_tree() const; diff --git a/modules/gdscript/gd_script.cpp b/modules/gdscript/gd_script.cpp index 4e72bc39a4..e1cc75acfc 100644 --- a/modules/gdscript/gd_script.cpp +++ b/modules/gdscript/gd_script.cpp @@ -27,18 +27,18 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_script.h" +#include "gd_compiler.h" #include "global_config.h" #include "global_constants.h" -#include "gd_compiler.h" -#include "os/file_access.h" #include "io/file_access_encrypted.h" +#include "os/file_access.h" #include "os/os.h" /////////////////////////// -GDNativeClass::GDNativeClass(const StringName& p_name) { +GDNativeClass::GDNativeClass(const StringName &p_name) { - name=p_name; + name = p_name; } /*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){ @@ -46,33 +46,30 @@ GDNativeClass::GDNativeClass(const StringName& p_name) { }*/ - -bool GDNativeClass::_get(const StringName& p_name,Variant &r_ret) const { +bool GDNativeClass::_get(const StringName &p_name, Variant &r_ret) const { bool ok; int v = ClassDB::get_integer_constant(name, p_name, &ok); if (ok) { - r_ret=v; + r_ret = v; return true; } else { return false; } } - void GDNativeClass::_bind_methods() { - ClassDB::bind_method(D_METHOD("new"),&GDNativeClass::_new); - + ClassDB::bind_method(D_METHOD("new"), &GDNativeClass::_new); } Variant GDNativeClass::_new() { Object *o = instance(); if (!o) { - ERR_EXPLAIN("Class type: '"+String(name)+"' is not instantiable."); - ERR_FAIL_COND_V(!o,Variant()); + ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable."); + ERR_FAIL_COND_V(!o, Variant()); } Reference *ref = o->cast_to<Reference>(); @@ -81,7 +78,6 @@ Variant GDNativeClass::_new() { } else { return o; } - } Object *GDNativeClass::instance() { @@ -89,27 +85,24 @@ Object *GDNativeClass::instance() { return ClassDB::instance(name); } - - -GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError& r_error) { - +GDInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) { /* STEP 1, CREATE */ - GDInstance* instance = memnew( GDInstance ); - instance->base_ref=p_isref; + GDInstance *instance = memnew(GDInstance); + instance->base_ref = p_isref; instance->members.resize(member_indices.size()); - instance->script=Ref<GDScript>(this); - instance->owner=p_owner; + instance->script = Ref<GDScript>(this); + instance->owner = p_owner; #ifdef DEBUG_ENABLED //needed for hot reloading - for(Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) { - instance->member_indices_cache[E->key()]=E->get().index; + for (Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) { + instance->member_indices_cache[E->key()] = E->get().index; } #endif instance->owner->set_script_instance(instance); - /* STEP 2, INITIALIZE AND CONSRTUCT */ +/* STEP 2, INITIALIZE AND CONSRTUCT */ #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); @@ -121,10 +114,10 @@ GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Obj GDScriptLanguage::singleton->lock->unlock(); #endif - initializer->call(instance,p_args,p_argcount,r_error); + initializer->call(instance, p_args, p_argcount, r_error); - if (r_error.error!=Variant::CallError::CALL_OK) { - instance->script=Ref<GDScript>(); + if (r_error.error != Variant::CallError::CALL_OK) { + instance->script = Ref<GDScript>(); instance->owner->set_script_instance(NULL); #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); @@ -134,47 +127,45 @@ GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Obj GDScriptLanguage::singleton->lock->unlock(); #endif - ERR_FAIL_COND_V(r_error.error!=Variant::CallError::CALL_OK, NULL); //error constructing + ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing } //@TODO make thread safe return instance; - } -Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) { +Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { /* STEP 1, CREATE */ if (!valid) { - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } - r_error.error=Variant::CallError::CALL_OK; + r_error.error = Variant::CallError::CALL_OK; REF ref; - Object *owner=NULL; + Object *owner = NULL; - GDScript *_baseptr=this; + GDScript *_baseptr = this; while (_baseptr->_base) { - _baseptr=_baseptr->_base; + _baseptr = _baseptr->_base; } ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant()); if (_baseptr->native.ptr()) { - owner=_baseptr->native->instance(); + owner = _baseptr->native->instance(); } else { - owner=memnew( Reference ); //by default, no base means use reference + owner = memnew(Reference); //by default, no base means use reference } - Reference *r=owner->cast_to<Reference>(); + Reference *r = owner->cast_to<Reference>(); if (r) { - ref=REF(r); + ref = REF(r); } - - GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL,r_error); + GDInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error); if (!instance) { if (ref.is_null()) { memdelete(owner); //no owner, sorry @@ -193,13 +184,12 @@ bool GDScript::can_instance() const { //return valid; //any script in GDscript can instance return valid || (!tool && !ScriptServer::is_scripting_enabled()); - } Ref<Script> GDScript::get_base_script() const { if (_base) { - return Ref<GDScript>( _base ); + return Ref<GDScript>(_base); } else { return Ref<Script>(); } @@ -218,14 +208,11 @@ struct _GDScriptMemberSort { int index; StringName name; - _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; } - + _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; } }; - #ifdef TOOLS_ENABLED - void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { placeholders.erase(p_placeholder); @@ -275,86 +262,80 @@ void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) { }*/ #endif - void GDScript::get_script_method_list(List<MethodInfo> *p_list) const { - for (const Map<StringName,GDFunction*>::Element *E=member_functions.front();E;E=E->next()) { + for (const Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) { MethodInfo mi; - mi.name=E->key(); - for(int i=0;i<E->get()->get_argument_count();i++) { + mi.name = E->key(); + for (int i = 0; i < E->get()->get_argument_count(); i++) { PropertyInfo arg; - arg.type=Variant::NIL; //variant - arg.name=E->get()->get_argument_name(i); + arg.type = Variant::NIL; //variant + arg.name = E->get()->get_argument_name(i); mi.arguments.push_back(arg); } - mi.return_val.name="Variant"; + mi.return_val.name = "Variant"; p_list->push_back(mi); } } void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const { - const GDScript *sptr=this; + const GDScript *sptr = this; List<PropertyInfo> props; - while(sptr) { + while (sptr) { Vector<_GDScriptMemberSort> msort; - for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) { + for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) { _GDScriptMemberSort ms; ERR_CONTINUE(!sptr->member_indices.has(E->key())); - ms.index=sptr->member_indices[E->key()].index; - ms.name=E->key(); + ms.index = sptr->member_indices[E->key()].index; + ms.name = E->key(); msort.push_back(ms); - } msort.sort(); msort.invert(); - for(int i=0;i<msort.size();i++) { + for (int i = 0; i < msort.size(); i++) { props.push_front(sptr->member_info[msort[i].name]); - } sptr = sptr->_base; } - for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { p_list->push_back(E->get()); } - } -bool GDScript::has_method(const StringName& p_method) const { +bool GDScript::has_method(const StringName &p_method) const { return member_functions.has(p_method); } -MethodInfo GDScript::get_method_info(const StringName& p_method) const { +MethodInfo GDScript::get_method_info(const StringName &p_method) const { - const Map<StringName,GDFunction*>::Element *E=member_functions.find(p_method); + const Map<StringName, GDFunction *>::Element *E = member_functions.find(p_method); if (!E) return MethodInfo(); MethodInfo mi; - mi.name=E->key(); - for(int i=0;i<E->get()->get_argument_count();i++) { + mi.name = E->key(); + for (int i = 0; i < E->get()->get_argument_count(); i++) { PropertyInfo arg; - arg.type=Variant::NIL; //variant - arg.name=E->get()->get_argument_name(i); + arg.type = Variant::NIL; //variant + arg.name = E->get()->get_argument_name(i); mi.arguments.push_back(arg); } - mi.return_val.name="Variant"; + mi.return_val.name = "Variant"; return mi; - } - -bool GDScript::get_property_default_value(const StringName& p_property, Variant &r_value) const { +bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const { #ifdef TOOLS_ENABLED @@ -363,26 +344,23 @@ bool GDScript::get_property_default_value(const StringName& p_property, Variant print_line("\t"+String(String(I->key())+":"+String(I->get()))); } */ - const Map<StringName,Variant>::Element *E=member_default_values_cache.find(p_property); + const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property); if (E) { - r_value=E->get(); + r_value = E->get(); return true; } if (base_cache.is_valid()) { - return base_cache->get_property_default_value(p_property,r_value); + return base_cache->get_property_default_value(p_property, r_value); } #endif return false; - } -ScriptInstance* GDScript::instance_create(Object *p_this) { - +ScriptInstance *GDScript::instance_create(Object *p_this) { if (!tool && !ScriptServer::is_scripting_enabled()) { - #ifdef TOOLS_ENABLED //instance a fake script for editing the values @@ -392,7 +370,7 @@ ScriptInstance* GDScript::instance_create(Object *p_this) { for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) { print_line(E->get().name); }*/ - PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) ); + PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this)); placeholders.insert(si); //_update_placeholder(si); _update_exports(); @@ -402,32 +380,30 @@ ScriptInstance* GDScript::instance_create(Object *p_this) { #endif } - GDScript *top=this; - while(top->_base) - top=top->_base; + GDScript *top = this; + while (top->_base) + top = top->_base; if (top->native.is_valid()) { - if (!ClassDB::is_parent_class(p_this->get_class_name(),top->native->get_name())) { + if (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),0,"Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_class()+"'"); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); } - ERR_EXPLAIN("Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_class()+"'"); + ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); ERR_FAIL_V(NULL); - } } Variant::CallError unchecked_error; - return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>(),unchecked_error); - + return _create_instance(NULL, 0, p_this, p_this->cast_to<Reference>(), unchecked_error); } bool GDScript::instance_has(const Object *p_this) const { #ifndef NO_THREADS GDScriptLanguage::singleton->lock->lock(); #endif - bool hasit = instances.has((Object*)p_this); + bool hasit = instances.has((Object *)p_this); #ifndef NO_THREADS GDScriptLanguage::singleton->lock->unlock(); @@ -438,39 +414,37 @@ bool GDScript::instance_has(const Object *p_this) const { bool GDScript::has_source_code() const { - return source!=""; + return source != ""; } String GDScript::get_source_code() const { return source; } -void GDScript::set_source_code(const String& p_code) { +void GDScript::set_source_code(const String &p_code) { - if (source==p_code) + if (source == p_code) return; - source=p_code; + source = p_code; #ifdef TOOLS_ENABLED - source_changed_cache=true; - //print_line("SC CHANGED "+get_path()); + source_changed_cache = true; +//print_line("SC CHANGED "+get_path()); #endif - } #ifdef TOOLS_ENABLED -void GDScript::_update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames) { +void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) { if (base_cache.is_valid()) { - base_cache->_update_exports_values(values,propnames); + base_cache->_update_exports_values(values, propnames); } - for(Map<StringName,Variant>::Element *E=member_default_values_cache.front();E;E=E->next()) { - values[E->key()]=E->get(); + for (Map<StringName, Variant>::Element *E = member_default_values_cache.front(); E; E = E->next()) { + values[E->key()] = E->get(); } - for (List<PropertyInfo>::Element *E=members_cache.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) { propnames.push_back(E->get()); } - } #endif @@ -478,90 +452,87 @@ bool GDScript::_update_exports() { #ifdef TOOLS_ENABLED - bool changed=false; + bool changed = false; if (source_changed_cache) { //print_line("updating source for "+get_path()); - source_changed_cache=false; - changed=true; + source_changed_cache = false; + changed = true; - String basedir=path; + String basedir = path; - if (basedir=="") - basedir=get_path(); + if (basedir == "") + basedir = get_path(); - if (basedir!="") - basedir=basedir.get_base_dir(); + if (basedir != "") + basedir = basedir.get_base_dir(); GDParser parser; - Error err = parser.parse(source,basedir,true,path); + Error err = parser.parse(source, basedir, true, path); - if (err==OK) { + if (err == OK) { - const GDParser::Node* root = parser.get_parse_tree(); - ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false); + const GDParser::Node *root = parser.get_parse_tree(); + ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false); - const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode*>(root); + const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode *>(root); if (base_cache.is_valid()) { base_cache->inheriters_cache.erase(get_instance_ID()); - base_cache=Ref<GDScript>(); + base_cache = Ref<GDScript>(); } - - if (c->extends_used && String(c->extends_file)!="" && String(c->extends_file) != get_path()) { + if (c->extends_used && String(c->extends_file) != "" && String(c->extends_file) != get_path()) { String path = c->extends_file; if (path.is_rel_path()) { String base = get_path(); - if (base=="" || base.is_rel_path()) { + if (base == "" || base.is_rel_path()) { - ERR_PRINT(("Could not resolve relative path for parent class: "+path).utf8().get_data()); + ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data()); } else { - path=base.get_base_dir().plus_file(path); + path = base.get_base_dir().plus_file(path); } } - if (path!=get_path()) { + if (path != get_path()) { Ref<GDScript> bf = ResourceLoader::load(path); if (bf.is_valid()) { //print_line("parent is: "+bf->get_path()); - base_cache=bf; + base_cache = bf; bf->inheriters_cache.insert(get_instance_ID()); //bf->_update_exports(p_instances,true,false); - } } else { - ERR_PRINT(("Path extending itself in "+path).utf8().get_data()); + ERR_PRINT(("Path extending itself in " + path).utf8().get_data()); } } members_cache.clear(); member_default_values_cache.clear(); - for(int i=0;i<c->variables.size();i++) { - if (c->variables[i]._export.type==Variant::NIL) + for (int i = 0; i < c->variables.size(); i++) { + if (c->variables[i]._export.type == Variant::NIL) continue; members_cache.push_back(c->variables[i]._export); //print_line("found "+c->variables[i]._export.name); - member_default_values_cache[c->variables[i].identifier]=c->variables[i].default_value; + member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value; } _signals.clear(); - for(int i=0;i<c->_signals.size();i++) { - _signals[c->_signals[i].name]=c->_signals[i].arguments; + for (int i = 0; i < c->_signals.size(); i++) { + _signals[c->_signals[i].name] = c->_signals[i].arguments; } } } else { //print_line("unchaged is "+get_path()); - } if (base_cache.is_valid()) { @@ -575,13 +546,13 @@ bool GDScript::_update_exports() { //print_line("updating placeholders for "+get_path()); //update placeholders if any - Map<StringName,Variant> values; + Map<StringName, Variant> values; List<PropertyInfo> propnames; - _update_exports_values(values,propnames); + _update_exports_values(values, propnames); - for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { + for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propnames,values); + E->get()->update(propnames, values); } } @@ -597,14 +568,14 @@ void GDScript::update_exports() { _update_exports(); - Set<ObjectID> copy=inheriters_cache; //might get modified + Set<ObjectID> copy = inheriters_cache; //might get modified //print_line("update exports for "+get_path()+" ic: "+itos(copy.size())); - for(Set<ObjectID>::Element *E=copy.front();E;E=E->next()) { - Object *id=ObjectDB::get_instance(E->get()); + for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) { + Object *id = ObjectDB::get_instance(E->get()); if (!id) continue; - GDScript *s=id->cast_to<GDScript>(); + GDScript *s = id->cast_to<GDScript>(); if (!s) continue; s->update_exports(); @@ -613,12 +584,12 @@ void GDScript::update_exports() { #endif } -void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) { +void GDScript::_set_subclass_path(Ref<GDScript> &p_sc, const String &p_path) { - p_sc->path=p_path; - for(Map<StringName,Ref<GDScript> >::Element *E=p_sc->subclasses.front();E;E=E->next()) { + p_sc->path = p_path; + for (Map<StringName, Ref<GDScript> >::Element *E = p_sc->subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),p_path); + _set_subclass_path(E->get(), p_path); } } @@ -633,58 +604,54 @@ Error GDScript::reload(bool p_keep_state) { GDScriptLanguage::singleton->lock->unlock(); #endif - ERR_FAIL_COND_V(!p_keep_state && has_instances,ERR_ALREADY_IN_USE); - - String basedir=path; - - if (basedir=="") - basedir=get_path(); + ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE); - if (basedir!="") - basedir=basedir.get_base_dir(); + String basedir = path; + if (basedir == "") + basedir = get_path(); + if (basedir != "") + basedir = basedir.get_base_dir(); - - valid=false; + valid = false; GDParser parser; - Error err = parser.parse(source,basedir,false,path); + Error err = parser.parse(source, basedir, false, path); if (err) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),parser.get_error_line(),"Parser Error: "+parser.get_error()); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), parser.get_error_line(), "Parser Error: " + parser.get_error()); } - _err_print_error("GDScript::reload",path.empty()?"built-in":(const char*)path.utf8().get_data(),parser.get_error_line(),("Parse Error: "+parser.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_PARSE_ERROR); } - bool can_run = ScriptServer::is_scripting_enabled() || parser.is_tool_script(); GDCompiler compiler; - err = compiler.compile(&parser,this,p_keep_state); + err = compiler.compile(&parser, this, p_keep_state); if (err) { if (can_run) { if (ScriptDebugger::get_singleton()) { - GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error()); + GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), compiler.get_error_line(), "Parser Error: " + compiler.get_error()); } - _err_print_error("GDScript::reload",path.empty()?"built-in":(const char*)path.utf8().get_data(),compiler.get_error_line(),("Compile Error: "+compiler.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::reload", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_COMPILATION_FAILED); } else { return err; } } - valid=true; + valid = true; - for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),path); + _set_subclass_path(E->get(), path); } #ifdef TOOLS_ENABLED - /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { +/*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { _update_placeholder(E->get()); }*/ @@ -702,74 +669,67 @@ ScriptLanguage *GDScript::get_language() const { return GDScriptLanguage::get_singleton(); } +Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { -Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { + GDScript *top = this; + while (top) { - - GDScript *top=this; - while(top) { - - Map<StringName,GDFunction*>::Element *E=top->member_functions.find(p_method); + Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method); if (E) { if (!E->get()->is_static()) { - WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data()); + WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data()); } - return E->get()->call(NULL,p_args,p_argcount,r_error); + return E->get()->call(NULL, p_args, p_argcount, r_error); } - top=top->_base; + top = top->_base; } //none found, regular - return Script::call(p_method,p_args,p_argcount,r_error); - + return Script::call(p_method, p_args, p_argcount, r_error); } -bool GDScript::_get(const StringName& p_name,Variant &r_ret) const { +bool GDScript::_get(const StringName &p_name, Variant &r_ret) const { { - - const GDScript *top=this; - while(top) { + const GDScript *top = this; + while (top) { { - const Map<StringName,Variant>::Element *E=top->constants.find(p_name); + const Map<StringName, Variant>::Element *E = top->constants.find(p_name); if (E) { - r_ret= E->get(); + r_ret = E->get(); return true; } } { - const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name); + const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name); if (E) { - r_ret=E->get(); + r_ret = E->get(); return true; } } - top=top->_base; + top = top->_base; } - if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) { + if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) { - r_ret=get_source_code(); + r_ret = get_source_code(); return true; } } - - return false; - } -bool GDScript::_set(const StringName& p_name, const Variant& p_value) { +bool GDScript::_set(const StringName &p_name, const Variant &p_value) { - if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) { + if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) { set_source_code(p_value); reload(); @@ -781,159 +741,147 @@ bool GDScript::_set(const StringName& p_name, const Variant& p_value) { void GDScript::_get_property_list(List<PropertyInfo> *p_properties) const { - p_properties->push_back( PropertyInfo(Variant::STRING,"script/source",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) ); + p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } - void GDScript::_bind_methods() { - ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo(Variant::OBJECT,"new")); - - ClassDB::bind_method(D_METHOD("get_as_byte_code"),&GDScript::get_as_byte_code); + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new")); + ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code); } - Vector<uint8_t> GDScript::get_as_byte_code() const { GDTokenizerBuffer tokenizer; return tokenizer.parse_code_string(source); }; - -Error GDScript::load_byte_code(const String& p_path) { +Error GDScript::load_byte_code(const String &p_path) { Vector<uint8_t> bytecode; if (p_path.ends_with("gde")) { - FileAccess *fa = FileAccess::open(p_path,FileAccess::READ); - ERR_FAIL_COND_V(!fa,ERR_CANT_OPEN); - FileAccessEncrypted *fae = memnew( FileAccessEncrypted ); - ERR_FAIL_COND_V(!fae,ERR_CANT_OPEN); + FileAccess *fa = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V(!fa, ERR_CANT_OPEN); + FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + ERR_FAIL_COND_V(!fae, ERR_CANT_OPEN); Vector<uint8_t> key; key.resize(32); - for(int i=0;i<key.size();i++) { - key[i]=script_encryption_key[i]; + for (int i = 0; i < key.size(); i++) { + key[i] = script_encryption_key[i]; } - Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_READ); - ERR_FAIL_COND_V(err,err); + Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ); + ERR_FAIL_COND_V(err, err); bytecode.resize(fae->get_len()); - fae->get_buffer(bytecode.ptr(),bytecode.size()); + fae->get_buffer(bytecode.ptr(), bytecode.size()); memdelete(fae); } else { bytecode = FileAccess::get_file_as_array(p_path); } - ERR_FAIL_COND_V(bytecode.size()==0,ERR_PARSE_ERROR); - path=p_path; + ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR); + path = p_path; - String basedir=path; + String basedir = path; - if (basedir=="") - basedir=get_path(); + if (basedir == "") + basedir = get_path(); - if (basedir!="") - basedir=basedir.get_base_dir(); + if (basedir != "") + basedir = basedir.get_base_dir(); - valid=false; + valid = false; GDParser parser; - Error err = parser.parse_bytecode(bytecode,basedir,get_path()); + Error err = parser.parse_bytecode(bytecode, basedir, get_path()); if (err) { - _err_print_error("GDScript::load_byte_code",path.empty()?"built-in":(const char*)path.utf8().get_data(),parser.get_error_line(),("Parse Error: "+parser.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), parser.get_error_line(), ("Parse Error: " + parser.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_PARSE_ERROR); } GDCompiler compiler; - err = compiler.compile(&parser,this); + err = compiler.compile(&parser, this); if (err) { - _err_print_error("GDScript::load_byte_code",path.empty()?"built-in":(const char*)path.utf8().get_data(),compiler.get_error_line(),("Compile Error: "+compiler.get_error()).utf8().get_data(),ERR_HANDLER_SCRIPT); + _err_print_error("GDScript::load_byte_code", path.empty() ? "built-in" : (const char *)path.utf8().get_data(), compiler.get_error_line(), ("Compile Error: " + compiler.get_error()).utf8().get_data(), ERR_HANDLER_SCRIPT); ERR_FAIL_V(ERR_COMPILATION_FAILED); } - valid=true; + valid = true; - for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { - _set_subclass_path(E->get(),path); + _set_subclass_path(E->get(), path); } return OK; } - -Error GDScript::load_source_code(const String& p_path) { - +Error GDScript::load_source_code(const String &p_path) { PoolVector<uint8_t> sourcef; Error err; - FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err); + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); } int len = f->get_len(); - sourcef.resize(len+1); + sourcef.resize(len + 1); PoolVector<uint8_t>::Write w = sourcef.write(); - int r = f->get_buffer(w.ptr(),len); + int r = f->get_buffer(w.ptr(), len); f->close(); memdelete(f); - ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN); - w[len]=0; + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); + w[len] = 0; String s; - if (s.parse_utf8((const char*)w.ptr())) { + if (s.parse_utf8((const char *)w.ptr())) { - ERR_EXPLAIN("Script '"+p_path+"' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); + ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); ERR_FAIL_V(ERR_INVALID_DATA); } - source=s; + source = s; #ifdef TOOLS_ENABLED - source_changed_cache=true; + source_changed_cache = true; #endif //print_line("LSC :"+get_path()); - path=p_path; + path = p_path; return OK; - } - -const Map<StringName,GDFunction*>& GDScript::debug_get_member_functions() const { +const Map<StringName, GDFunction *> &GDScript::debug_get_member_functions() const { return member_functions; } - - StringName GDScript::debug_get_member_by_index(int p_idx) const { + for (const Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) { - for(const Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) { - - if (E->get().index==p_idx) + if (E->get().index == p_idx) return E->key(); } return "<error>"; } - Ref<GDScript> GDScript::get_base() const { return base; } -bool GDScript::has_script_signal(const StringName& p_signal) const { +bool GDScript::has_script_signal(const StringName &p_signal) const { if (_signals.has(p_signal)) return true; if (base.is_valid()) { return base->has_script_signal(p_signal); } #ifdef TOOLS_ENABLED - else if (base_cache.is_valid()){ + else if (base_cache.is_valid()) { return base_cache->has_script_signal(p_signal); } @@ -942,13 +890,13 @@ bool GDScript::has_script_signal(const StringName& p_signal) const { } void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const { - for(const Map<StringName,Vector<StringName> >::Element *E=_signals.front();E;E=E->next()) { + for (const Map<StringName, Vector<StringName> >::Element *E = _signals.front(); E; E = E->next()) { MethodInfo mi; - mi.name=E->key(); - for(int i=0;i<E->get().size();i++) { + mi.name = E->key(); + for (int i = 0; i < E->get().size(); i++) { PropertyInfo arg; - arg.name=E->get()[i]; + arg.name = E->get()[i]; mi.arguments.push_back(arg); } r_signals->push_back(mi); @@ -958,27 +906,25 @@ void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const { base->get_script_signal_list(r_signals); } #ifdef TOOLS_ENABLED - else if (base_cache.is_valid()){ + else if (base_cache.is_valid()) { base_cache->get_script_signal_list(r_signals); } #endif - } +GDScript::GDScript() + : script_list(this) { -GDScript::GDScript() : script_list(this) { - - - _static_ref=this; - valid=false; - subclass_count=0; - initializer=NULL; - _base=NULL; - _owner=NULL; - tool=false; + _static_ref = this; + valid = false; + subclass_count = 0; + initializer = NULL; + _base = NULL; + _owner = NULL; + tool = false; #ifdef TOOLS_ENABLED - source_changed_cache=false; + source_changed_cache = false; #endif #ifdef DEBUG_ENABLED @@ -994,12 +940,12 @@ GDScript::GDScript() : script_list(this) { } GDScript::~GDScript() { - for (Map<StringName,GDFunction*>::Element *E=member_functions.front();E;E=E->next()) { - memdelete( E->get() ); + for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) { + memdelete(E->get()); } - for (Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) { - E->get()->_owner=NULL; //bye, you are no longer owned cause I died + for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) { + E->get()->_owner = NULL; //bye, you are no longer owned cause I died } #ifdef DEBUG_ENABLED @@ -1014,48 +960,41 @@ GDScript::~GDScript() { #endif } - - - - ////////////////////////////// // INSTANCE // ////////////////////////////// - -bool GDInstance::set(const StringName& p_name, const Variant& p_value) { +bool GDInstance::set(const StringName &p_name, const Variant &p_value) { //member { - const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); + const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); if (E) { if (E->get().setter) { - const Variant *val=&p_value; + const Variant *val = &p_value; Variant::CallError err; - call(E->get().setter,&val,1,err); - if (err.error==Variant::CallError::CALL_OK) { + call(E->get().setter, &val, 1, err); + if (err.error == Variant::CallError::CALL_OK) { return true; //function exists, call was successful } - } - else + } else members[E->get().index] = p_value; return true; } } - GDScript *sptr=script.ptr(); - while(sptr) { - + GDScript *sptr = script.ptr(); + while (sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set); + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set); if (E) { - Variant name=p_name; - const Variant *args[2]={&name,&p_value}; + Variant name = p_name; + const Variant *args[2] = { &name, &p_value }; Variant::CallError err; - Variant ret = E->get()->call(this,(const Variant**)args,2,err); - if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool()) + Variant ret = E->get()->call(this, (const Variant **)args, 2, err); + if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool()) return true; } sptr = sptr->_base; @@ -1064,54 +1003,50 @@ bool GDInstance::set(const StringName& p_name, const Variant& p_value) { return false; } -bool GDInstance::get(const StringName& p_name, Variant &r_ret) const { +bool GDInstance::get(const StringName &p_name, Variant &r_ret) const { - - - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { { - const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); + const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name); if (E) { if (E->get().getter) { Variant::CallError err; - r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err); - if (err.error==Variant::CallError::CALL_OK) { + r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err); + if (err.error == Variant::CallError::CALL_OK) { return true; } } - r_ret=members[E->get().index]; + r_ret = members[E->get().index]; return true; //index found - } } { const GDScript *sl = sptr; - while(sl) { - const Map<StringName,Variant>::Element *E = sl->constants.find(p_name); + while (sl) { + const Map<StringName, Variant>::Element *E = sl->constants.find(p_name); if (E) { - r_ret=E->get(); + r_ret = E->get(); return true; //index found - } - sl=sl->_base; + sl = sl->_base; } } { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get); + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get); if (E) { - Variant name=p_name; - const Variant *args[1]={&name}; + Variant name = p_name; + const Variant *args[1] = { &name }; Variant::CallError err; - Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err); - if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) { - r_ret=ret; + Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err); + if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) { + r_ret = ret; return true; } } @@ -1120,94 +1055,86 @@ bool GDInstance::get(const StringName& p_name, Variant &r_ret) const { } return false; - } -Variant::Type GDInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const { +Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { - - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { if (sptr->member_info.has(p_name)) { if (r_is_valid) - *r_is_valid=true; + *r_is_valid = true; return sptr->member_info[p_name].type; } sptr = sptr->_base; } if (r_is_valid) - *r_is_valid=false; + *r_is_valid = false; return Variant::NIL; } void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { // exported members, not doen yet! - const GDScript *sptr=script.ptr(); + const GDScript *sptr = script.ptr(); List<PropertyInfo> props; - while(sptr) { - + while (sptr) { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list); + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list); if (E) { - Variant::CallError err; - Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),NULL,0,err); - if (err.error==Variant::CallError::CALL_OK) { + Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err); + if (err.error == Variant::CallError::CALL_OK) { - if (ret.get_type()!=Variant::ARRAY) { + if (ret.get_type() != Variant::ARRAY) { ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries."); ERR_FAIL(); } Array arr = ret; - for(int i=0;i<arr.size();i++) { + for (int i = 0; i < arr.size(); i++) { Dictionary d = arr[i]; ERR_CONTINUE(!d.has("name")); ERR_CONTINUE(!d.has("type")); PropertyInfo pinfo; - pinfo.type = Variant::Type( d["type"].operator int()); - ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX ); + pinfo.type = Variant::Type(d["type"].operator int()); + ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX); pinfo.name = d["name"]; - ERR_CONTINUE(pinfo.name==""); + ERR_CONTINUE(pinfo.name == ""); if (d.has("hint")) - pinfo.hint=PropertyHint(d["hint"].operator int()); + pinfo.hint = PropertyHint(d["hint"].operator int()); if (d.has("hint_string")) - pinfo.hint_string=d["hint_string"]; + pinfo.hint_string = d["hint_string"]; if (d.has("usage")) - pinfo.usage=d["usage"]; + pinfo.usage = d["usage"]; props.push_back(pinfo); - } - } } //instance a fake script for editing the values Vector<_GDScriptMemberSort> msort; - for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) { + for (Map<StringName, PropertyInfo>::Element *E = sptr->member_info.front(); E; E = E->next()) { _GDScriptMemberSort ms; ERR_CONTINUE(!sptr->member_indices.has(E->key())); - ms.index=sptr->member_indices[E->key()].index; - ms.name=E->key(); + ms.index = sptr->member_indices[E->key()].index; + ms.name = E->key(); msort.push_back(ms); - } msort.sort(); msort.invert(); - for(int i=0;i<msort.size();i++) { + for (int i = 0; i < msort.size(); i++) { props.push_front(sptr->member_info[msort[i].name]); - } #if 0 if (sptr->member_functions.has("_get_property_list")) { @@ -1256,7 +1183,7 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { //props.invert(); - for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) { + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { p_properties->push_back(E->get()); } @@ -1264,28 +1191,27 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const { void GDInstance::get_method_list(List<MethodInfo> *p_list) const { - const GDScript *sptr=script.ptr(); - while(sptr) { + const GDScript *sptr = script.ptr(); + while (sptr) { - for (Map<StringName,GDFunction*>::Element *E = sptr->member_functions.front();E;E=E->next()) { + for (Map<StringName, GDFunction *>::Element *E = sptr->member_functions.front(); E; E = E->next()) { MethodInfo mi; - mi.name=E->key(); - mi.flags|=METHOD_FLAG_FROM_SCRIPT; - for(int i=0;i<E->get()->get_argument_count();i++) - mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i))); + mi.name = E->key(); + mi.flags |= METHOD_FLAG_FROM_SCRIPT; + for (int i = 0; i < E->get()->get_argument_count(); i++) + mi.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i))); p_list->push_back(mi); } sptr = sptr->_base; } - } -bool GDInstance::has_method(const StringName& p_method) const { +bool GDInstance::has_method(const StringName &p_method) const { - const GDScript *sptr=script.ptr(); - while(sptr) { - const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + const GDScript *sptr = script.ptr(); + while (sptr) { + const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) return true; sptr = sptr->_base; @@ -1293,81 +1219,74 @@ bool GDInstance::has_method(const StringName& p_method) const { return false; } -Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { +Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { //printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str()); - GDScript *sptr=script.ptr(); - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + GDScript *sptr = script.ptr(); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - return E->get()->call(this,p_args,p_argcount,r_error); + return E->get()->call(this, p_args, p_argcount, r_error); } sptr = sptr->_base; } - r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; + r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } -void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) { - GDScript *sptr=script.ptr(); + GDScript *sptr = script.ptr(); Variant::CallError ce; - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - E->get()->call(this,p_args,p_argcount,ce); + E->get()->call(this, p_args, p_argcount, ce); } sptr = sptr->_base; } - } - -void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::_ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount) { if (sptr->_base) - _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount); + _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount); Variant::CallError ce; - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method); if (E) { - E->get()->call(this,p_args,p_argcount,ce); + E->get()->call(this, p_args, p_argcount, ce); } - } -void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { +void GDInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) { if (script.ptr()) { - _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount); + _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount); } } - - void GDInstance::notification(int p_notification) { //notification is not virutal, it gets called at ALL levels just like in C. - Variant value=p_notification; - const Variant *args[1]={&value }; + Variant value = p_notification; + const Variant *args[1] = { &value }; - GDScript *sptr=script.ptr(); - while(sptr) { - Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification); + GDScript *sptr = script.ptr(); + while (sptr) { + Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification); if (E) { Variant::CallError err; - E->get()->call(this,args,1,err); - if (err.error!=Variant::CallError::CALL_OK) { + E->get()->call(this, args, 1, err); + if (err.error != Variant::CallError::CALL_OK) { //print error about notification call - } } sptr = sptr->_base; } - } Ref<Script> GDInstance::get_script() const { @@ -1380,46 +1299,42 @@ ScriptLanguage *GDInstance::get_language() { return GDScriptLanguage::get_singleton(); } -GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName& p_method) const { +GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName &p_method) const { const GDScript *cscript = script.ptr(); - while(cscript) { - const Map<StringName,GDFunction*>::Element *E=cscript->member_functions.find(p_method); + while (cscript) { + const Map<StringName, GDFunction *>::Element *E = cscript->member_functions.find(p_method); if (E) { - if (E->get()->get_rpc_mode()!=RPC_MODE_DISABLED) { + if (E->get()->get_rpc_mode() != RPC_MODE_DISABLED) { return E->get()->get_rpc_mode(); } - } - cscript=cscript->_base; + cscript = cscript->_base; } return RPC_MODE_DISABLED; } -GDInstance::RPCMode GDInstance::get_rset_mode(const StringName& p_variable) const { +GDInstance::RPCMode GDInstance::get_rset_mode(const StringName &p_variable) const { const GDScript *cscript = script.ptr(); - while(cscript) { - const Map<StringName,GDScript::MemberInfo>::Element *E=cscript->member_indices.find(p_variable); + while (cscript) { + const Map<StringName, GDScript::MemberInfo>::Element *E = cscript->member_indices.find(p_variable); if (E) { if (E->get().rpc_mode) { return E->get().rpc_mode; } - } - cscript=cscript->_base; + cscript = cscript->_base; } return RPC_MODE_DISABLED; } - - void GDInstance::reload_members() { #ifdef DEBUG_ENABLED @@ -1430,44 +1345,42 @@ void GDInstance::reload_members() { new_members.resize(script->member_indices.size()); //pass the values to the new indices - for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) { if (member_indices_cache.has(E->key())) { Variant value = members[member_indices_cache[E->key()]]; - new_members[E->get().index]=value; + new_members[E->get().index] = value; } - } //apply - members=new_members; + members = new_members; //pass the values to the new indices member_indices_cache.clear(); - for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) { + for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) { - member_indices_cache[E->key()]=E->get().index; + member_indices_cache[E->key()] = E->get().index; } #endif } GDInstance::GDInstance() { - owner=NULL; - base_ref=false; + owner = NULL; + base_ref = false; } GDInstance::~GDInstance() { if (script.is_valid() && owner) { #ifndef NO_THREADS - GDScriptLanguage::singleton->lock->lock(); + GDScriptLanguage::singleton->lock->lock(); #endif - script->instances.erase(owner); + script->instances.erase(owner); #ifndef NO_THREADS - GDScriptLanguage::singleton->lock->unlock(); + GDScriptLanguage::singleton->lock->unlock(); #endif - } } @@ -1477,8 +1390,7 @@ GDInstance::~GDInstance() { /************* SCRIPT LANGUAGE **************/ /************* SCRIPT LANGUAGE **************/ -GDScriptLanguage *GDScriptLanguage::singleton=NULL; - +GDScriptLanguage *GDScriptLanguage::singleton = NULL; String GDScriptLanguage::get_name() const { @@ -1487,63 +1399,60 @@ String GDScriptLanguage::get_name() const { /* LANGUAGE FUNCTIONS */ -void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) { - +void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) { if (globals.has(p_name)) { //overwrite existing - global_array[globals[p_name]]=p_value; + global_array[globals[p_name]] = p_value; return; } - globals[p_name]=global_array.size(); + globals[p_name] = global_array.size(); global_array.push_back(p_value); - _global_array=global_array.ptr(); + _global_array = global_array.ptr(); } -void GDScriptLanguage::add_global_constant(const StringName& p_variable,const Variant& p_value) { +void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) { - _add_global(p_variable,p_value); + _add_global(p_variable, p_value); } - void GDScriptLanguage::init() { - //populate global constants - int gcc=GlobalConstants::get_global_constant_count(); - for(int i=0;i<gcc;i++) { + int gcc = GlobalConstants::get_global_constant_count(); + for (int i = 0; i < gcc; i++) { - _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)),GlobalConstants::get_global_constant_value(i)); + _add_global(StaticCString::create(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i)); } - _add_global(StaticCString::create("PI"),Math_PI); - _add_global(StaticCString::create("INF"),Math_INF); - _add_global(StaticCString::create("NAN"),Math_NAN); + _add_global(StaticCString::create("PI"), Math_PI); + _add_global(StaticCString::create("INF"), Math_INF); + _add_global(StaticCString::create("NAN"), Math_NAN); //populate native classes List<StringName> class_list; ClassDB::get_class_list(&class_list); - for(List<StringName>::Element *E=class_list.front();E;E=E->next()) { + for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) { StringName n = E->get(); String s = String(n); if (s.begins_with("_")) - n=s.substr(1,s.length()); + n = s.substr(1, s.length()); if (globals.has(n)) continue; - Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) ); - _add_global(n,nc); + Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get())); + _add_global(n, nc); } //populate singletons List<GlobalConfig::Singleton> singletons; GlobalConfig::get_singleton()->get_singletons(&singletons); - for(List<GlobalConfig::Singleton>::Element *E=singletons.front();E;E=E->next()) { + for (List<GlobalConfig::Singleton>::Element *E = singletons.front(); E; E = E->next()) { - _add_global(E->get().name,E->get().ptr); + _add_global(E->get().name, E->get().ptr); } } @@ -1555,14 +1464,12 @@ String GDScriptLanguage::get_extension() const { return "gd"; } -Error GDScriptLanguage::execute_file(const String& p_path) { +Error GDScriptLanguage::execute_file(const String &p_path) { // ?? return OK; } -void GDScriptLanguage::finish() { - - +void GDScriptLanguage::finish() { } void GDScriptLanguage::profiling_start() { @@ -1572,27 +1479,26 @@ void GDScriptLanguage::profiling_start() { lock->lock(); } - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - elem->self()->profile.call_count=0; - elem->self()->profile.self_time=0; - elem->self()->profile.total_time=0; - elem->self()->profile.frame_call_count=0; - elem->self()->profile.frame_self_time=0; - elem->self()->profile.frame_total_time=0; - elem->self()->profile.last_frame_call_count=0; - elem->self()->profile.last_frame_self_time=0; - elem->self()->profile.last_frame_total_time=0; - elem=elem->next(); + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + elem->self()->profile.call_count = 0; + elem->self()->profile.self_time = 0; + elem->self()->profile.total_time = 0; + elem->self()->profile.frame_call_count = 0; + elem->self()->profile.frame_self_time = 0; + elem->self()->profile.frame_total_time = 0; + elem->self()->profile.last_frame_call_count = 0; + elem->self()->profile.last_frame_self_time = 0; + elem->self()->profile.last_frame_total_time = 0; + elem = elem->next(); } - profiling=true; + profiling = true; if (lock) { lock->unlock(); } #endif - } void GDScriptLanguage::profiling_stop() { @@ -1602,7 +1508,7 @@ void GDScriptLanguage::profiling_stop() { lock->lock(); } - profiling=false; + profiling = false; if (lock) { lock->unlock(); } @@ -1610,95 +1516,83 @@ void GDScriptLanguage::profiling_stop() { #endif } -int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max) { +int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { - int current=0; + int current = 0; #ifdef DEBUG_ENABLED if (lock) { lock->lock(); } - - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - if (current>=p_info_max) + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + if (current >= p_info_max) break; - p_info_arr[current].call_count=elem->self()->profile.call_count; - p_info_arr[current].self_time=elem->self()->profile.self_time; - p_info_arr[current].total_time=elem->self()->profile.total_time; - p_info_arr[current].signature=elem->self()->profile.signature; - elem=elem->next(); + p_info_arr[current].call_count = elem->self()->profile.call_count; + p_info_arr[current].self_time = elem->self()->profile.self_time; + p_info_arr[current].total_time = elem->self()->profile.total_time; + p_info_arr[current].signature = elem->self()->profile.signature; + elem = elem->next(); current++; } - - if (lock) { lock->unlock(); } - #endif return current; - - } -int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max) { +int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { - int current=0; + int current = 0; #ifdef DEBUG_ENABLED if (lock) { lock->lock(); } - - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - if (current>=p_info_max) + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + if (current >= p_info_max) break; - if (elem->self()->profile.last_frame_call_count>0) { - p_info_arr[current].call_count=elem->self()->profile.last_frame_call_count; - p_info_arr[current].self_time=elem->self()->profile.last_frame_self_time; - p_info_arr[current].total_time=elem->self()->profile.last_frame_total_time; - p_info_arr[current].signature=elem->self()->profile.signature; + if (elem->self()->profile.last_frame_call_count > 0) { + p_info_arr[current].call_count = elem->self()->profile.last_frame_call_count; + p_info_arr[current].self_time = elem->self()->profile.last_frame_self_time; + p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time; + p_info_arr[current].signature = elem->self()->profile.signature; //print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count)); current++; } - elem=elem->next(); - + elem = elem->next(); } - if (lock) { lock->unlock(); } - #endif return current; - } - struct GDScriptDepSort { //must support sorting so inheritance works properly (parent must be reloaded first) - bool operator()(const Ref<GDScript> &A, const Ref<GDScript>& B) const { + bool operator()(const Ref<GDScript> &A, const Ref<GDScript> &B) const { - if (A==B) + if (A == B) return false; //shouldn't happen but.. - const GDScript *I=B->get_base().ptr(); - while(I) { - if (I==A.ptr()) { + const GDScript *I = B->get_base().ptr(); + while (I) { + if (I == A.ptr()) { // A is a base of B return true; } - I=I->get_base().ptr(); + I = I->get_base().ptr(); } return false; //not a base @@ -1707,8 +1601,6 @@ struct GDScriptDepSort { void GDScriptLanguage::reload_all_scripts() { - - #ifdef DEBUG_ENABLED print_line("RELOAD ALL SCRIPTS"); if (lock) { @@ -1717,13 +1609,13 @@ void GDScriptLanguage::reload_all_scripts() { List<Ref<GDScript> > scripts; - SelfList<GDScript> *elem=script_list.first(); - while(elem) { + SelfList<GDScript> *elem = script_list.first(); + while (elem) { if (elem->self()->get_path().is_resource_file()) { - print_line("FOUND: "+elem->self()->get_path()); + print_line("FOUND: " + elem->self()->get_path()); scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident } - elem=elem->next(); + elem = elem->next(); } if (lock) { @@ -1734,18 +1626,16 @@ void GDScriptLanguage::reload_all_scripts() { scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) { + for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) { - print_line("RELOADING: "+E->get()->get_path()); + print_line("RELOADING: " + E->get()->get_path()); E->get()->load_source_code(E->get()->get_path()); E->get()->reload(true); } #endif } - -void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload) { - +void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) { #ifdef DEBUG_ENABLED @@ -1755,13 +1645,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof List<Ref<GDScript> > scripts; - SelfList<GDScript> *elem=script_list.first(); - while(elem) { + SelfList<GDScript> *elem = script_list.first(); + while (elem) { if (elem->self()->get_path().is_resource_file()) { scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident } - elem=elem->next(); + elem = elem->next(); } if (lock) { @@ -1770,68 +1660,68 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof //when someone asks you why dynamically typed languages are easier to write.... - Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > > to_reload; + Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload; //as scripts are going to be reloaded, must proceed without locking here scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) { + for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) { - bool reload = E->get()==p_script || to_reload.has(E->get()->get_base()); + bool reload = E->get() == p_script || to_reload.has(E->get()->get_base()); if (!reload) continue; - to_reload.insert(E->get(),Map<ObjectID,List<Pair<StringName,Variant> > >()); + to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant> > >()); if (!p_soft_reload) { //save state and remove script from instances - Map<ObjectID,List<Pair<StringName,Variant> > >& map = to_reload[E->get()]; + Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()]; - while(E->get()->instances.front()) { + while (E->get()->instances.front()) { Object *obj = E->get()->instances.front()->get(); //save instance info - List<Pair<StringName,Variant> > state; + List<Pair<StringName, Variant> > state; if (obj->get_script_instance()) { obj->get_script_instance()->get_property_state(state); - map[obj->get_instance_ID()]=state; + map[obj->get_instance_ID()] = state; obj->set_script(RefPtr()); } } - //same thing for placeholders +//same thing for placeholders #ifdef TOOLS_ENABLED - while(E->get()->placeholders.size()) { + while (E->get()->placeholders.size()) { Object *obj = E->get()->placeholders.front()->get()->get_owner(); //save instance info - List<Pair<StringName,Variant> > state; + List<Pair<StringName, Variant> > state; if (obj->get_script_instance()) { obj->get_script_instance()->get_property_state(state); - map[obj->get_instance_ID()]=state; + map[obj->get_instance_ID()] = state; obj->set_script(RefPtr()); } } #endif - for(Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get()->pending_reload_state.front();F;F=F->next()) { - map[F->key()]=F->get(); //pending to reload, use this one instead + for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) { + map[F->key()] = F->get(); //pending to reload, use this one instead } } } - for(Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > >::Element *E=to_reload.front();E;E=E->next()) { + for (Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > >::Element *E = to_reload.front(); E; E = E->next()) { Ref<GDScript> scr = E->key(); scr->reload(p_soft_reload); //restore state if saved - for (Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get().front();F;F=F->next()) { + for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) { Object *obj = ObjectDB::get_instance(F->key()); if (!obj) @@ -1845,13 +1735,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof if (!obj->get_script_instance()) { //failed, save reload state for next time if not saved if (!scr->pending_reload_state.has(obj->get_instance_ID())) { - scr->pending_reload_state[obj->get_instance_ID()]=F->get(); + scr->pending_reload_state[obj->get_instance_ID()] = F->get(); } continue; } - for (List<Pair<StringName,Variant> >::Element *G=F->get().front();G;G=G->next()) { - obj->get_script_instance()->set(G->get().first,G->get().second); + for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) { + obj->get_script_instance()->set(G->get().first, G->get().second); } scr->pending_reload_state.erase(obj->get_instance_ID()); //as it reloaded, remove pending state @@ -1860,14 +1750,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof //if instance states were saved, set them! } - #endif } void GDScriptLanguage::frame() { //print_line("calls: "+itos(calls)); - calls=0; + calls = 0; #ifdef DEBUG_ENABLED if (profiling) { @@ -1875,18 +1764,17 @@ void GDScriptLanguage::frame() { lock->lock(); } - SelfList<GDFunction> *elem=function_list.first(); - while(elem) { - elem->self()->profile.last_frame_call_count=elem->self()->profile.frame_call_count; - elem->self()->profile.last_frame_self_time=elem->self()->profile.frame_self_time; - elem->self()->profile.last_frame_total_time=elem->self()->profile.frame_total_time; - elem->self()->profile.frame_call_count=0; - elem->self()->profile.frame_self_time=0; - elem->self()->profile.frame_total_time=0; - elem=elem->next(); + SelfList<GDFunction> *elem = function_list.first(); + while (elem) { + elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count; + elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time; + elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time; + elem->self()->profile.frame_call_count = 0; + elem->self()->profile.frame_self_time = 0; + elem->self()->profile.frame_total_time = 0; + elem = elem->next(); } - if (lock) { lock->unlock(); } @@ -1896,9 +1784,9 @@ void GDScriptLanguage::frame() { } /* EDITOR FUNCTIONS */ -void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { +void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { - static const char *_reserved_words[]={ + static const char *_reserved_words[] = { // operators "and", "in", @@ -1948,11 +1836,10 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { "sync", "master", "slave", - 0}; - - - const char **w=_reserved_words; + 0 + }; + const char **w = _reserved_words; while (*w) { @@ -1960,73 +1847,69 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { w++; } - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i))); } - } GDScriptLanguage::GDScriptLanguage() { - calls=0; + calls = 0; ERR_FAIL_COND(singleton); - singleton=this; + singleton = this; strings._init = StaticCString::create("_init"); strings._notification = StaticCString::create("_notification"); - strings._set= StaticCString::create("_set"); - strings._get= StaticCString::create("_get"); - strings._get_property_list= StaticCString::create("_get_property_list"); - strings._script_source=StaticCString::create("script/source"); - _debug_parse_err_line=-1; - _debug_parse_err_file=""; + strings._set = StaticCString::create("_set"); + strings._get = StaticCString::create("_get"); + strings._get_property_list = StaticCString::create("_get_property_list"); + strings._script_source = StaticCString::create("script/source"); + _debug_parse_err_line = -1; + _debug_parse_err_file = ""; #ifdef NO_THREADS - lock=NULL; + lock = NULL; #else lock = Mutex::create(); #endif - profiling=false; - script_frame_time=0; + profiling = false; + script_frame_time = 0; - _debug_call_stack_pos=0; - int dmcs=GLOBAL_DEF("debug/script/max_call_stack",1024); + _debug_call_stack_pos = 0; + int dmcs = GLOBAL_DEF("debug/script/max_call_stack", 1024); if (ScriptDebugger::get_singleton()) { //debugging enabled! _debug_max_call_stack = dmcs; - if (_debug_max_call_stack<1024) - _debug_max_call_stack=1024; - _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 ); + if (_debug_max_call_stack < 1024) + _debug_max_call_stack = 1024; + _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1); } else { - _debug_max_call_stack=0; - _call_stack=NULL; + _debug_max_call_stack = 0; + _call_stack = NULL; } - } - GDScriptLanguage::~GDScriptLanguage() { - if (lock) { memdelete(lock); - lock=NULL; + lock = NULL; } - if (_call_stack) { + if (_call_stack) { memdelete_arr(_call_stack); } - singleton=NULL; + singleton = NULL; } /*************** RESOURCE ***************/ -RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_original_path, Error *r_error) { +RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) - *r_error=ERR_FILE_CANT_OPEN; + *r_error = ERR_FILE_CANT_OPEN; - GDScript *script = memnew( GDScript ); + GDScript *script = memnew(GDScript); Ref<GDScript> scriptres(script); @@ -2036,18 +1919,17 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori script->set_path(p_original_path); Error err = script->load_byte_code(p_path); + if (err != OK) { - if (err!=OK) { - - ERR_FAIL_COND_V(err!=OK, RES()); + ERR_FAIL_COND_V(err != OK, RES()); } } else { Error err = script->load_source_code(p_path); - if (err!=OK) { + if (err != OK) { - ERR_FAIL_COND_V(err!=OK, RES()); + ERR_FAIL_COND_V(err != OK, RES()); } script->set_script_path(p_original_path); // script needs this. @@ -2057,7 +1939,7 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori script->reload(); } if (r_error) - *r_error=OK; + *r_error = OK; return scriptres; } @@ -2068,38 +1950,36 @@ void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_ext p_extensions->push_back("gde"); } -bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const { +bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const { - return (p_type=="Script" || p_type=="GDScript"); + return (p_type == "Script" || p_type == "GDScript"); } String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) const { String el = p_path.get_extension().to_lower(); - if (el=="gd" || el=="gdc" || el=="gde") + if (el == "gd" || el == "gdc" || el == "gde") return "GDScript"; return ""; } - -Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) { +Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Ref<GDScript> sqscr = p_resource; - ERR_FAIL_COND_V(sqscr.is_null(),ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER); String source = sqscr->get_source_code(); Error err; - FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err); - + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { - ERR_FAIL_COND_V(err,err); + ERR_FAIL_COND_V(err, err); } file->store_string(source); - if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) { + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { memdelete(file); return ERR_CANT_CREATE; } @@ -2107,20 +1987,19 @@ Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resour memdelete(file); if (ScriptServer::is_reload_scripts_on_save_enabled()) { - GDScriptLanguage::get_singleton()->reload_tool_script(p_resource,false); + GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false); } return OK; } -void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const { +void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { if (p_resource->cast_to<GDScript>()) { p_extensions->push_back("gd"); } - } -bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const { +bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const { - return p_resource->cast_to<GDScript>()!=NULL; + return p_resource->cast_to<GDScript>() != NULL; } diff --git a/modules/gdscript/gd_script.h b/modules/gdscript/gd_script.h index 4d3baa5bc0..d64cc9798d 100644 --- a/modules/gdscript/gd_script.h +++ b/modules/gdscript/gd_script.h @@ -29,50 +29,45 @@ #ifndef GD_SCRIPT_H #define GD_SCRIPT_H -#include "script_language.h" +#include "gd_function.h" #include "io/resource_loader.h" #include "io/resource_saver.h" -#include "gd_function.h" +#include "script_language.h" class GDNativeClass : public Reference { - GDCLASS(GDNativeClass,Reference); + GDCLASS(GDNativeClass, Reference); StringName name; -protected: - bool _get(const StringName& p_name,Variant &r_ret) const; +protected: + bool _get(const StringName &p_name, Variant &r_ret) const; static void _bind_methods(); public: - - _FORCE_INLINE_ const StringName& get_name() const { return name; } + _FORCE_INLINE_ const StringName &get_name() const { return name; } Variant _new(); Object *instance(); - GDNativeClass(const StringName& p_name); + GDNativeClass(const StringName &p_name); }; - class GDScript : public Script { - - GDCLASS(GDScript,Script); + GDCLASS(GDScript, Script); bool tool; bool valid; - struct MemberInfo { int index; StringName setter; StringName getter; ScriptInstance::RPCMode rpc_mode; - }; -friend class GDInstance; -friend class GDFunction; -friend class GDCompiler; -friend class GDFunctions; -friend class GDScriptLanguage; + friend class GDInstance; + friend class GDFunction; + friend class GDCompiler; + friend class GDFunctions; + friend class GDScriptLanguage; Variant _static_ref; //used for static call Ref<GDNativeClass> native; @@ -81,130 +76,125 @@ friend class GDScriptLanguage; GDScript *_owner; //for subclasses Set<StringName> members; //members are just indices to the instanced script. - Map<StringName,Variant> constants; - Map<StringName,GDFunction*> member_functions; - Map<StringName,MemberInfo> member_indices; //members are just indices to the instanced script. - Map<StringName,Ref<GDScript> > subclasses; - Map<StringName,Vector<StringName> > _signals; - + Map<StringName, Variant> constants; + Map<StringName, GDFunction *> member_functions; + Map<StringName, MemberInfo> member_indices; //members are just indices to the instanced script. + Map<StringName, Ref<GDScript> > subclasses; + Map<StringName, Vector<StringName> > _signals; #ifdef TOOLS_ENABLED - Map<StringName,int> member_lines; + Map<StringName, int> member_lines; - Map<StringName,Variant> member_default_values; + Map<StringName, Variant> member_default_values; List<PropertyInfo> members_cache; - Map<StringName,Variant> member_default_values_cache; + Map<StringName, Variant> member_default_values_cache; Ref<GDScript> base_cache; Set<ObjectID> inheriters_cache; bool source_changed_cache; - void _update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames); + void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames); #endif - Map<StringName,PropertyInfo> member_info; + Map<StringName, PropertyInfo> member_info; GDFunction *initializer; //direct pointer to _init , faster to locate int subclass_count; - Set<Object*> instances; + Set<Object *> instances; //exported members String source; String path; String name; SelfList<GDScript> script_list; + GDInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error); - GDInstance* _create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError &r_error); - - void _set_subclass_path(Ref<GDScript>& p_sc,const String& p_path); + void _set_subclass_path(Ref<GDScript> &p_sc, const String &p_path); #ifdef TOOLS_ENABLED - Set<PlaceHolderScriptInstance*> placeholders; + Set<PlaceHolderScriptInstance *> placeholders; //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder); #endif #ifdef DEBUG_ENABLED - Map<ObjectID,List<Pair<StringName,Variant> > > pending_reload_state; + Map<ObjectID, List<Pair<StringName, Variant> > > pending_reload_state; #endif bool _update_exports(); protected: - bool _get(const StringName& p_name,Variant &r_ret) const; - bool _set(const StringName& p_name, const Variant& p_value); + bool _get(const StringName &p_name, Variant &r_ret) const; + bool _set(const StringName &p_name, const Variant &p_value); void _get_property_list(List<PropertyInfo> *p_properties) const; - Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error); + Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); //void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); static void _bind_methods(); -public: +public: bool is_valid() const { return valid; } - const Map<StringName,Ref<GDScript> >& get_subclasses() const { return subclasses; } - const Map<StringName,Variant >& get_constants() const { return constants; } - const Set<StringName>& get_members() const { return members; } - const Map<StringName,GDFunction*>& get_member_functions() const { return member_functions; } - const Ref<GDNativeClass>& get_native() const { return native; } + const Map<StringName, Ref<GDScript> > &get_subclasses() const { return subclasses; } + const Map<StringName, Variant> &get_constants() const { return constants; } + const Set<StringName> &get_members() const { return members; } + const Map<StringName, GDFunction *> &get_member_functions() const { return member_functions; } + const Ref<GDNativeClass> &get_native() const { return native; } - virtual bool has_script_signal(const StringName& p_signal) const; + virtual bool has_script_signal(const StringName &p_signal) const; virtual void get_script_signal_list(List<MethodInfo> *r_signals) const; - bool is_tool() const { return tool; } Ref<GDScript> get_base() const; - const Map<StringName,MemberInfo>& debug_get_member_indices() const { return member_indices; } - const Map<StringName,GDFunction*>& debug_get_member_functions() const; //this is debug only + const Map<StringName, MemberInfo> &debug_get_member_indices() const { return member_indices; } + const Map<StringName, GDFunction *> &debug_get_member_functions() const; //this is debug only StringName debug_get_member_by_index(int p_idx) const; - Variant _new(const Variant** p_args,int p_argcount,Variant::CallError& r_error); + Variant _new(const Variant **p_args, int p_argcount, Variant::CallError &r_error); virtual bool can_instance() const; virtual Ref<Script> get_base_script() const; virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so - virtual ScriptInstance* instance_create(Object *p_this); + virtual ScriptInstance *instance_create(Object *p_this); virtual bool instance_has(const Object *p_this) const; virtual bool has_source_code() const; virtual String get_source_code() const; - virtual void set_source_code(const String& p_code); + virtual void set_source_code(const String &p_code); virtual void update_exports(); - virtual Error reload(bool p_keep_state=false); + virtual Error reload(bool p_keep_state = false); virtual String get_node_type() const; - void set_script_path(const String& p_path) { path=p_path; } //because subclasses need a path too... - Error load_source_code(const String& p_path); - Error load_byte_code(const String& p_path); + void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too... + Error load_source_code(const String &p_path); + Error load_byte_code(const String &p_path); Vector<uint8_t> get_as_byte_code() const; - bool get_property_default_value(const StringName& p_property,Variant& r_value) const; + bool get_property_default_value(const StringName &p_property, Variant &r_value) const; virtual void get_script_method_list(List<MethodInfo> *p_list) const; - virtual bool has_method(const StringName& p_method) const; - virtual MethodInfo get_method_info(const StringName& p_method) const; + virtual bool has_method(const StringName &p_method) const; + virtual MethodInfo get_method_info(const StringName &p_method) const; virtual void get_script_property_list(List<PropertyInfo> *p_list) const; - virtual ScriptLanguage *get_language() const; - virtual int get_member_line(const StringName& p_member) const { + virtual int get_member_line(const StringName &p_member) const { #ifdef TOOLS_ENABLED if (member_lines.has(p_member)) return member_lines[p_member]; else #endif return -1; - } GDScript(); @@ -212,37 +202,34 @@ public: }; class GDInstance : public ScriptInstance { -friend class GDScript; -friend class GDFunction; -friend class GDFunctions; -friend class GDCompiler; + friend class GDScript; + friend class GDFunction; + friend class GDFunctions; + friend class GDCompiler; Object *owner; Ref<GDScript> script; #ifdef DEBUG_ENABLED - Map<StringName,int> member_indices_cache; //used only for hot script reloading + Map<StringName, int> member_indices_cache; //used only for hot script reloading #endif Vector<Variant> members; bool base_ref; - - void _ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount); + void _ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount); public: + _FORCE_INLINE_ Object *get_owner() { return owner; } - _FORCE_INLINE_ Object* get_owner() { return owner; } - - virtual bool set(const StringName& p_name, const Variant& p_value); - virtual bool get(const StringName& p_name, Variant &r_ret) const; + virtual bool set(const StringName &p_name, const Variant &p_value); + virtual bool get(const StringName &p_name, Variant &r_ret) const; virtual void get_property_list(List<PropertyInfo> *p_properties) const; - virtual Variant::Type get_property_type(const StringName& p_name,bool *r_is_valid=NULL) const; - + virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const; virtual void get_method_list(List<MethodInfo> *p_list) const; - virtual bool has_method(const StringName& p_method) const; - virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error); - virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); - virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount); + virtual bool has_method(const StringName &p_method) const; + virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); + virtual void call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount); + virtual void call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount); Variant debug_get_member_by_index(int p_idx) const { return members[p_idx]; } @@ -252,27 +239,24 @@ public: virtual ScriptLanguage *get_language(); - void set_path(const String& p_path); + void set_path(const String &p_path); void reload_members(); - virtual RPCMode get_rpc_mode(const StringName& p_method) const; - virtual RPCMode get_rset_mode(const StringName& p_variable) const; - + virtual RPCMode get_rpc_mode(const StringName &p_method) const; + virtual RPCMode get_rset_mode(const StringName &p_variable) const; GDInstance(); ~GDInstance(); - }; class GDScriptLanguage : public ScriptLanguage { static GDScriptLanguage *singleton; - Variant* _global_array; + Variant *_global_array; Vector<Variant> global_array; - Map<StringName,int> globals; - + Map<StringName, int> globals; struct CallLevel { @@ -281,10 +265,8 @@ class GDScriptLanguage : public ScriptLanguage { GDInstance *instance; int *ip; int *line; - }; - int _debug_parse_err_line; String _debug_parse_err_file; String _debug_error; @@ -292,65 +274,61 @@ class GDScriptLanguage : public ScriptLanguage { int _debug_max_call_stack; CallLevel *_call_stack; - void _add_global(const StringName& p_name,const Variant& p_value); + void _add_global(const StringName &p_name, const Variant &p_value); -friend class GDInstance; + friend class GDInstance; Mutex *lock; - - - -friend class GDScript; + friend class GDScript; SelfList<GDScript>::List script_list; -friend class GDFunction; + friend class GDFunction; SelfList<GDFunction>::List function_list; bool profiling; uint64_t script_frame_time; -public: - +public: int calls; - bool debug_break(const String& p_error,bool p_allow_continue=true); - bool debug_break_parse(const String& p_file, int p_line,const String& p_error); + bool debug_break(const String &p_error, bool p_allow_continue = true); + bool debug_break_parse(const String &p_file, int p_line, const String &p_error); - _FORCE_INLINE_ void enter_function(GDInstance *p_instance,GDFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) { + _FORCE_INLINE_ void enter_function(GDInstance *p_instance, GDFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) { - if (Thread::get_main_ID()!=Thread::get_caller_ID()) + if (Thread::get_main_ID() != Thread::get_caller_ID()) return; //no support for other threads than main for now - if (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0) - ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() +1 ); + if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0) + ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() + 1); if (_debug_call_stack_pos >= _debug_max_call_stack) { //stack overflow - _debug_error="Stack Overflow (Stack Size: "+itos(_debug_max_call_stack)+")"; + _debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")"; ScriptDebugger::get_singleton()->debug(this); return; } - _call_stack[_debug_call_stack_pos].stack=p_stack; - _call_stack[_debug_call_stack_pos].instance=p_instance; - _call_stack[_debug_call_stack_pos].function=p_function; - _call_stack[_debug_call_stack_pos].ip=p_ip; - _call_stack[_debug_call_stack_pos].line=p_line; + _call_stack[_debug_call_stack_pos].stack = p_stack; + _call_stack[_debug_call_stack_pos].instance = p_instance; + _call_stack[_debug_call_stack_pos].function = p_function; + _call_stack[_debug_call_stack_pos].ip = p_ip; + _call_stack[_debug_call_stack_pos].line = p_line; _debug_call_stack_pos++; } _FORCE_INLINE_ void exit_function() { - if (Thread::get_main_ID()!=Thread::get_caller_ID()) + if (Thread::get_main_ID() != Thread::get_caller_ID()) return; //no support for other threads than main for now - if (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0) - ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() -1 ); + if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0) + ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() - 1); - if (_debug_call_stack_pos==0) { + if (_debug_call_stack_pos == 0) { - _debug_error="Stack Underflow (Engine Bug)"; + _debug_error = "Stack Underflow (Engine Bug)"; ScriptDebugger::get_singleton()->debug(this); return; } @@ -358,16 +336,15 @@ public: _debug_call_stack_pos--; } - virtual Vector<StackInfo> debug_get_current_stack_info() { - if (Thread::get_main_ID()!=Thread::get_caller_ID()) + if (Thread::get_main_ID() != Thread::get_caller_ID()) return Vector<StackInfo>(); Vector<StackInfo> csi; csi.resize(_debug_call_stack_pos); - for(int i=0;i<_debug_call_stack_pos;i++) { - csi[_debug_call_stack_pos-i-1].line=_call_stack[i].line?*_call_stack[i].line:0; - csi[_debug_call_stack_pos-i-1].script=Ref<GDScript>(_call_stack[i].function->get_script()); + for (int i = 0; i < _debug_call_stack_pos; i++) { + csi[_debug_call_stack_pos - i - 1].line = _call_stack[i].line ? *_call_stack[i].line : 0; + csi[_debug_call_stack_pos - i - 1].script = Ref<GDScript>(_call_stack[i].function->get_script()); } return csi; } @@ -383,10 +360,9 @@ public: } strings; - _FORCE_INLINE_ int get_global_array_size() const { return global_array.size(); } - _FORCE_INLINE_ Variant* get_global_array() { return _global_array; } - _FORCE_INLINE_ const Map<StringName,int>& get_global_map() { return globals; } + _FORCE_INLINE_ Variant *get_global_array() { return _global_array; } + _FORCE_INLINE_ const Map<StringName, int> &get_global_map() { return globals; } _FORCE_INLINE_ static GDScriptLanguage *get_singleton() { return singleton; } @@ -396,26 +372,25 @@ public: virtual void init(); virtual String get_type() const; virtual String get_extension() const; - virtual Error execute_file(const String& p_path) ; + virtual Error execute_file(const String &p_path); virtual void finish(); /* EDITOR FUNCTIONS */ virtual void get_reserved_words(List<String> *p_words) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; - virtual Ref<Script> get_template(const String& p_class_name, const String& p_base_class_name) const; - virtual bool validate(const String& p_script,int &r_line_error,int &r_col_error,String& r_test_error, const String& p_path="",List<String> *r_functions=NULL) const; + virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; - virtual int find_function(const String& p_function,const String& p_code) const; - virtual String make_function(const String& p_class,const String& p_name,const PoolStringArray& p_args) const; - virtual Error complete_code(const String& p_code, const String& p_base_path, Object*p_owner,List<String>* r_options,String& r_call_hint); + virtual int find_function(const String &p_function, const String &p_code) const; + virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; + virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint); #ifdef TOOLS_ENABLED - virtual Error lookup_code(const String& p_code, const String& p_symbol, const String& p_base_path, Object*p_owner, LookupResult& r_result); + virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result); #endif - virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const; - virtual void add_global_constant(const StringName& p_variable,const Variant& p_value); - + virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; + virtual void add_global_constant(const StringName &p_variable, const Variant &p_value); /* DEBUGGER FUNCTIONS */ @@ -424,24 +399,24 @@ public: virtual int debug_get_stack_level_line(int p_level) const; virtual String debug_get_stack_level_function(int p_level) const; virtual String debug_get_stack_level_source(int p_level) const; - virtual void debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1); - virtual void debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1); - virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1); - virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1); + virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1); virtual void reload_all_scripts(); - virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload); + virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload); virtual void frame(); virtual void get_public_functions(List<MethodInfo> *p_functions) const; - virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const; + virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const; virtual void profiling_start(); virtual void profiling_stop(); - virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max); - virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max); + virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max); + virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max); /* LOADER FUNCTIONS */ @@ -451,24 +426,19 @@ public: ~GDScriptLanguage(); }; - class ResourceFormatLoaderGDScript : public ResourceFormatLoader { public: - - virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String& p_type) const; + virtual bool handles_type(const String &p_type) const; virtual String get_resource_type(const String &p_path) const; - }; class ResourceFormatSaverGDScript : public ResourceFormatSaver { public: - - virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0); - virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const; - virtual bool recognize(const RES& p_resource) const; - + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; + virtual bool recognize(const RES &p_resource) const; }; #endif // GD_SCRIPT_H diff --git a/modules/gdscript/gd_tokenizer.cpp b/modules/gdscript/gd_tokenizer.cpp index 54b9624e8e..981924191f 100644 --- a/modules/gdscript/gd_tokenizer.cpp +++ b/modules/gdscript/gd_tokenizer.cpp @@ -27,212 +27,205 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "gd_tokenizer.h" -#include "print_string.h" #include "gd_functions.h" #include "io/marshalls.h" #include "map.h" +#include "print_string.h" -const char* GDTokenizer::token_names[TK_MAX]={ -"Empty", -"Identifier", -"Constant", -"Self", -"Built-In Type", -"Built-In Func", -"In", -"'=='", -"'!='", -"'<'", -"'<='", -"'>'", -"'>='", -"'and'", -"'or'", -"'not'", -"'+'", -"'-'", -"'*'", -"'/'", -"'%'", -"'<<'", -"'>>'", -"'='", -"'+='", -"'-='", -"'*='", -"'/='", -"'%='", -"'<<='", -"'>>='", -"'&='", -"'|='", -"'^='", -"'&'", -"'|'", -"'^'", -"'~'", -//"Plus Plus", -//"Minus Minus", -"if", -"elif", -"else", -"for", -"do", -"while", -"switch (reserved)", -"case (reserved)", -"break", -"continue", -"pass", -"return", -"match", -"func", -"class", -"extends", -"onready", -"tool", -"static", -"export", -"setget", -"const", -"var", -"enum", -"preload", -"assert", -"yield", -"signal", -"breakpoint", -"rpc", -"sync", -"master", -"slave", -"'['", -"']'", -"'{'", -"'}'", -"'('", -"')'", -"','", -"';'", -"'.'", -"'?'", -"':'", -"'\\n'", -"PI", -"_", -"INF", -"NAN", -"Error", -"EOF", -"Cursor"}; +const char *GDTokenizer::token_names[TK_MAX] = { + "Empty", + "Identifier", + "Constant", + "Self", + "Built-In Type", + "Built-In Func", + "In", + "'=='", + "'!='", + "'<'", + "'<='", + "'>'", + "'>='", + "'and'", + "'or'", + "'not'", + "'+'", + "'-'", + "'*'", + "'/'", + "'%'", + "'<<'", + "'>>'", + "'='", + "'+='", + "'-='", + "'*='", + "'/='", + "'%='", + "'<<='", + "'>>='", + "'&='", + "'|='", + "'^='", + "'&'", + "'|'", + "'^'", + "'~'", + //"Plus Plus", + //"Minus Minus", + "if", + "elif", + "else", + "for", + "do", + "while", + "switch (reserved)", + "case (reserved)", + "break", + "continue", + "pass", + "return", + "match", + "func", + "class", + "extends", + "onready", + "tool", + "static", + "export", + "setget", + "const", + "var", + "enum", + "preload", + "assert", + "yield", + "signal", + "breakpoint", + "rpc", + "sync", + "master", + "slave", + "'['", + "']'", + "'{'", + "'}'", + "'('", + "')'", + "','", + "';'", + "'.'", + "'?'", + "':'", + "'\\n'", + "PI", + "_", + "INF", + "NAN", + "Error", + "EOF", + "Cursor" +}; const char *GDTokenizer::get_token_name(Token p_token) { - ERR_FAIL_INDEX_V(p_token,TK_MAX,"<error>"); + ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>"); return token_names[p_token]; } static bool _is_text_char(CharType c) { - return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_'; + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; } static bool _is_number(CharType c) { - return (c>='0' && c<='9'); + return (c >= '0' && c <= '9'); } static bool _is_hex(CharType c) { - return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'); + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } -void GDTokenizerText::_make_token(Token p_type) { +void GDTokenizerText::_make_token(Token p_type) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=p_type; - tk.line=line; - tk.col=column; + tk.type = p_type; + tk.line = line; + tk.col = column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_identifier(const StringName& p_identifier) { +void GDTokenizerText::_make_identifier(const StringName &p_identifier) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=TK_IDENTIFIER; - tk.identifier=p_identifier; - tk.line=line; - tk.col=column; - - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_IDENTIFIER; + tk.identifier = p_identifier; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) { - - TokenData &tk=tk_rb[tk_rb_pos]; +void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) { - tk.type=TK_BUILT_IN_FUNC; - tk.func=p_func; - tk.line=line; - tk.col=column; + TokenData &tk = tk_rb[tk_rb_pos]; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_BUILT_IN_FUNC; + tk.func = p_func; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_constant(const Variant& p_constant) { +void GDTokenizerText::_make_constant(const Variant &p_constant) { - TokenData &tk=tk_rb[tk_rb_pos]; + TokenData &tk = tk_rb[tk_rb_pos]; - tk.type=TK_CONSTANT; - tk.constant=p_constant; - tk.line=line; - tk.col=column; - - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_CONSTANT; + tk.constant = p_constant; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } -void GDTokenizerText::_make_type(const Variant::Type& p_type) { - - - TokenData &tk=tk_rb[tk_rb_pos]; +void GDTokenizerText::_make_type(const Variant::Type &p_type) { - tk.type=TK_BUILT_IN_TYPE; - tk.vtype=p_type; - tk.line=line; - tk.col=column; + TokenData &tk = tk_rb[tk_rb_pos]; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + tk.type = TK_BUILT_IN_TYPE; + tk.vtype = p_type; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } +void GDTokenizerText::_make_error(const String &p_error) { -void GDTokenizerText::_make_error(const String& p_error) { - - error_flag=true; - last_error=p_error; - - TokenData &tk=tk_rb[tk_rb_pos]; - tk.type=TK_ERROR; - tk.constant=p_error; - tk.line=line; - tk.col=column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + error_flag = true; + last_error = p_error; + TokenData &tk = tk_rb[tk_rb_pos]; + tk.type = TK_ERROR; + tk.constant = p_error; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } - void GDTokenizerText::_make_newline(int p_spaces) { - TokenData &tk=tk_rb[tk_rb_pos]; - tk.type=TK_NEWLINE; - tk.constant=p_spaces; - tk.line=line; - tk.col=column; - tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE; + TokenData &tk = tk_rb[tk_rb_pos]; + tk.type = TK_NEWLINE; + tk.constant = p_spaces; + tk.line = line; + tk.col = column; + tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE; } void GDTokenizerText::_advance() { @@ -243,29 +236,32 @@ void GDTokenizerText::_advance() { return; } - if (code_pos>=len) { + if (code_pos >= len) { _make_token(TK_EOF); return; } -#define GETCHAR(m_ofs) ((m_ofs+code_pos)>=len?0:_code[m_ofs+code_pos]) -#define INCPOS(m_amount) { code_pos+=m_amount; column+=m_amount; } +#define GETCHAR(m_ofs) ((m_ofs + code_pos) >= len ? 0 : _code[m_ofs + code_pos]) +#define INCPOS(m_amount) \ + { \ + code_pos += m_amount; \ + column += m_amount; \ + } while (true) { + bool is_node_path = false; + StringMode string_mode = STRING_DOUBLE_QUOTE; - bool is_node_path = false; - StringMode string_mode=STRING_DOUBLE_QUOTE; - - switch(GETCHAR(0)) { + switch (GETCHAR(0)) { case 0: _make_token(TK_EOF); break; case '\\': INCPOS(1); - if (GETCHAR(0)=='\r') { + if (GETCHAR(0) == '\r') { INCPOS(1); } - if (GETCHAR(0)!='\n') { + if (GETCHAR(0) != '\n') { _make_error("Expected newline after '\\'."); return; } @@ -273,7 +269,7 @@ void GDTokenizerText::_advance() { INCPOS(1); line++; - while(GETCHAR(0)==' ' || GETCHAR(0)=='\t') { + while (GETCHAR(0) == ' ' || GETCHAR(0) == '\t') { INCPOS(1); } @@ -286,9 +282,9 @@ void GDTokenizerText::_advance() { case '\n': { line++; INCPOS(1); - column=1; - int i=0; - while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') { + column = 1; + int i = 0; + while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { i++; } @@ -298,19 +294,19 @@ void GDTokenizerText::_advance() { #if 1 //py style tokenizer case '#': { // line comment skip - while(GETCHAR(0)!='\n') { + while (GETCHAR(0) != '\n') { code_pos++; - if (GETCHAR(0)==0) { //end of file + if (GETCHAR(0) == 0) { //end of file //_make_error("Unterminated Comment"); _make_token(TK_EOF); return; } } INCPOS(1); - column=1; + column = 1; line++; - int i=0; - while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') { + int i = 0; + while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') { i++; } _make_newline(i); @@ -320,7 +316,7 @@ void GDTokenizerText::_advance() { #endif case '/': { - switch(GETCHAR(1)) { + switch (GETCHAR(1)) { #if 0 // c style tokenizer case '*': { // block comment int pos = code_pos+2; @@ -376,11 +372,10 @@ void GDTokenizerText::_advance() { } break; default: _make_token(TK_OP_DIV); - } } break; case '=': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_EQUAL); INCPOS(1); @@ -389,12 +384,12 @@ void GDTokenizerText::_advance() { } break; case '<': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_LESS_EQUAL); INCPOS(1); - } else if (GETCHAR(1)=='<') { - if (GETCHAR(2)=='=') { + } else if (GETCHAR(1) == '<') { + if (GETCHAR(2) == '=') { _make_token(TK_OP_ASSIGN_SHIFT_LEFT); INCPOS(1); } else { @@ -406,11 +401,11 @@ void GDTokenizerText::_advance() { } break; case '>': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_GREATER_EQUAL); INCPOS(1); - } else if (GETCHAR(1)=='>') { - if (GETCHAR(2)=='=') { + } else if (GETCHAR(1) == '>') { + if (GETCHAR(2) == '=') { _make_token(TK_OP_ASSIGN_SHIFT_RIGHT); INCPOS(1); @@ -424,7 +419,7 @@ void GDTokenizerText::_advance() { } break; case '!': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_NOT_EQUAL); INCPOS(1); } else { @@ -468,7 +463,7 @@ void GDTokenizerText::_advance() { _make_token(TK_DOLLAR); //for the get_node() shortener break; case '^': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_XOR); INCPOS(1); } else { @@ -480,11 +475,11 @@ void GDTokenizerText::_advance() { _make_token(TK_OP_BIT_INVERT); break; case '&': { - if (GETCHAR(1)=='&') { + if (GETCHAR(1) == '&') { _make_token(TK_OP_AND); INCPOS(1); - } else if (GETCHAR(1)=='=') { + } else if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_AND); INCPOS(1); } else { @@ -492,11 +487,11 @@ void GDTokenizerText::_advance() { } } break; case '|': { - if (GETCHAR(1)=='|') { + if (GETCHAR(1) == '|') { _make_token(TK_OP_OR); INCPOS(1); - } else if (GETCHAR(1)=='=') { + } else if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_BIT_OR); INCPOS(1); } else { @@ -505,7 +500,7 @@ void GDTokenizerText::_advance() { } break; case '*': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_MUL); INCPOS(1); } else { @@ -514,10 +509,10 @@ void GDTokenizerText::_advance() { } break; case '+': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_ADD); INCPOS(1); - /* + /* } else if (GETCHAR(1)=='+') { _make_token(TK_OP_PLUS_PLUS); INCPOS(1); @@ -529,10 +524,10 @@ void GDTokenizerText::_advance() { } break; case '-': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_SUB); INCPOS(1); - /* + /* } else if (GETCHAR(1)=='-') { _make_token(TK_OP_MINUS_MINUS); INCPOS(1); @@ -543,7 +538,7 @@ void GDTokenizerText::_advance() { } break; case '%': { - if (GETCHAR(1)=='=') { + if (GETCHAR(1) == '=') { _make_token(TK_OP_ASSIGN_MOD); INCPOS(1); } else { @@ -551,106 +546,103 @@ void GDTokenizerText::_advance() { } } break; case '@': - if( CharType(GETCHAR(1))!='"' && CharType(GETCHAR(1))!='\'' ) { + if (CharType(GETCHAR(1)) != '"' && CharType(GETCHAR(1)) != '\'') { _make_error("Unexpected '@'"); return; } INCPOS(1); - is_node_path=true; + is_node_path = true; case '\'': case '"': { - if (GETCHAR(0)=='\'') - string_mode=STRING_SINGLE_QUOTE; - - - int i=1; - if (string_mode==STRING_DOUBLE_QUOTE && GETCHAR(i)=='"' && GETCHAR(i+1)=='"') { - i+=2; - string_mode=STRING_MULTILINE; + if (GETCHAR(0) == '\'') + string_mode = STRING_SINGLE_QUOTE; + int i = 1; + if (string_mode == STRING_DOUBLE_QUOTE && GETCHAR(i) == '"' && GETCHAR(i + 1) == '"') { + i += 2; + string_mode = STRING_MULTILINE; } - String str; - while(true) { - if (CharType(GETCHAR(i))==0) { + while (true) { + if (CharType(GETCHAR(i)) == 0) { _make_error("Unterminated String"); return; - } else if( string_mode==STRING_DOUBLE_QUOTE && CharType(GETCHAR(i))=='"' ) { + } else if (string_mode == STRING_DOUBLE_QUOTE && CharType(GETCHAR(i)) == '"') { break; - } else if( string_mode==STRING_SINGLE_QUOTE && CharType(GETCHAR(i))=='\'' ) { + } else if (string_mode == STRING_SINGLE_QUOTE && CharType(GETCHAR(i)) == '\'') { break; - } else if( string_mode==STRING_MULTILINE && CharType(GETCHAR(i))=='\"' && CharType(GETCHAR(i+1))=='\"' && CharType(GETCHAR(i+2))=='\"') { - i+=2; + } else if (string_mode == STRING_MULTILINE && CharType(GETCHAR(i)) == '\"' && CharType(GETCHAR(i + 1)) == '\"' && CharType(GETCHAR(i + 2)) == '\"') { + i += 2; break; - } else if( string_mode!=STRING_MULTILINE && CharType(GETCHAR(i))=='\n') { + } else if (string_mode != STRING_MULTILINE && CharType(GETCHAR(i)) == '\n') { _make_error("Unexpected EOL at String."); return; - } else if( CharType(GETCHAR(i))==0xFFFF) { + } else if (CharType(GETCHAR(i)) == 0xFFFF) { //string ends here, next will be TK i--; break; - } else if (CharType(GETCHAR(i))=='\\') { + } else if (CharType(GETCHAR(i)) == '\\') { //escaped characters... i++; CharType next = GETCHAR(i); - if (next==0) { + if (next == 0) { _make_error("Unterminated String"); return; } - CharType res=0; - - switch(next) { - - case 'a': res=7; break; - case 'b': res=8; break; - case 't': res=9; break; - case 'n': res=10; break; - case 'v': res=11; break; - case 'f': res=12; break; - case 'r': res=13; break; - case '\'': res='\''; break; - case '\"': res='\"'; break; - case '\\': res='\\'; break; - case '/': res='/'; break; //wtf + CharType res = 0; + + switch (next) { + + case 'a': res = 7; break; + case 'b': res = 8; break; + case 't': res = 9; break; + case 'n': res = 10; break; + case 'v': res = 11; break; + case 'f': res = 12; break; + case 'r': res = 13; break; + case '\'': res = '\''; break; + case '\"': res = '\"'; break; + case '\\': res = '\\'; break; + case '/': + res = '/'; + break; //wtf case 'u': { //hexnumbarh - oct is deprecated - i+=1; - for(int j=0;j<4;j++) { - CharType c = GETCHAR(i+j); - if (c==0) { + i += 1; + for (int j = 0; j < 4; j++) { + CharType c = GETCHAR(i + j); + if (c == 0) { _make_error("Unterminated String"); return; } - if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) { _make_error("Malformed hex constant in string"); return; } CharType v; - if (c>='0' && c<='9') { - v=c-'0'; - } else if (c>='a' && c<='f') { - v=c-'a'; - v+=10; - } else if (c>='A' && c<='F') { - v=c-'A'; - v+=10; + if (c >= '0' && c <= '9') { + v = c - '0'; + } else if (c >= 'a' && c <= 'f') { + v = c - 'a'; + v += 10; + } else if (c >= 'A' && c <= 'F') { + v = c - 'A'; + v += 10; } else { ERR_PRINT("BUG"); - v=0; + v = 0; } - res<<=4; - res|=v; - - + res <<= 4; + res |= v; } - i+=3; + i += 3; } break; default: { @@ -660,15 +652,15 @@ void GDTokenizerText::_advance() { } break; } - str+=res; + str += res; } else { - if (CharType(GETCHAR(i))=='\n') { + if (CharType(GETCHAR(i)) == '\n') { line++; - column=1; + column = 1; } - str+=CharType(GETCHAR(i)); + str += CharType(GETCHAR(i)); } i++; } @@ -686,54 +678,54 @@ void GDTokenizerText::_advance() { } break; default: { - if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) { + if (_is_number(GETCHAR(0)) || (GETCHAR(0) == '.' && _is_number(GETCHAR(1)))) { // parse number - bool period_found=false; - bool exponent_found=false; - bool hexa_found=false; - bool sign_found=false; + bool period_found = false; + bool exponent_found = false; + bool hexa_found = false; + bool sign_found = false; String str; - int i=0; + int i = 0; - while(true) { - if (GETCHAR(i)=='.') { + while (true) { + if (GETCHAR(i) == '.') { if (period_found || exponent_found) { _make_error("Invalid numeric constant at '.'"); return; } - period_found=true; - } else if (GETCHAR(i)=='x') { - if (hexa_found || str.length()!=1 || !( (i==1 && str[0]=='0') || (i==2 && str[1]=='0' && str[0]=='-') ) ) { + period_found = true; + } else if (GETCHAR(i) == 'x') { + if (hexa_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) { _make_error("Invalid numeric constant at 'x'"); return; } - hexa_found=true; - } else if (!hexa_found && GETCHAR(i)=='e') { + hexa_found = true; + } else if (!hexa_found && GETCHAR(i) == 'e') { if (hexa_found || exponent_found) { _make_error("Invalid numeric constant at 'e'"); return; } - exponent_found=true; + exponent_found = true; } else if (_is_number(GETCHAR(i))) { //all ok } else if (hexa_found && _is_hex(GETCHAR(i))) { - } else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) { + } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) { if (sign_found) { _make_error("Invalid numeric constant at '-'"); return; } - sign_found=true; + sign_found = true; } else break; - str+=CharType(GETCHAR(i)); + str += CharType(GETCHAR(i)); i++; } - if (!( _is_number(str[str.length()-1]) || (hexa_found && _is_hex(str[str.length()-1])))) { - _make_error("Invalid numeric constant: "+str); + if (!(_is_number(str[str.length() - 1]) || (hexa_found && _is_hex(str[str.length() - 1])))) { + _make_error("Invalid numeric constant: " + str); return; } @@ -748,13 +740,12 @@ void GDTokenizerText::_advance() { } else { int64_t val = str.to_int64(); _make_constant(val); - } return; } - if (GETCHAR(0)=='.') { + if (GETCHAR(0) == '.') { //parse period _make_token(TK_PERIOD); break; @@ -763,74 +754,76 @@ void GDTokenizerText::_advance() { if (_is_text_char(GETCHAR(0))) { // parse identifier String str; - str+=CharType(GETCHAR(0)); + str += CharType(GETCHAR(0)); - int i=1; - while(_is_text_char(GETCHAR(i))) { - str+=CharType(GETCHAR(i)); + int i = 1; + while (_is_text_char(GETCHAR(i))) { + str += CharType(GETCHAR(i)); i++; } - bool identifier=false; + bool identifier = false; - if (str=="null") { + if (str == "null") { _make_constant(Variant()); - } else if (str=="true") { + } else if (str == "true") { _make_constant(true); - } else if (str=="false") { + } else if (str == "false") { _make_constant(false); } else { - bool found=false; + bool found = false; - struct _bit { Variant::Type type; const char *text;}; + struct _bit { + Variant::Type type; + const char *text; + }; //built in types - static const _bit type_list[]={ + static const _bit type_list[] = { //types - {Variant::BOOL,"bool"}, - {Variant::INT,"int"}, - {Variant::REAL,"float"}, - {Variant::STRING,"String"}, - {Variant::VECTOR2,"Vector2"}, - {Variant::RECT2,"Rect2"}, - {Variant::TRANSFORM2D,"Transform2D"}, - {Variant::VECTOR3,"Vector3"}, - {Variant::RECT3,"Rect3"}, - {Variant::PLANE,"Plane"}, - {Variant::QUAT,"Quat"}, - {Variant::BASIS,"Basis"}, - {Variant::TRANSFORM,"Transform"}, - {Variant::COLOR,"Color"}, - {Variant::IMAGE,"Image"}, - {Variant::_RID,"RID"}, - {Variant::OBJECT,"Object"}, - {Variant::INPUT_EVENT,"InputEvent"}, - {Variant::NODE_PATH,"NodePath"}, - {Variant::DICTIONARY,"Dictionary"}, - {Variant::ARRAY,"Array"}, - {Variant::POOL_BYTE_ARRAY,"PoolByteArray"}, - {Variant::POOL_INT_ARRAY,"PoolIntArray"}, - {Variant::POOL_REAL_ARRAY,"PoolFloatArray"}, - {Variant::POOL_STRING_ARRAY,"PoolStringArray"}, - {Variant::POOL_VECTOR2_ARRAY,"PoolVector2Array"}, - {Variant::POOL_VECTOR3_ARRAY,"PoolVector3Array"}, - {Variant::POOL_COLOR_ARRAY,"PoolColorArray"}, - {Variant::VARIANT_MAX,NULL}, + { Variant::BOOL, "bool" }, + { Variant::INT, "int" }, + { Variant::REAL, "float" }, + { Variant::STRING, "String" }, + { Variant::VECTOR2, "Vector2" }, + { Variant::RECT2, "Rect2" }, + { Variant::TRANSFORM2D, "Transform2D" }, + { Variant::VECTOR3, "Vector3" }, + { Variant::RECT3, "Rect3" }, + { Variant::PLANE, "Plane" }, + { Variant::QUAT, "Quat" }, + { Variant::BASIS, "Basis" }, + { Variant::TRANSFORM, "Transform" }, + { Variant::COLOR, "Color" }, + { Variant::IMAGE, "Image" }, + { Variant::_RID, "RID" }, + { Variant::OBJECT, "Object" }, + { Variant::INPUT_EVENT, "InputEvent" }, + { Variant::NODE_PATH, "NodePath" }, + { Variant::DICTIONARY, "Dictionary" }, + { Variant::ARRAY, "Array" }, + { Variant::POOL_BYTE_ARRAY, "PoolByteArray" }, + { Variant::POOL_INT_ARRAY, "PoolIntArray" }, + { Variant::POOL_REAL_ARRAY, "PoolFloatArray" }, + { Variant::POOL_STRING_ARRAY, "PoolStringArray" }, + { Variant::POOL_VECTOR2_ARRAY, "PoolVector2Array" }, + { Variant::POOL_VECTOR3_ARRAY, "PoolVector3Array" }, + { Variant::POOL_COLOR_ARRAY, "PoolColorArray" }, + { Variant::VARIANT_MAX, NULL }, }; { + int idx = 0; - int idx=0; - - while(type_list[idx].text) { + while (type_list[idx].text) { - if (str==type_list[idx].text) { + if (str == type_list[idx].text) { _make_type(type_list[idx].type); - found=true; + found = true; break; } idx++; @@ -841,12 +834,12 @@ void GDTokenizerText::_advance() { //built in func? - for(int i=0;i<GDFunctions::FUNC_MAX;i++) { + for (int i = 0; i < GDFunctions::FUNC_MAX; i++) { - if (str==GDFunctions::get_func_name(GDFunctions::Function(i))) { + if (str == GDFunctions::get_func_name(GDFunctions::Function(i))) { _make_built_in_func(GDFunctions::Function(i)); - found=true; + found = true; break; } } @@ -856,66 +849,68 @@ void GDTokenizerText::_advance() { if (!found) { + struct _kws { + Token token; + const char *text; + }; - struct _kws { Token token; const char *text;}; - - static const _kws keyword_list[]={ + static const _kws keyword_list[] = { //ops - {TK_OP_IN,"in"}, - {TK_OP_NOT,"not"}, - {TK_OP_OR,"or"}, - {TK_OP_AND,"and"}, + { TK_OP_IN, "in" }, + { TK_OP_NOT, "not" }, + { TK_OP_OR, "or" }, + { TK_OP_AND, "and" }, //func - {TK_PR_FUNCTION,"func"}, - {TK_PR_CLASS,"class"}, - {TK_PR_EXTENDS,"extends"}, - {TK_PR_ONREADY,"onready"}, - {TK_PR_TOOL,"tool"}, - {TK_PR_STATIC,"static"}, - {TK_PR_EXPORT,"export"}, - {TK_PR_SETGET,"setget"}, - {TK_PR_VAR,"var"}, - {TK_PR_PRELOAD,"preload"}, - {TK_PR_ASSERT,"assert"}, - {TK_PR_YIELD,"yield"}, - {TK_PR_SIGNAL,"signal"}, - {TK_PR_BREAKPOINT,"breakpoint"}, - {TK_PR_REMOTE,"remote"}, - {TK_PR_MASTER,"master"}, - {TK_PR_SLAVE,"slave"}, - {TK_PR_SYNC,"sync"}, - {TK_PR_CONST,"const"}, - {TK_PR_ENUM,"enum"}, + { TK_PR_FUNCTION, "func" }, + { TK_PR_CLASS, "class" }, + { TK_PR_EXTENDS, "extends" }, + { TK_PR_ONREADY, "onready" }, + { TK_PR_TOOL, "tool" }, + { TK_PR_STATIC, "static" }, + { TK_PR_EXPORT, "export" }, + { TK_PR_SETGET, "setget" }, + { TK_PR_VAR, "var" }, + { TK_PR_PRELOAD, "preload" }, + { TK_PR_ASSERT, "assert" }, + { TK_PR_YIELD, "yield" }, + { TK_PR_SIGNAL, "signal" }, + { TK_PR_BREAKPOINT, "breakpoint" }, + { TK_PR_REMOTE, "remote" }, + { TK_PR_MASTER, "master" }, + { TK_PR_SLAVE, "slave" }, + { TK_PR_SYNC, "sync" }, + { TK_PR_CONST, "const" }, + { TK_PR_ENUM, "enum" }, //controlflow - {TK_CF_IF,"if"}, - {TK_CF_ELIF,"elif"}, - {TK_CF_ELSE,"else"}, - {TK_CF_FOR,"for"}, - {TK_CF_WHILE,"while"}, - {TK_CF_DO,"do"}, - {TK_CF_SWITCH,"switch"}, - {TK_CF_CASE,"case"}, - {TK_CF_BREAK,"break"}, - {TK_CF_CONTINUE,"continue"}, - {TK_CF_RETURN,"return"}, - {TK_CF_MATCH, "match"}, - {TK_CF_PASS,"pass"}, - {TK_SELF,"self"}, - {TK_CONST_PI,"PI"}, - {TK_WILDCARD,"_"}, - {TK_CONST_INF,"INF"}, - {TK_CONST_NAN,"NAN"}, - {TK_ERROR,NULL} + { TK_CF_IF, "if" }, + { TK_CF_ELIF, "elif" }, + { TK_CF_ELSE, "else" }, + { TK_CF_FOR, "for" }, + { TK_CF_WHILE, "while" }, + { TK_CF_DO, "do" }, + { TK_CF_SWITCH, "switch" }, + { TK_CF_CASE, "case" }, + { TK_CF_BREAK, "break" }, + { TK_CF_CONTINUE, "continue" }, + { TK_CF_RETURN, "return" }, + { TK_CF_MATCH, "match" }, + { TK_CF_PASS, "pass" }, + { TK_SELF, "self" }, + { TK_CONST_PI, "PI" }, + { TK_WILDCARD, "_" }, + { TK_CONST_INF, "INF" }, + { TK_CONST_NAN, "NAN" }, + { TK_ERROR, NULL } }; - int idx=0; - found=false; + int idx = 0; + found = false; - while(keyword_list[idx].text) { + while (keyword_list[idx].text) { - if (str==keyword_list[idx].text) { + if (str == keyword_list[idx].text) { _make_token(keyword_list[idx].token); - found=true; + found = true; break; } idx++; @@ -923,10 +918,9 @@ void GDTokenizerText::_advance() { } if (!found) - identifier=true; + identifier = true; } - if (identifier) { _make_identifier(str); } @@ -943,381 +937,358 @@ void GDTokenizerText::_advance() { INCPOS(1); break; } - } -void GDTokenizerText::set_code(const String& p_code) { +void GDTokenizerText::set_code(const String &p_code) { - code=p_code; + code = p_code; len = p_code.length(); if (len) { - _code=&code[0]; + _code = &code[0]; } else { - _code=NULL; + _code = NULL; } - code_pos=0; - line=1; //it is stand-ar-ized that lines begin in 1 in code.. - column=1; //the same holds for columns - tk_rb_pos=0; - error_flag=false; - last_error=""; - for(int i=0;i<MAX_LOOKAHEAD+1;i++) + code_pos = 0; + line = 1; //it is stand-ar-ized that lines begin in 1 in code.. + column = 1; //the same holds for columns + tk_rb_pos = 0; + error_flag = false; + last_error = ""; + for (int i = 0; i < MAX_LOOKAHEAD + 1; i++) _advance(); } GDTokenizerText::Token GDTokenizerText::get_token(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, TK_ERROR); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, TK_ERROR); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, TK_ERROR); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, TK_ERROR); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].type; } int GDTokenizerText::get_token_line(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, -1); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].line; } int GDTokenizerText::get_token_column(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, -1); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, -1); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, -1); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; return tk_rb[ofs].col; } -const Variant& GDTokenizerText::get_token_constant(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant); +const Variant &GDTokenizerText::get_token_constant(int p_offset) const { + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, tk_rb[0].constant); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, tk_rb[0].constant); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_CONSTANT,tk_rb[0].constant); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_CONSTANT, tk_rb[0].constant); return tk_rb[ofs].constant; } StringName GDTokenizerText::get_token_identifier(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, StringName()); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, StringName()); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, StringName()); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, StringName()); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_IDENTIFIER,StringName()); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_IDENTIFIER, StringName()); return tk_rb[ofs].identifier; - } GDFunctions::Function GDTokenizerText::get_token_built_in_func(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, GDFunctions::FUNC_MAX); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_BUILT_IN_FUNC,GDFunctions::FUNC_MAX); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_FUNC, GDFunctions::FUNC_MAX); return tk_rb[ofs].func; - } Variant::Type GDTokenizerText::get_token_type(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, Variant::NIL); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, Variant::NIL); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, Variant::NIL); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, Variant::NIL); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_BUILT_IN_TYPE,Variant::NIL); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_BUILT_IN_TYPE, Variant::NIL); return tk_rb[ofs].vtype; - } - int GDTokenizerText::get_token_line_indent(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, 0); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, 0); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_NEWLINE,0); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_NEWLINE, 0); return tk_rb[ofs].constant; - } String GDTokenizerText::get_token_error(int p_offset) const { - ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, String()); - ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, String()); + ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, String()); + ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, String()); - int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD -1)%TK_RB_SIZE; - ERR_FAIL_COND_V(tk_rb[ofs].type!=TK_ERROR,String()); + int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE; + ERR_FAIL_COND_V(tk_rb[ofs].type != TK_ERROR, String()); return tk_rb[ofs].constant; } void GDTokenizerText::advance(int p_amount) { - ERR_FAIL_COND( p_amount <=0 ); - for(int i=0;i<p_amount;i++) + ERR_FAIL_COND(p_amount <= 0); + for (int i = 0; i < p_amount; i++) _advance(); } - - - - - - - - - - ////////////////////////////////////////////////////////////////////////////////////////////////////// #define BYTECODE_VERSION 12 -Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> & p_buffer) { - +Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> &p_buffer) { - const uint8_t *buf=p_buffer.ptr(); - int total_len=p_buffer.size(); - ERR_FAIL_COND_V( p_buffer.size()<24 || p_buffer[0]!='G' || p_buffer[1]!='D' || p_buffer[2]!='S' || p_buffer[3]!='C',ERR_INVALID_DATA); + const uint8_t *buf = p_buffer.ptr(); + int total_len = p_buffer.size(); + ERR_FAIL_COND_V(p_buffer.size() < 24 || p_buffer[0] != 'G' || p_buffer[1] != 'D' || p_buffer[2] != 'S' || p_buffer[3] != 'C', ERR_INVALID_DATA); int version = decode_uint32(&buf[4]); - if (version>BYTECODE_VERSION) { + if (version > BYTECODE_VERSION) { ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version."); - ERR_FAIL_COND_V(version>BYTECODE_VERSION,ERR_INVALID_DATA); + ERR_FAIL_COND_V(version > BYTECODE_VERSION, ERR_INVALID_DATA); } int identifier_count = decode_uint32(&buf[8]); int constant_count = decode_uint32(&buf[12]); int line_count = decode_uint32(&buf[16]); int token_count = decode_uint32(&buf[20]); - const uint8_t *b=buf; + const uint8_t *b = buf; - b=&buf[24]; - total_len-=24; + b = &buf[24]; + total_len -= 24; identifiers.resize(identifier_count); - for(int i=0;i<identifier_count;i++) { + for (int i = 0; i < identifier_count; i++) { int len = decode_uint32(b); - ERR_FAIL_COND_V(len>total_len,ERR_INVALID_DATA); - b+=4; + ERR_FAIL_COND_V(len > total_len, ERR_INVALID_DATA); + b += 4; Vector<uint8_t> cs; cs.resize(len); - for(int j=0;j<len;j++) { - cs[j]=b[j]^0xb6; + for (int j = 0; j < len; j++) { + cs[j] = b[j] ^ 0xb6; } - cs[cs.size()-1]=0; + cs[cs.size() - 1] = 0; String s; - s.parse_utf8((const char*)cs.ptr()); - b+=len; - total_len-=len+4; - identifiers[i]=s; + s.parse_utf8((const char *)cs.ptr()); + b += len; + total_len -= len + 4; + identifiers[i] = s; } constants.resize(constant_count); - for(int i=0;i<constant_count;i++) { + for (int i = 0; i < constant_count; i++) { Variant v; int len; - Error err = decode_variant(v,b,total_len,&len); + Error err = decode_variant(v, b, total_len, &len); if (err) return err; - b+=len; - total_len-=len; - constants[i]=v; - + b += len; + total_len -= len; + constants[i] = v; } - ERR_FAIL_COND_V(line_count*8>total_len,ERR_INVALID_DATA); + ERR_FAIL_COND_V(line_count * 8 > total_len, ERR_INVALID_DATA); - for(int i=0;i<line_count;i++) { + for (int i = 0; i < line_count; i++) { - uint32_t token=decode_uint32(b); - b+=4; - uint32_t linecol=decode_uint32(b); - b+=4; + uint32_t token = decode_uint32(b); + b += 4; + uint32_t linecol = decode_uint32(b); + b += 4; - lines.insert(token,linecol); - total_len-=8; + lines.insert(token, linecol); + total_len -= 8; } tokens.resize(token_count); - for(int i=0;i<token_count;i++) { + for (int i = 0; i < token_count; i++) { - ERR_FAIL_COND_V( total_len < 1, ERR_INVALID_DATA); + ERR_FAIL_COND_V(total_len < 1, ERR_INVALID_DATA); - if ((*b)&TOKEN_BYTE_MASK) { //little endian always - ERR_FAIL_COND_V( total_len < 4, ERR_INVALID_DATA); + if ((*b) & TOKEN_BYTE_MASK) { //little endian always + ERR_FAIL_COND_V(total_len < 4, ERR_INVALID_DATA); - tokens[i]=decode_uint32(b)&~TOKEN_BYTE_MASK; - b+=4; + tokens[i] = decode_uint32(b) & ~TOKEN_BYTE_MASK; + b += 4; } else { - tokens[i]=*b; - b+=1; + tokens[i] = *b; + b += 1; total_len--; } } - token=0; + token = 0; return OK; - } - -Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) { +Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String &p_code) { Vector<uint8_t> buf; - - Map<StringName,int> identifier_map; - HashMap<Variant,int,VariantHasher,VariantComparator> constant_map; - Map<uint32_t,int> line_map; + Map<StringName, int> identifier_map; + HashMap<Variant, int, VariantHasher, VariantComparator> constant_map; + Map<uint32_t, int> line_map; Vector<uint32_t> token_array; GDTokenizerText tt; tt.set_code(p_code); - int line=-1; + int line = -1; - while(true) { + while (true) { - if (tt.get_token_line()!=line) { + if (tt.get_token_line() != line) { - line=tt.get_token_line(); - line_map[line]=token_array.size(); + line = tt.get_token_line(); + line_map[line] = token_array.size(); } - uint32_t token=tt.get_token(); - switch(tt.get_token()) { + uint32_t token = tt.get_token(); + switch (tt.get_token()) { case TK_IDENTIFIER: { StringName id = tt.get_token_identifier(); if (!identifier_map.has(id)) { int idx = identifier_map.size(); - identifier_map[id]=idx; + identifier_map[id] = idx; } - token|=identifier_map[id]<<TOKEN_BITS; + token |= identifier_map[id] << TOKEN_BITS; } break; case TK_CONSTANT: { Variant c = tt.get_token_constant(); if (!constant_map.has(c)) { int idx = constant_map.size(); - constant_map[c]=idx; + constant_map[c] = idx; } - token|=constant_map[c]<<TOKEN_BITS; + token |= constant_map[c] << TOKEN_BITS; } break; case TK_BUILT_IN_TYPE: { - token|=tt.get_token_type()<<TOKEN_BITS; + token |= tt.get_token_type() << TOKEN_BITS; } break; case TK_BUILT_IN_FUNC: { - token|=tt.get_token_built_in_func()<<TOKEN_BITS; + token |= tt.get_token_built_in_func() << TOKEN_BITS; } break; case TK_NEWLINE: { - token|=tt.get_token_line_indent()<<TOKEN_BITS; + token |= tt.get_token_line_indent() << TOKEN_BITS; } break; case TK_ERROR: { ERR_FAIL_V(Vector<uint8_t>()); } break; default: {} - }; token_array.push_back(token); - if (tt.get_token()==TK_EOF) + if (tt.get_token() == TK_EOF) break; tt.advance(); - } //reverse maps - Map<int,StringName> rev_identifier_map; - for(Map<StringName,int>::Element *E=identifier_map.front();E;E=E->next()) { - rev_identifier_map[E->get()]=E->key(); + Map<int, StringName> rev_identifier_map; + for (Map<StringName, int>::Element *E = identifier_map.front(); E; E = E->next()) { + rev_identifier_map[E->get()] = E->key(); } - Map<int,Variant> rev_constant_map; - const Variant *K =NULL; - while((K=constant_map.next(K))) { - rev_constant_map[constant_map[*K]]=*K; + Map<int, Variant> rev_constant_map; + const Variant *K = NULL; + while ((K = constant_map.next(K))) { + rev_constant_map[constant_map[*K]] = *K; } - Map<int,uint32_t> rev_line_map; - for(Map<uint32_t,int>::Element *E=line_map.front();E;E=E->next()) { - rev_line_map[E->get()]=E->key(); + Map<int, uint32_t> rev_line_map; + for (Map<uint32_t, int>::Element *E = line_map.front(); E; E = E->next()) { + rev_line_map[E->get()] = E->key(); } //save header buf.resize(24); - buf[0]='G'; - buf[1]='D'; - buf[2]='S'; - buf[3]='C'; - encode_uint32(BYTECODE_VERSION,&buf[4]); - encode_uint32(identifier_map.size(),&buf[8]); - encode_uint32(constant_map.size(),&buf[12]); - encode_uint32(line_map.size(),&buf[16]); - encode_uint32(token_array.size(),&buf[20]); + buf[0] = 'G'; + buf[1] = 'D'; + buf[2] = 'S'; + buf[3] = 'C'; + encode_uint32(BYTECODE_VERSION, &buf[4]); + encode_uint32(identifier_map.size(), &buf[8]); + encode_uint32(constant_map.size(), &buf[12]); + encode_uint32(line_map.size(), &buf[16]); + encode_uint32(token_array.size(), &buf[20]); //save identifiers - for(Map<int,StringName>::Element *E=rev_identifier_map.front();E;E=E->next()) { + for (Map<int, StringName>::Element *E = rev_identifier_map.front(); E; E = E->next()) { CharString cs = String(E->get()).utf8(); - int len = cs.length()+1; - int extra = 4-(len%4); - if (extra==4) - extra=0; + int len = cs.length() + 1; + int extra = 4 - (len % 4); + if (extra == 4) + extra = 0; uint8_t ibuf[4]; - encode_uint32(len+extra,ibuf); - for(int i=0;i<4;i++) { + encode_uint32(len + extra, ibuf); + for (int i = 0; i < 4; i++) { buf.push_back(ibuf[i]); } - for(int i=0;i<len;i++) { - buf.push_back(cs[i]^0xb6); + for (int i = 0; i < len; i++) { + buf.push_back(cs[i] ^ 0xb6); } - for(int i=0;i<extra;i++) { - buf.push_back(0^0xb6); + for (int i = 0; i < extra; i++) { + buf.push_back(0 ^ 0xb6); } } - for(Map<int,Variant>::Element *E=rev_constant_map.front();E;E=E->next()) { + for (Map<int, Variant>::Element *E = rev_constant_map.front(); E; E = E->next()) { int len; - Error err = encode_variant(E->get(),NULL,len); - ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>()); - int pos=buf.size(); - buf.resize(pos+len); - encode_variant(E->get(),&buf[pos],len); + Error err = encode_variant(E->get(), NULL, len); + ERR_FAIL_COND_V(err != OK, Vector<uint8_t>()); + int pos = buf.size(); + buf.resize(pos + len); + encode_variant(E->get(), &buf[pos], len); } - for(Map<int,uint32_t>::Element *E=rev_line_map.front();E;E=E->next()) { + for (Map<int, uint32_t>::Element *E = rev_line_map.front(); E; E = E->next()) { uint8_t ibuf[8]; - encode_uint32(E->key(),&ibuf[0]); - encode_uint32(E->get(),&ibuf[4]); - for(int i=0;i<8;i++) + encode_uint32(E->key(), &ibuf[0]); + encode_uint32(E->get(), &ibuf[4]); + for (int i = 0; i < 8; i++) buf.push_back(ibuf[i]); } - for(int i=0;i<token_array.size();i++) { + for (int i = 0; i < token_array.size(); i++) { uint32_t token = token_array[i]; - if (token&~TOKEN_MASK) { + if (token & ~TOKEN_MASK) { uint8_t buf4[4]; - encode_uint32(token_array[i]|TOKEN_BYTE_MASK,&buf4[0]); - for(int j=0;j<4;j++) { + encode_uint32(token_array[i] | TOKEN_BYTE_MASK, &buf4[0]); + for (int j = 0; j < 4; j++) { buf.push_back(buf4[j]); } } else { @@ -1326,102 +1297,94 @@ Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) { } return buf; - } GDTokenizerBuffer::Token GDTokenizerBuffer::get_token(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; - if (offset<0 || offset>=tokens.size()) + if (offset < 0 || offset >= tokens.size()) return TK_EOF; - return GDTokenizerBuffer::Token(tokens[offset]&TOKEN_MASK); + return GDTokenizerBuffer::Token(tokens[offset] & TOKEN_MASK); } +StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const { -StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const{ + int offset = token + p_offset; - int offset = token+p_offset; - - ERR_FAIL_INDEX_V(offset,tokens.size(),StringName()); - uint32_t identifier = tokens[offset]>>TOKEN_BITS; - ERR_FAIL_INDEX_V(identifier,(uint32_t)identifiers.size(),StringName()); + ERR_FAIL_INDEX_V(offset, tokens.size(), StringName()); + uint32_t identifier = tokens[offset] >> TOKEN_BITS; + ERR_FAIL_INDEX_V(identifier, (uint32_t)identifiers.size(), StringName()); return identifiers[identifier]; } -GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const{ +GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),GDFunctions::FUNC_MAX); - return GDFunctions::Function(tokens[offset]>>TOKEN_BITS); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), GDFunctions::FUNC_MAX); + return GDFunctions::Function(tokens[offset] >> TOKEN_BITS); } -Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const{ +Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),Variant::NIL); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), Variant::NIL); - return Variant::Type(tokens[offset]>>TOKEN_BITS); + return Variant::Type(tokens[offset] >> TOKEN_BITS); } -int GDTokenizerBuffer::get_token_line(int p_offset) const{ +int GDTokenizerBuffer::get_token_line(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; int pos = lines.find_nearest(offset); - if (pos<0) + if (pos < 0) return -1; - if (pos>=lines.size()) - pos=lines.size()-1; + if (pos >= lines.size()) + pos = lines.size() - 1; uint32_t l = lines.getv(pos); - return l&TOKEN_LINE_MASK; - + return l & TOKEN_LINE_MASK; } -int GDTokenizerBuffer::get_token_column(int p_offset) const{ +int GDTokenizerBuffer::get_token_column(int p_offset) const { - int offset = token+p_offset; + int offset = token + p_offset; int pos = lines.find_nearest(offset); - if (pos<0) + if (pos < 0) return -1; - if (pos>=lines.size()) - pos=lines.size()-1; + if (pos >= lines.size()) + pos = lines.size() - 1; uint32_t l = lines.getv(pos); - return l>>TOKEN_LINE_BITS; - + return l >> TOKEN_LINE_BITS; } -int GDTokenizerBuffer::get_token_line_indent(int p_offset) const{ +int GDTokenizerBuffer::get_token_line_indent(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),0); - return tokens[offset]>>TOKEN_BITS; + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), 0); + return tokens[offset] >> TOKEN_BITS; } -const Variant& GDTokenizerBuffer::get_token_constant(int p_offset) const{ - +const Variant &GDTokenizerBuffer::get_token_constant(int p_offset) const { - int offset = token+p_offset; - ERR_FAIL_INDEX_V(offset,tokens.size(),nil); - uint32_t constant = tokens[offset]>>TOKEN_BITS; - ERR_FAIL_INDEX_V(constant,(uint32_t)constants.size(),nil); + int offset = token + p_offset; + ERR_FAIL_INDEX_V(offset, tokens.size(), nil); + uint32_t constant = tokens[offset] >> TOKEN_BITS; + ERR_FAIL_INDEX_V(constant, (uint32_t)constants.size(), nil); return constants[constant]; - } -String GDTokenizerBuffer::get_token_error(int p_offset) const{ +String GDTokenizerBuffer::get_token_error(int p_offset) const { ERR_FAIL_V(String()); } -void GDTokenizerBuffer::advance(int p_amount){ +void GDTokenizerBuffer::advance(int p_amount) { - ERR_FAIL_INDEX(p_amount+token,tokens.size()); - token+=p_amount; + ERR_FAIL_INDEX(p_amount + token, tokens.size()); + token += p_amount; } -GDTokenizerBuffer::GDTokenizerBuffer(){ - - token=0; +GDTokenizerBuffer::GDTokenizerBuffer() { + token = 0; } - diff --git a/modules/gdscript/gd_tokenizer.h b/modules/gdscript/gd_tokenizer.h index 1e9eda7947..c1ed8ad92e 100644 --- a/modules/gdscript/gd_tokenizer.h +++ b/modules/gdscript/gd_tokenizer.h @@ -29,15 +29,14 @@ #ifndef GD_TOKENIZER_H #define GD_TOKENIZER_H +#include "gd_functions.h" +#include "string_db.h" #include "ustring.h" #include "variant.h" -#include "string_db.h" -#include "gd_functions.h" #include "vmap.h" class GDTokenizer { public: - enum Token { TK_EMPTY, @@ -137,37 +136,36 @@ public: }; protected: - enum StringMode { STRING_SINGLE_QUOTE, STRING_DOUBLE_QUOTE, STRING_MULTILINE }; - static const char* token_names[TK_MAX]; + static const char *token_names[TK_MAX]; + public: static const char *get_token_name(Token p_token); - virtual const Variant& get_token_constant(int p_offset=0) const=0; - virtual Token get_token(int p_offset=0) const=0; - virtual StringName get_token_identifier(int p_offset=0) const=0; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const=0; - virtual Variant::Type get_token_type(int p_offset=0) const=0; - virtual int get_token_line(int p_offset=0) const=0; - virtual int get_token_column(int p_offset=0) const=0; - virtual int get_token_line_indent(int p_offset=0) const=0; - virtual String get_token_error(int p_offset=0) const=0; - virtual void advance(int p_amount=1)=0; + virtual const Variant &get_token_constant(int p_offset = 0) const = 0; + virtual Token get_token(int p_offset = 0) const = 0; + virtual StringName get_token_identifier(int p_offset = 0) const = 0; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const = 0; + virtual Variant::Type get_token_type(int p_offset = 0) const = 0; + virtual int get_token_line(int p_offset = 0) const = 0; + virtual int get_token_column(int p_offset = 0) const = 0; + virtual int get_token_line_indent(int p_offset = 0) const = 0; + virtual String get_token_error(int p_offset = 0) const = 0; + virtual void advance(int p_amount = 1) = 0; virtual ~GDTokenizer(){}; - }; class GDTokenizerText : public GDTokenizer { enum { - MAX_LOOKAHEAD=4, - TK_RB_SIZE=MAX_LOOKAHEAD*2+1 + MAX_LOOKAHEAD = 4, + TK_RB_SIZE = MAX_LOOKAHEAD * 2 + 1 }; @@ -179,17 +177,21 @@ class GDTokenizerText : public GDTokenizer { Variant::Type vtype; //for type types GDFunctions::Function func; //function for built in functions }; - int line,col; - TokenData() { type = TK_EMPTY; line=col=0; vtype=Variant::NIL; } + int line, col; + TokenData() { + type = TK_EMPTY; + line = col = 0; + vtype = Variant::NIL; + } }; void _make_token(Token p_type); - void _make_newline(int p_spaces=0); - void _make_identifier(const StringName& p_identifier); + void _make_newline(int p_spaces = 0); + void _make_identifier(const StringName &p_identifier); void _make_built_in_func(GDFunctions::Function p_func); - void _make_constant(const Variant& p_constant); - void _make_type(const Variant::Type& p_type); - void _make_error(const String& p_error); + void _make_constant(const Variant &p_constant); + void _make_type(const Variant::Type &p_type); + void _make_error(const String &p_error); String code; int len; @@ -197,66 +199,58 @@ class GDTokenizerText : public GDTokenizer { const CharType *_code; int line; int column; - TokenData tk_rb[TK_RB_SIZE*2+1]; + TokenData tk_rb[TK_RB_SIZE * 2 + 1]; int tk_rb_pos; String last_error; bool error_flag; void _advance(); -public: - - void set_code(const String& p_code); - virtual Token get_token(int p_offset=0) const; - virtual StringName get_token_identifier(int p_offset=0) const; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const; - virtual Variant::Type get_token_type(int p_offset=0) const; - virtual int get_token_line(int p_offset=0) const; - virtual int get_token_column(int p_offset=0) const; - virtual int get_token_line_indent(int p_offset=0) const; - virtual const Variant& get_token_constant(int p_offset=0) const; - virtual String get_token_error(int p_offset=0) const; - virtual void advance(int p_amount=1); +public: + void set_code(const String &p_code); + virtual Token get_token(int p_offset = 0) const; + virtual StringName get_token_identifier(int p_offset = 0) const; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const; + virtual Variant::Type get_token_type(int p_offset = 0) const; + virtual int get_token_line(int p_offset = 0) const; + virtual int get_token_column(int p_offset = 0) const; + virtual int get_token_line_indent(int p_offset = 0) const; + virtual const Variant &get_token_constant(int p_offset = 0) const; + virtual String get_token_error(int p_offset = 0) const; + virtual void advance(int p_amount = 1); }; - - - class GDTokenizerBuffer : public GDTokenizer { - enum { - TOKEN_BYTE_MASK=0x80, - TOKEN_BITS=8, - TOKEN_MASK=(1<<TOKEN_BITS)-1, - TOKEN_LINE_BITS=24, - TOKEN_LINE_MASK=(1<<TOKEN_LINE_BITS)-1, + TOKEN_BYTE_MASK = 0x80, + TOKEN_BITS = 8, + TOKEN_MASK = (1 << TOKEN_BITS) - 1, + TOKEN_LINE_BITS = 24, + TOKEN_LINE_MASK = (1 << TOKEN_LINE_BITS) - 1, }; - Vector<StringName> identifiers; Vector<Variant> constants; - VMap<uint32_t,uint32_t> lines; + VMap<uint32_t, uint32_t> lines; Vector<uint32_t> tokens; Variant nil; int token; public: - - - Error set_code_buffer(const Vector<uint8_t> & p_buffer); - static Vector<uint8_t> parse_code_string(const String& p_code); - virtual Token get_token(int p_offset=0) const; - virtual StringName get_token_identifier(int p_offset=0) const; - virtual GDFunctions::Function get_token_built_in_func(int p_offset=0) const; - virtual Variant::Type get_token_type(int p_offset=0) const; - virtual int get_token_line(int p_offset=0) const; - virtual int get_token_column(int p_offset=0) const; - virtual int get_token_line_indent(int p_offset=0) const; - virtual const Variant& get_token_constant(int p_offset=0) const; - virtual String get_token_error(int p_offset=0) const; - virtual void advance(int p_amount=1); + Error set_code_buffer(const Vector<uint8_t> &p_buffer); + static Vector<uint8_t> parse_code_string(const String &p_code); + virtual Token get_token(int p_offset = 0) const; + virtual StringName get_token_identifier(int p_offset = 0) const; + virtual GDFunctions::Function get_token_built_in_func(int p_offset = 0) const; + virtual Variant::Type get_token_type(int p_offset = 0) const; + virtual int get_token_line(int p_offset = 0) const; + virtual int get_token_column(int p_offset = 0) const; + virtual int get_token_line_indent(int p_offset = 0) const; + virtual const Variant &get_token_constant(int p_offset = 0) const; + virtual String get_token_error(int p_offset = 0) const; + virtual void advance(int p_amount = 1); GDTokenizerBuffer(); }; diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index d1d69c6709..5acd412f7e 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -29,22 +29,20 @@ #include "register_types.h" #include "gd_script.h" +#include "io/file_access_encrypted.h" #include "io/resource_loader.h" #include "os/file_access.h" -#include "io/file_access_encrypted.h" - - -GDScriptLanguage *script_language_gd=NULL; -ResourceFormatLoaderGDScript *resource_loader_gd=NULL; -ResourceFormatSaverGDScript *resource_saver_gd=NULL; +GDScriptLanguage *script_language_gd = NULL; +ResourceFormatLoaderGDScript *resource_loader_gd = NULL; +ResourceFormatSaverGDScript *resource_saver_gd = NULL; #if 0 #ifdef TOOLS_ENABLED #include "editor/editor_import_export.h" -#include "gd_tokenizer.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" +#include "gd_tokenizer.h" class EditorExportGDScript : public EditorExportPlugin { @@ -133,7 +131,6 @@ static void register_editor_plugin() { EditorImportExport::get_singleton()->add_export_plugin(egd); } - #endif #endif void register_gdscript_types() { @@ -141,12 +138,12 @@ void register_gdscript_types() { ClassDB::register_class<GDScript>(); ClassDB::register_virtual_class<GDFunctionState>(); - script_language_gd=memnew( GDScriptLanguage ); + script_language_gd = memnew(GDScriptLanguage); //script_language_gd->init(); ScriptServer::register_language(script_language_gd); - resource_loader_gd=memnew( ResourceFormatLoaderGDScript ); + resource_loader_gd = memnew(ResourceFormatLoaderGDScript); ResourceLoader::add_resource_format_loader(resource_loader_gd); - resource_saver_gd=memnew( ResourceFormatSaverGDScript ); + resource_saver_gd = memnew(ResourceFormatSaverGDScript); ResourceSaver::add_resource_format_saver(resource_saver_gd); #if 0 #ifdef TOOLS_ENABLED @@ -154,18 +151,15 @@ void register_gdscript_types() { EditorNode::add_init_callback(register_editor_plugin); #endif #endif - } void unregister_gdscript_types() { - ScriptServer::unregister_language(script_language_gd); if (script_language_gd) - memdelete( script_language_gd ); + memdelete(script_language_gd); if (resource_loader_gd) - memdelete( resource_loader_gd ); + memdelete(resource_loader_gd); if (resource_saver_gd) - memdelete( resource_saver_gd ); - + memdelete(resource_saver_gd); } |