Ejemplo n.º 1
0
parsing_result_type_t parseSync(xmlNode * node, CONTEXT * ctx)
{
    ctx->sync_manager = calloc(1, sizeof(EC_SYNC_MANAGER));
    EC_SYNC_MANAGER *sm = ctx->sync_manager;
    char parseBuffer[20];
    char *direction = parseBuffer;
    int parsingIsOkay = 1;
    parsingIsOkay = getStr(node, "dir", &direction);
    if (strcasecmp("outputs", direction) == 0)
    {
      sm->direction = PARSER_DIR_OUTPUT;
    }
    else if (strcasecmp("inputs", direction) == 0)
    {
      sm->direction = PARSER_DIR_INPUT;
    }
    else
    {
      sm->direction = PARSER_DIR_INVALID;
    }
    parsingIsOkay =parsingIsOkay &&
        getInt(node, "index", &sm->index, PARSER_REQUIRED) &&
        getInt(node, "watchdog", &sm->watchdog, PARSER_REQUIRED) &&
        parseChildren(node, ctx, "pdo", parsePdo) &&
        (sm->parent = ctx->device_type);
    if (parsingIsOkay)
    {
        if (sm->direction == PARSER_DIR_INVALID)
            return PARSING_OKAY;
        return ellAddOK(&ctx->device_type->sync_managers, &sm->node);
    }
    else
        return PARSING_ERROR;
}
Ejemplo n.º 2
0
void XML::parseChildren(xmlDocPtr doc, xmlNodePtr child, DomElement *parent) {
	xmlNode *cur_node = NULL;
	XMLElement *new_element = NULL;
	xmlAttrPtr attr;
		
	for(cur_node = child ; cur_node ; cur_node = cur_node->next ) {
		if( cur_node->type == XML_ELEMENT_NODE) {
			if(!parent) {
				new_element = newElement((char *)cur_node->name);
			} else {
				new_element = (XMLElement *)parent->newElement((char *)cur_node->name);
			}
		} else if (cur_node->type == XML_TEXT_NODE && xmlIsBlankNode(cur_node)==0) {
			parent->setValue((char *)cur_node->content);
		}
		parseChildren(doc,cur_node->children,new_element);
		attr = cur_node->properties;
		while(attr) {
			std::string name = (char *)attr->name;
			std::string value = (char *)attr->children->content;
			new_element->setAttribute(name,value);
			attr = attr->next;
		}
	}
}	
Ejemplo n.º 3
0
void
MusicDNSXmlParser::parseElement( const QDomElement &e )
{
    QString elementName = e.tagName();
    if( elementName == "track" )
        parseTrack( e );
    else
        parseChildren( e );
}
Ejemplo n.º 4
0
parsing_result_type_t parsePdo(xmlNode * node, CONTEXT * ctx)
{
    ctx->pdo = calloc(1, sizeof(EC_PDO));
    return 
        getStr(node, "name", &ctx->pdo->name) &&
        getInt(node, "index", &ctx->pdo->index, PARSER_REQUIRED) &&
        parseChildren(node, ctx, "entry", parsePdoEntry) &&
        (ctx->pdo->parent = ctx->sync_manager) && 
        ellAddOK(&ctx->sync_manager->pdos, &ctx->pdo->node);
}
Ejemplo n.º 5
0
int parseEntriesFromBuffer(char * text, int size, EC_CONFIG * cfg)
{
    CONTEXT ctx;
    ctx.config = cfg;
    //printf("%s\n", text);
    xmlDoc * doc = xmlReadMemory(text, size, NULL, NULL, 0);
    assert(doc);
    xmlNode * node = xmlDocGetRootElement(doc);
    assert(node);
    parseChildren(node, &ctx, "entry", parsePdoEntryMapping);
    return PARSING_ERROR;
}
Ejemplo n.º 6
0
parsing_result_type_t  parseSdo(xmlNode * node, CONTEXT * ctx)
{
    char * slave;
    ctx->sdo = calloc(1, sizeof(EC_SDO));
    parsing_result_type_t parsing_status;
    parsing_status =     getInt(node, "index", &ctx->sdo->index, PARSER_REQUIRED) &&
        getStr(node, "name", &ctx->sdo->name) &&
        getStr(node, "slave", &slave) && 
        joinSlave(ctx->config, slave, ctx->sdo);
    return parsing_status &&
        parseChildren(node, ctx, "sdoentry", parseSdoEntry) &&
        ellAddOK(&ctx->config->sdo_requests, &ctx->sdo->node);
}
Ejemplo n.º 7
0
parsing_result_type_t parseDeviceType(xmlNode * node, CONTEXT * ctx)
{
    ctx->device_type = calloc(1, sizeof(EC_DEVICE_TYPE));
    EC_DEVICE_TYPE *dt = ctx->device_type;
    return
        getStr(node, "name", &dt->name) &&
        getInt(node, "dcactivate", 
               &dt->oversampling_activate, PARSER_OPTIONAL) &&
        getInt(node, "vendor", &dt->vendor_id, PARSER_REQUIRED) &&
        getInt(node, "product", &dt->product_id, PARSER_REQUIRED) &&
        getInt(node, "revision", &dt->revision_id, PARSER_REQUIRED) &&
        parseChildren(node, ctx, "sync", parseSync) &&
        ellAddOK(&ctx->config->device_types, &dt->node);
}
Ejemplo n.º 8
0
    //---------------------------------------------------------------------
    void OverlayManager::parseNewElement( DataStreamPtr& stream, String& elemType, String& elemName, 
            bool isContainer, Overlay* pOverlay, bool isATemplate, String templateName, OverlayContainer* container)
    {
        String line;

		OverlayElement* newElement = NULL;
		newElement = 
				OverlayManager::getSingleton().createOverlayElementFromTemplate(templateName, elemType, elemName, isATemplate);

			// do not add a template to an overlay

		// add new element to parent
		if (container)
		{
			// Attach to container
			container->addChild(newElement);
		}
		// do not add a template to the overlay. For templates overlay = 0
		else if (pOverlay)	
		{
			pOverlay->add2D((OverlayContainer*)newElement);
		}

        while(!stream->eof())
        {
            line = stream->getLine();
            // Ignore comments & blanks
            if (!(line.length() == 0 || line.substr(0,2) == "//"))
            {
                if (line == "}")
                {
                    // Finished element
                    break;
                }
                else
                {
                    if (isContainer && parseChildren(stream,line, pOverlay, isATemplate, static_cast<OverlayContainer*>(newElement)))
                    {
					    // nested children... don't reparse it
                    }
                    else
                    {
                        // Attribute
                        parseElementAttrib(line, pOverlay, newElement);
                    }
                }
            }
        }
    }
