summaryrefslogtreecommitdiff
path: root/src/smlnode.cpp
blob: e2f8a74f9b6c8ec1a4b616b6a18d82d877d5dbc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include "smlnode.h"

#include <bu/sio.h>

using namespace Bu;

SmlNode::SmlNode( Type eType, const Bu::String &sText, SmlNode *pParent ) :
	eType( eType ),
	sText( sText ),
	pParent( pParent )
{
}

SmlNode::~SmlNode()
{
	for( SmlNodeList::iterator i = lChildren.begin(); i; i++ )
	{
		delete *i;
	}
}

SmlNode *SmlNode::parse( const Bu::String &sSrc )
{
	SmlNode *pRoot = new SmlNode( SmlNode::typeRoot );
	SmlNode *pCur = pRoot;
	pRoot->eType = typeRoot;

	enum Mode
	{
		mText,
		mStartTag,
		mEndTag,
	};
	Bu::String sTmp;
	Mode mode = mText;
	for( Bu::String::const_iterator i = sSrc.begin(); i; i++ )
	{
		if( *i == '\\' )
		{
			i++;
			if( !i )
				sTmp += '\\';
			else if( *i == '[' || *i == ']' || *i == '<' || *i == '>' )
				sTmp += *i;
		}
		else if( *i == '[' && mode == mText )
		{
			if( !sTmp.isEmpty() )
				pCur->append( typeText, sTmp );
			sTmp.clear();
			mode = mStartTag;
		}
		else if( *i == '<' && mode == mText )
		{
			if( !sTmp.isEmpty() )
				pCur->append( typeText, sTmp );
			sTmp.clear();
			mode = mEndTag;
		}
		else if( *i == '>' && mode == mStartTag )
		{
			pCur = pCur->append( typeTag, sTmp );
			sTmp.clear();
			mode = mText;
		}
		else if( *i == ']' && mode == mStartTag )
		{
			pCur->append( typeTag, sTmp );
			sTmp.clear();
			mode = mText;
		}
		else if( *i == ']' && mode == mEndTag )
		{
			if( sTmp != pCur->getText() )
				throw Bu::ExceptionBase("Tag mismatch: [%s> != <%s]\n",
					pCur->getText().getStr(), sTmp.getStr() );
			pCur = pCur->getParent();
			sTmp.clear();
			mode = mText;
		}
		else
		{
			sTmp += *i;
		}
	}
	if( !sTmp.isEmpty() )
		pCur->append( typeText, sTmp );

	return pRoot;
}

SmlNode *SmlNode::append( SmlNode::Type eType, const Bu::String &sText )
{
	SmlNode *pChild = new SmlNode( eType, sText, this );
	lChildren.append( pChild );
	return pChild;
}

Bu::Formatter &operator<<( Bu::Formatter &f, const SmlNode &n )
{
	switch( n.eType )
	{
		case SmlNode::typeRoot:
			f.incIndent();
			f << "Root {" << f.nl;
			break;

		case SmlNode::typeText:
			return f << "Text: >>" << n.sText << "<<" << f.nl;
			break;
			
		case SmlNode::typeTag:
			f.incIndent();
			f << "Tag[" << n.sText << "] {" << f.nl;
			break;
	}

	for( SmlNode::SmlNodeList::const_iterator i = n.lChildren.begin(); i; i++ )
	{
		f << *(*i);
	}
	f.decIndent();
	f << "}" << f.nl;

	return f;
}