Ejemplo n.º 9
0
void
MusicBrainzXmlParser::parseElement( const QDomElement &e )
{
    QString elementName = e.tagName();
    if( elementName == "recording-list" )
    {
        m_type = TrackList;
        parseRecordingList( e );
    }
    else if( elementName == "release-group" )
    {
        m_type = ReleaseGroup;
        parseReleaseGroup( e );
    }
    else
        parseChildren( e );
}
Ejemplo n.º 10
0
bool DomTree::load(char *buffer, int len) {
	xmlDocPtr doc;
	xmlNodePtr cur;
	xmlAttrPtr attr;
	
	doc = xmlParseMemory(buffer,len);
	
	
	if(doc == NULL) {
		return(false);
	}
	
	if(doc->version)
		version = (char *)doc->version;
	if(doc->encoding)
		encoding = (char *)doc->encoding;
	
	
	cur = xmlDocGetRootElement(doc);
	
	if(cur == NULL) {
		return(false);
	}
	
	name = (char *)cur->name;
	
	attr = cur->properties;
	
	while(attr) {
		std::string name = (char *)attr->name;
		std::string value = (char *)attr->children->content;
		setAttribute(name,value);
		attr = attr->next;
	}
	
	cur = cur->children;
	
	parseChildren(doc,cur,NULL);
	
	xmlFreeDoc(doc);
	xmlCleanupParser();
	return(true);
	
}
Ejemplo n.º 11
0
GroupNode::GroupNode(VRMLParser& parser)
	:haveBoundingBox(false),
	 boundingBox(Box::empty)
	{
	/* Check for the opening brace: */
	if(!parser.isToken("{"))
		Misc::throwStdErr("GroupNode::GroupNode: Missing opening brace in node definition, have %s instead",parser.getToken());
	parser.getNextToken();
	
	/* Process attributes until closing brace: */
	Vec3f bboxCenter(0.0f,0.0f,0.0f);
	Vec3f bboxSize(-1.0f,-1.0f,-1.0f);
	while(!parser.isToken("}"))
		{
		if(parser.isToken("bboxCenter"))
			{
			parser.getNextToken();
			bboxCenter=SFVec3f::parse(parser);
			}
		else if(parser.isToken("bboxSize"))
			{
			parser.getNextToken();
			bboxSize=SFVec3f::parse(parser);
			}
		else if(parser.isToken("children"))
			{
			/* Parse the node's children: */
			parseChildren(parser);
			}
		else
			Misc::throwStdErr("GroupNode::GroupNode: unknown attribute \"%s\" in node definition",parser.getToken());
		}
	
	/* Skip the closing brace: */
	parser.getNextToken();
	
	/* Construct the explicit bounding box: */
	setBoundingBox(bboxCenter,bboxSize);
	}
Ejemplo n.º 12
0
void RenJS::parseParam(const CString& strParam, RenJS::Node& node)
{
	int index = strParam.Find("=");

	CString strKey(strParam.Left(index));
	CString strValue(strParam.Right(strParam.GetLength() - 1 - index));

	if (strKey == "i")
	{
		parseId(strValue, node);
	}
	else if (strKey == "p")
	{
		parseCoordinate(strValue, node);
	}
	else if (strKey == "m")
	{
		parseNumber(strValue, node);
	}
	else if (strKey == "f")
	{
		parseParent(strValue, node);
	}
	else if (strKey == "c")
	{
		parseChildren(strValue, node);
	}
	else if (strKey == "co")
	{
		parseComment(strValue, node);
	}
	else if (strKey == "k")
	{
		parseBoardText(strValue, node);
	}
}
Ejemplo n.º 13
0
SimObject* TamlBinaryReader::parseElement( Stream& stream, const U32 versionId )
{
    // Debug Profiling.
    PROFILE_SCOPE(TamlBinaryReader_ParseElement);

    SimObject* pSimObject = NULL;

#ifdef TORQUE_DEBUG
    // Format the type location.
    char typeLocationBuffer[64];
    dSprintf( typeLocationBuffer, sizeof(typeLocationBuffer), "Taml [format='binary' offset=%u]", stream.getPosition() );
#endif

    // Fetch element name.    
    StringTableEntry typeName = stream.readSTString();

    // Fetch object name.
    StringTableEntry objectName = stream.readSTString();

    // Read references.
    U32 tamlRefId;
    U32 tamlRefToId;
    stream.read( &tamlRefId );
    stream.read( &tamlRefToId );

    // Do we have a reference to Id?
    if ( tamlRefToId != 0 )
    {
        // Yes, so fetch reference.
        typeObjectReferenceHash::Iterator referenceItr = mObjectReferenceMap.find( tamlRefToId );

        // Did we find the reference?
        if ( referenceItr == mObjectReferenceMap.end() )
        {
            // No, so warn.
            Con::warnf( "Taml: Could not find a reference Id of '%d'", tamlRefToId );
            return NULL;
        }

        // Return object.
        return referenceItr->value;
    }

#ifdef TORQUE_DEBUG
    // Create type.
    pSimObject = Taml::createType( typeName, mpTaml, typeLocationBuffer );
#else
    // Create type.
    pSimObject = Taml::createType( typeName, mpTaml );
#endif

    // Finish if we couldn't create the type.
    if ( pSimObject == NULL )
        return NULL;

    // Find Taml callbacks.
    TamlCallbacks* pCallbacks = dynamic_cast<TamlCallbacks*>( pSimObject );

    // Are there any Taml callbacks?
    if ( pCallbacks != NULL )
    {
        // Yes, so call it.
        mpTaml->tamlPreRead( pCallbacks );
    }

    // Parse attributes.
    parseAttributes( stream, pSimObject, versionId );

    // Does the object require a name?
    if ( objectName == StringTable->EmptyString() )
    {
        // No, so just register anonymously.
        pSimObject->registerObject();
    }
    else
    {
        // Yes, so register a named object.
        pSimObject->registerObject( objectName );

        // Was the name assigned?
        if ( pSimObject->getName() != objectName )
        {
            // No, so warn that the name was rejected.
#ifdef TORQUE_DEBUG
            Con::warnf( "Taml::parseElement() - Registered an instance of type '%s' but a request to name it '%s' was rejected.  This is typically because an object of that name already exists.  '%s'", typeName, objectName, typeLocationBuffer );
#else
            Con::warnf( "Taml::parseElement() - Registered an instance of type '%s' but a request to name it '%s' was rejected.  This is typically because an object of that name already exists.", typeName, objectName );
#endif
        }
    }

    // Do we have a reference Id?
    if ( tamlRefId != 0 )
    {
        // Yes, so insert reference.
        mObjectReferenceMap.insertUnique( tamlRefId, pSimObject );
    }

    // Parse custom elements.
    TamlCustomNodes customProperties;

    // Parse children.
    parseChildren( stream, pCallbacks, pSimObject, versionId );

    // Parse custom elements.
    parseCustomElements( stream, pCallbacks, customProperties, versionId );

    // Are there any Taml callbacks?
    if ( pCallbacks != NULL )
    {
        // Yes, so call it.
        mpTaml->tamlPostRead( pCallbacks, customProperties );
    }

    // Return object.
    return pSimObject;
}
Ejemplo n.º 14
0
int parseSdoRequests(xmlNode * node, CONTEXT * ctx)
{
    return parseChildren(node, ctx, "sdo", parseSdo);
}
Ejemplo n.º 15
0
TransformNode::TransformNode(VRMLParser& parser)
	:transform(Transformation::identity)
	{
	/* Check for the opening brace: */
	if(!parser.isToken("{"))
		Misc::throwStdErr("TransformNode::TransformNode: Missing opening brace in node definition");
	parser.getNextToken();
	
	/* Process attributes until closing brace: */
	Point center=Point::origin;
	Rotation rotation=Rotation::identity;
	float scale=1.0f;
	Rotation scaleOrientation=Rotation::identity;
	Vector translation=Vector::zero;
	Vec3f bboxCenter(0.0f,0.0f,0.0f);
	Vec3f bboxSize(-1.0f,-1.0f,-1.0f);
	while(!parser.isToken("}"))
		{
		if(parser.isToken("center"))
			{
			/* Parse the rotation and scaling center: */
			parser.getNextToken();
			Vec3f c=SFVec3f::parse(parser);
			center=Point(c.getXyzw());
			}
		else if(parser.isToken("rotation"))
			{
			/* Parse the rotation: */
			parser.getNextToken();
			rotation=SFRotation::parse(parser);
			}
		else if(parser.isToken("scale"))
			{
			/* Parse the scale factors: */
			parser.getNextToken();
			Vec3f s=SFVec3f::parse(parser);
			scale=Math::pow(s[0]*s[1]*s[2],1.0f/3.0f);
			}
		else if(parser.isToken("scaleOrientation"))
			{
			/* Parse the scale orientation: */
			parser.getNextToken();
			scaleOrientation=SFRotation::parse(parser);
			}
		else if(parser.isToken("translation"))
			{
			/* Parse the translation vector: */
			parser.getNextToken();
			Vec3f t=SFVec3f::parse(parser);
			translation=Vector(t.getXyzw());
			}
		else if(parser.isToken("bboxCenter"))
			{
			parser.getNextToken();
			bboxCenter=SFVec3f::parse(parser);
			}
		else if(parser.isToken("bboxSize"))
			{
			parser.getNextToken();
			bboxSize=SFVec3f::parse(parser);
			}
		else if(parser.isToken("children"))
			{
			/* Parse the node's children: */
			parseChildren(parser);
			}
		else
			Misc::throwStdErr("TransformNode::TransformNode: unknown attribute \"%s\" in node definition",parser.getToken());
		}
	
	/* Skip the closing brace: */
	parser.getNextToken();
	
	/* Construct the explicit bounding box: */
	setBoundingBox(bboxCenter,bboxSize);
	
	/* Set the transformation: */
	transform=Transformation::identity;
	transform*=Transformation::translate(translation);
	transform*=Transformation::translateFromOriginTo(center);
	transform*=Transformation::scale(scale);
	transform*=Transformation::rotate(rotation);
	transform*=Transformation::translateToOriginFrom(center);
	}
Ejemplo n.º 16
0
parsing_result_type_t parseChain(xmlNode * node, CONTEXT * ctx)
{
    parsing_result_type_t r = parseChildren(node, ctx, "device", parseDevice);
    /* show(ctx); */
    return r;
}
Ejemplo n.º 17
0
parsing_result_type_t parseSimspec(xmlNode * node, CONTEXT * ctx)
{
    return parseChildren(node, ctx, "simulation", parseSimulation);
}
Ejemplo n.º 18
0
parsing_result_type_t parseTypes(xmlNode * node, CONTEXT * ctx)
{
    return parseChildren(node, ctx, "device", parseDeviceType);
}
Ejemplo n.º 19
0
XERCES_CPP_NAMESPACE_USE

#define ARRAY_SIZE(ARY) ( (int)(sizeof(ARY)/sizeof(ARY[0])) )

#ifdef CONF_DUMP
#define ENABLE_DUMP
#define ENABLE_DUMP1
#endif
#include "ParserDump.h"

void JointParser::parse(DOMNode &target, Eval &eval)
{
	char *name = XMLUtils::getAttribute(target, "name");
	DUMP1(("name %s\n", name));

	m_transform.push();

	DOMNode *p = target.getFirstChild();
	while (p) {
		char *s = XMLString::transcode(p->getNodeName());
		//		printf("%s\n", s);
		if (strcmp(s, "type") == 0) {
			char *type = XMLUtils::parseJointType(*p);
			DUMP1(("type=\"%s\"\n", type));
			Joint *j = 0;
			if (strcmp(type, "fixed") == 0) {
				j = new FixedJoint(name);
			} else if (strcmp(type, "ball") == 0) {
				j = new BallJoint(name);
			} else if (strcmp(type, "hinge") == 0) {
				j = new HingeJoint(name, Vector3d(0, 1, 0));
			}
			
			if (j) {
				m_joint = j;
			}
			XMLString::release(&type);
			/*
		} else if (strcmp(s, "limitOrientation") == 0) {
			double *v = XMLUtils::parseLimitOrientation(*p);
			if (m_joint) {
				delete m_joint;
			}
			m_joint = new HingeJoint(name, Vector3d(v[0], v[1], v[2]));
			*/
				
		} else if (strcmp(s, "translation") == 0) {
			double * values = XMLUtils::parseTranslation(*p, eval);
			DUMP1(("translation (%f, %f, %f)\n", values[0], values[1], values[2]));
			m_transform.curr().push(Vector3d(values[0], values[1], values[2]));

		} else if (strcmp(s, "rotation") == 0) {
			double *values = XMLUtils::parseRotation(*p);
			DUMP1(("rotation (%f, %f, %f, %f)\n", values[0], values[1], values[2], values[3]));
			Rotation rot;
			rot.setAxisAndAngle(values[0], values[1], values[2], values[3]);
			m_transform.curr().push(rot);
			
		} else if (strcmp(s, "axis") == 0) {
			double *values = XMLUtils::parseAxis(*p);
			DUMP1(("axis (%f, %f, %f)\n", values[0], values[1], values[2]));
			
			if (m_joint) {
				if (m_joint->type() == Joint::TYPE_HINGE) {
					HingeJoint *hinge = static_cast<HingeJoint*>(m_joint);
					hinge->setAxis(values[0], values[1], values[2]);
				} else {
					DUMP1(("not hinge type joint. axis ingored\n"));
				}
			} else {
				DUMP1(("no joint type"));
			}
				

		} else if (strcmp(s, "children") == 0) {
			DUMP1(("JOINT TRANSFORM TEST \n"));
			TRANSFORM_TEST(m_transform.curr());
			parseChildren(*p, eval);
		}
		
		p = p->getNextSibling();
		XMLString::release(&s);
	}
	{
		Transform &t = m_transform.curr();
		const Vector3d &v = t.translation();
		if (m_joint) {
			m_f.addJoint(m_joint);
			DUMP(("Joint : (%f, %f, %f)\n", v.x(), v.y(), v.z()));
			m_joint->setAnchor(v.x(), v.y(), v.z());
		}
	}
	m_transform.pop();

	char *strs[] = { name,};
	for (int i=0; i<ARRAY_SIZE(strs); i++) {
		char *p = strs[i];
		XMLString::release(&p);
	}
}
Ejemplo n.º 20
0
ASTNode::Link XMLParser::parseXMLNode(rapidxml::xml_node<>* node) {
  auto safeAttr = [node](std::string what, std::string defaultValue = "") -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else return defaultValue;
  };
  auto requiredAttr = [node](std::string what) -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else throw XMLParseError("Can't find required attribute", {
      METADATA_PAIRS,
      {"missing attribute", what}
    });
  };
  auto funArgs = [node, &safeAttr]() -> FunctionSignature::Arguments {
    FunctionSignature::Arguments args {};
    std::vector<std::string> stringArgs = split(safeAttr("args"), ',');
    for (auto& arg : stringArgs) {
      std::vector<std::string> namePlusTypes = split(arg, ':');
      std::vector<std::string> types = split(namePlusTypes[1], ' ');
      args.push_back(std::make_pair(namePlusTypes[0], TypeList(ALL(types))));
    }
    return args;
  };
  auto funRet = [node, &safeAttr]() -> TypeInfo {
    std::vector<std::string> returnTypes = split(safeAttr("return"), ' ');
    return returnTypes.size() == 0 ? nullptr : TypeInfo(TypeList(ALL(returnTypes)));
  };
  auto funBlock = [=](Node<FunctionNode>::Link f) {
    if (!f->isForeign()) {
      auto codeBlock = node->first_node("block");
      if (codeBlock == nullptr) throw XMLParseError("Method missing code block", {METADATA_PAIRS});
      f->setCode(Node<BlockNode>::staticPtrCast(parseXMLNode(codeBlock)));
    }
  };
  auto getVisibility = [node, &safeAttr]() -> Visibility {
    return fromString(safeAttr("visibility", "private"));
  };
  auto boolAttr = [node, &safeAttr](std::string what) -> bool {
    return safeAttr(what, "false") == "true";
  };

  if (node == nullptr) throw XMLParseError("Null node", {METADATA_PAIRS});
  std::string name = node->name();
  if (name == "block") {
    std::string type = safeAttr("type", "code");
    BlockType bt =
      type == "root" ? ROOT_BLOCK :
      type == "if" ? IF_BLOCK :
      type == "function" ? FUNCTION_BLOCK : CODE_BLOCK;
    auto block = Node<BlockNode>::make(bt);
    parseChildren(node, block);
    return block;
  } else if (name == "return") {
    auto retNode = Node<ReturnNode>::make();
    auto val = node->first_node("expr");
    if (val != nullptr) retNode->setValue(Node<ExpressionNode>::dynPtrCast(parseXMLNode(val)));
    return retNode;
  } else if (name == "expr") {
    TokenType tokenType = TT::findByPrettyName(requiredAttr("type"));
    std::string data = requiredAttr("value");
    std::unique_ptr<Token> content;
    if (tokenType == TT::OPERATOR) {
      content = std::make_unique<Token>(tokenType, Operator::find(data), defaultTrace);
    } else {
      content = std::make_unique<Token>(tokenType, data, defaultTrace);
    }
    auto expr = Node<ExpressionNode>::make(*content);
    parseChildren(node, expr);
    return expr;
  } else if (name == "decl") {
    Node<DeclarationNode>::Link decl;
    std::string ident = requiredAttr("ident");
    bool isDynamic = boolAttr("dynamic");
    if (isDynamic) {
      decl = Node<DeclarationNode>::make(ident, TypeList {});
    } else {
      std::string tlValue = requiredAttr("types");
      auto vec = split(tlValue, ' ');
      decl = Node<DeclarationNode>::make(ident, TypeList(ALL(vec)));
    }
    auto expr = node->first_node("expr");
    if (expr != nullptr) {
      decl->setInit(Node<ExpressionNode>::dynPtrCast(parseXMLNode(expr)));
    }
    return decl;
  } else if (name == "branch") {
    auto branch = Node<BranchNode>::make();
    auto cond = node->first_node();
    if (cond == nullptr) throw XMLParseError("Missing condition in branch", {METADATA_PAIRS});
    branch->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    auto success = cond->next_sibling();
    if (success == nullptr) throw XMLParseError("Missing success node in branch", {METADATA_PAIRS});
    branch->setSuccessBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(success)));
    auto blockFailiure = success->next_sibling("block");
    if (blockFailiure != nullptr) {
      branch->setFailiureBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(blockFailiure)));
    }
    auto branchFailiure = success->next_sibling("branch");
    if (branchFailiure != nullptr) {
      branch->setFailiureBlock(Node<BranchNode>::dynPtrCast(parseXMLNode(branchFailiure)));
    }
    return branch;
  } else if (name == "loop") {
    auto loop = Node<LoopNode>::make();
    auto init = node->first_node("loop_init");
    if (init != nullptr) {
      loop->setInit(Node<DeclarationNode>::dynPtrCast(parseXMLNode(init)));
    }
    auto cond = node->first_node("loop_condition");
    if (cond != nullptr) {
      loop->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    }
    auto update = node->first_node("loop_update");
    if (update != nullptr) {
      loop->setUpdate(Node<ExpressionNode>::dynPtrCast(parseXMLNode(update)));
    }
    auto code = node->first_node("block");
    if (code != nullptr) {
      loop->setCode(Node<BlockNode>::dynPtrCast(parseXMLNode(code)));
    }
    return loop;
  } else if (name == "loop_init" || name == "loop_condition" || name == "loop_update") {
    return parseXMLNode(node->first_node());
  } else if (name == "break") {
    return Node<BreakLoopNode>::make();
  } else if (name == "function") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto n = Node<FunctionNode>::make(ident, FunctionSignature(funRet(), funArgs()), isForeign);
    funBlock(n);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign function", {METADATA_PAIRS});
    return n;
  } else if (name == "type") {
    std::string typeName = requiredAttr("name");
    std::vector<std::string> inheritTypes = split(safeAttr("inherits"), ' ');
    auto typeNode = Node<TypeNode>::make(typeName, TypeList(ALL(inheritTypes)));
    parseChildren(node, typeNode);
    return typeNode;
  } else if (name == "member") {
    std::string ident = requiredAttr("ident");
    std::vector<std::string> types = split(safeAttr("types"), ' ');
    auto member = Node<MemberNode>::make(ident, TypeList(ALL(types)), boolAttr("static"), getVisibility());
    auto init = node->first_node("expr");
    if (init != nullptr) {
      member->setInit(Node<ExpressionNode>::staticPtrCast(parseXMLNode(init)));
    }
    return member;
  } else if (name == "method") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto method = Node<MethodNode>::make(ident, FunctionSignature(funRet(), funArgs()), getVisibility(), boolAttr("static"), isForeign);
    funBlock(method);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign method", {METADATA_PAIRS});
    return method;
  } else if (name == "constructor") {
    auto constructor = Node<ConstructorNode>::make(funArgs(), getVisibility());
    funBlock(constructor);
    return constructor;
  }
  throw XMLParseError("Unknown type of node", {METADATA_PAIRS, {"node name", name}});
}
Ejemplo n.º 21
0
    //---------------------------------------------------------------------
    void OverlayManager::parseScript(DataStreamPtr& stream, const String& groupName)
    {
		// check if we've seen this script before (can happen if included 
		// multiple times)
		if (!stream->getName().empty() && 
			mLoadedScripts.find(stream->getName()) != mLoadedScripts.end())
		{
			LogManager::getSingleton().logMessage( 
				"Skipping loading overlay include: '"
				+ stream->getName() + " as it is already loaded.");
			return;
		}
	    String line;
	    Overlay* pOverlay = 0;
		bool skipLine;

	    while(!stream->eof())
	    {
			bool isATemplate = false;
			skipLine = false;
		    line = stream->getLine();
		    // Ignore comments & blanks
		    if (!(line.length() == 0 || line.substr(0,2) == "//"))
		    {
				if (line.substr(0,8) == "#include")
				{
                    vector<String>::type params = StringUtil::split(line, "\t\n ()<>");
                    DataStreamPtr includeStream = 
                        ResourceGroupManager::getSingleton().openResource(
                            params[1], groupName);
					parseScript(includeStream, groupName);
					continue;
				}
			    if (!pOverlay)
			    {
				    // No current overlay

					// check to see if there is a template
					if (line.substr(0,8) == "template")
					{
						isATemplate = true;
					}
					else
					{
						// So first valid data should be overlay name
						if (StringUtil::startsWith(line, "overlay "))
						{
							// chop off the 'particle_system ' needed by new compilers
							line = line.substr(8);
						}
						pOverlay = create(line);
						pOverlay->_notifyOrigin(stream->getName());
						// Skip to and over next {
						skipToNextOpenBrace(stream);
						skipLine = true;
					}
			    }
			    if ((pOverlay && !skipLine) || isATemplate)
			    {
				    // Already in overlay
                    vector<String>::type params = StringUtil::split(line, "\t\n ()");

				    if (line == "}")
				    {
					    // Finished overlay
					    pOverlay = 0;
				    }
				    else if (parseChildren(stream,line, pOverlay, isATemplate, NULL))
				    {

				    }
				    else
				    {
					    // Attribute
						if (!isATemplate)
						{
							parseAttrib(line, pOverlay);
						}
				    }
			    }
		    }
	    }

		// record as parsed
		mLoadedScripts.insert(stream->getName());

    }