xml.cpp 44.2 KB
Newer Older
1
2
3
4
5
#ifdef _MSC_VER //kill some warnings
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "inmost.h"
#include <stdarg.h> //for va_list
Kirill Terekhov's avatar
Kirill Terekhov committed
6
7
//#define WAITNL {printf("Press enter..."); scanf("%*c");}
#define WAITNL {}
8
9
10

namespace INMOST
{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
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
	static std::string GetFolder(std::string file)
	{
		size_t found = file.find_last_of("/\\");
		if( found == std::string::npos )
			return "";
		else return file.substr(0,found);
	}

	static int get_priority(char c)
	{
		switch(c)
		{
		case '(': return 0;
		case ')': return 1;
		case '+':
		case '-': return 8;
		case '*':
		case '/': return 9;
		case '~': return 10;
		default: return -1;
		}
	}

	static int ConvertHex(char in)
	{
		int ret = tolower(in) - 48;
		if( ret > 10 ) ret -= 7;
		if( ret > 15 ) ret -= 32;
		return ret;
	}
	static char atoc(const char * str)
	{
		return (char)(ConvertHex(str[0])*16 + ConvertHex(str[1]));
	}

	std::string CharToHex(char c)
	{
		char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F'};
		std::string str = "";
		str.append(&hex[(c & 0xF0) >> 4], 1);
		str.append(&hex[c & 0xF], 1);
		return str;
	}
54
55

#if defined(USE_MESH)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
	std::string ReferenceToString(INMOST::HandleType h, int pos)
	{

		std::stringstream ret;
		switch(INMOST::GetHandleElementType(h))
		{
		case INMOST::NODE: ret << "Node:"; break;
		case INMOST::EDGE: ret << "Edge:"; break;
		case INMOST::FACE: ret << "Face:"; break;
		case INMOST::CELL: ret << "Cell:"; break;
		case INMOST::ESET: ret << "Set:"; break;
		case INMOST::MESH: ret << "Mesh:"; break;
		}
		ret << pos;//INMOST::GetHandleID(h);
		return ret.str();
	}
72
73
#endif

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
74
75
76
77
78
79
80
81
82
	static char * sstrip(char * str)
	{
		int text_start = 0, text_end = (int)strlen(str);
		for(text_start = 0; isspace(str[text_start]) && text_start < text_end; text_start++);
		if( text_start == text_end ) return str+text_start;
		for(text_end = text_end-1; isspace(str[text_end]) && text_end > text_start; text_end--);
		str[text_end+1] = '\0';
		return str+text_start;
	}
83

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
84
85
	static std::string sstrip(const std::string & input)
	{
86

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
87
88
89
90
		char temp[2048];
		strcpy(temp,input.c_str());
		return std::string(sstrip(temp));
	}
91
92
93


#if defined(USE_AUTODIFF)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
	std::string VariableToString(INMOST::Storage::var v)
	{
		std::stringstream ret;
		const INMOST::Sparse::Row & r = v.GetRow();
		ret << "(";
		ret << v.GetValue() << ";";
		ret << r.Size();
		if( !r.Empty() )
		{
			ret << ";";
			for(int q = 0; q < (int)r.Size()-1; ++q)
			{
				ret << r.GetValue(q) << ";";
				ret << r.GetIndex(q) << ";";
			}
			ret << r.GetValue(r.Size()-1) << ";";
			ret << r.GetIndex(r.Size()-1);
		}
		ret << ")";
		return ret.str();
	}
115
116
#endif

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
117
118
119
120
121
	std::vector<std::string> XMLReader::Interpreter::Expand(const std::string & input) const
	{
		std::vector<std::string> ret;
		std::string put;
		for(int k = 0; k < (int)input.length(); ++k)
Kirill Terekhov's avatar
Kirill Terekhov committed
122
		{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
123
			if( get_priority(input[k]) != -1 )
Kirill Terekhov's avatar
Kirill Terekhov committed
124
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
125
126
127
128
129
130
				if( !put.empty() ) 
				{
					ret.push_back(put);
					put.clear();
				}
				ret.push_back(std::string(1,input[k]));
Kirill Terekhov's avatar
Kirill Terekhov committed
131
			}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
			else put.push_back(input[k]);
		}
		if( !put.empty() ) ret.push_back(put);
		return ret;
	}



	std::vector<std::string> XMLReader::Interpreter::MakePolish(const std::vector<std::string> & input) 
	{
		std::vector<std::string> stack, ret;
		int priority;
		for(int k = 0; k < (int)input.size(); ++k)
		{
			if( input[k].size() == 1 && (priority = get_priority(input[k][0])) != -1 )
Kirill Terekhov's avatar
Kirill Terekhov committed
147
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
				char op = input[k][0];
				if( op != '(' )
				{
					while(!stack.empty() && priority <= get_priority(stack.back()[0]) )
					{
						ret.push_back(stack.back());
						stack.pop_back();
					}
				}
				if( op == ')' )
				{
					if( stack.empty() )
					{
						std::cout << "Warning: parentheses unbalanced" << std::endl;
						error_state = true;
						break;
					}
					else if( stack.back()[0] == '(' )
						stack.pop_back();
					else 
					{
						std::cout << "Warning: expected left bracket" << std::endl;
						error_state = true;
						break;
					}
				}
				else if( op == '-' && (k == 0 || (input[k-1].size() == 1 && get_priority(input[k-1][0]) != -1)) ) //unary minus
					stack.push_back("~");
				else
					stack.push_back(input[k]);
			}
			else ret.push_back(input[k]);
		}
		while(!stack.empty())
		{
			ret.push_back(stack.back());
			stack.pop_back();
		}
		return ret;
	}
	void XMLReader::Interpreter::Print(const std::vector<std::string> & polish) const
	{
		for(int k = 0; k < (int)polish.size(); ++k)
			std::cout << polish[k] << " ";
		std::cout << std::endl;
	}
	double XMLReader::Interpreter::Run(const std::vector<std::string> & polish)
	{
		std::vector<double> stack;
		for(int k = 0; k < (int)polish.size(); ++k)
		{
			if( polish[k].size() == 1 && get_priority(polish[k][0]) != -1 )
			{
				double larg, rarg;
				char op = polish[k][0];
				switch(op)
				{
				case '+':
					if( stack.size() < 2 )
					{
						std::cout << "Less then two arguments in stack for + operand" << std::endl;
						error_state = true;
						return 1.0e+20;
					}
					rarg = stack.back();
					stack.pop_back();
					larg = stack.back();
					stack.pop_back();
					stack.push_back(larg+rarg);
					break;
				case '-':
					if( stack.size() < 2 )
					{
						std::cout << "Less then two arguments in stack for - operand" << std::endl;
						error_state = true;
						return 1.0e+20;
					}
					rarg = stack.back();
					stack.pop_back();
					larg = stack.back();
					stack.pop_back();
					stack.push_back(larg-rarg);
					break;
				case '*':
					if( stack.size() < 2 ) 
					{
						std::cout << "Less then two arguments in stack for * operand" << std::endl;
						error_state = true;
						return 1.0e+20;
					}
					rarg = stack.back();
					stack.pop_back();
					larg = stack.back();
					stack.pop_back();
					stack.push_back(larg*rarg);
					break;
				case '/':
					if( stack.size() < 2 ) 
					{
						std::cout << "Less then two arguments in stack for / operand" << std::endl;
						error_state = true;
						return 1.0e+20;
					}
					rarg = stack.back();
					stack.pop_back();
					larg = stack.back();
					stack.pop_back();
					stack.push_back(larg/rarg);
					break;
				case '~':
					if( stack.size() < 1 ) 
					{
						std::cout << "No arguments in stack for unary minus operand" << std::endl;
						error_state = true;
						return 1.0e+20;
					}
					larg = stack.back();
					stack.pop_back();
					stack.push_back(-larg);
					break;
				}
			}
			else stack.push_back(atof(polish[k].c_str()));
		}
		if( stack.size() != 1 )
		{
			std::cout << "There are more operands on stack, but no operators" << std::endl;
			error_state = true;
			return 1.0e+20;
		}
		return stack.back();
	}

	XMLReader::Interpreter::Interpreter() :error_state(false) {}
	XMLReader::Interpreter::Interpreter(const Interpreter & b) : error_state(b.error_state) {}
	XMLReader::Interpreter & XMLReader::Interpreter::operator = (Interpreter const & b)
	{
		error_state = b.error_state;
		return * this;
	}

	double XMLReader::Interpreter::Evaluate(const std::string & str)
	{
		//const char * debug_str = str.c_str();
		std::vector<std::string> decompose = Expand(str);
		std::vector<std::string> polish = MakePolish(decompose);
		//Print(polish);
		return Run(polish);
	}
	bool XMLReader::Interpreter::isError() {return error_state;}
	void XMLReader::Interpreter::ClearError() {error_state = false;}

	XMLReader::Stream & XMLReader::get_Stream() {return inp.back();}
	const XMLReader::Stream & XMLReader::get_Stream() const {return inp.back();}
	std::istream & XMLReader::get_iStream() {return *inp.back().s;}
	const std::istream & XMLReader::get_iStream() const {return *inp.back().s;}

305
306
    XMLReader::XMLReader(const XMLReader & other) {(void)other;}
    XMLReader & XMLReader::operator =(XMLReader & other) {(void)other; return *this;}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

	char XMLReader::GetChar()
	{
		char c = '\0';
		get_iStream().get(c);
		get_Stream().hadlinebreak = get_Stream().linebreak;
		get_Stream().hadlinechar = get_Stream().linechar;
		if( c == '\n' ) 
		{
			++get_Stream().linebreak;
			get_Stream().linechar = 0;
		}
		else ++get_Stream().linechar;
		if( get_iStream().eof() ) 
		{
			if( inp.size() > 1 )
			{
				PopStream();
				c = GetChar();
			}
			else
				_state = EndOfFile;
		}
		if( get_iStream().fail() )
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
332
			Report("Stream failed while getting the char, state %s",StateName(_state).c_str());
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
			WAITNL;
			_state = Failure;
		}
		return c;
	}

	void XMLReader::RetChar()
	{
		get_Stream().linebreak = get_Stream().hadlinebreak;
		get_Stream().linechar = get_Stream().hadlinechar;
		get_iStream().unget();
		if( get_iStream().fail() ) 
		{
			Report("Stream failed while ungetting the char");
			WAITNL;
			_state = Failure;
		}
	}
	void XMLReader::SkipComments(State RetState)
	{
		int ntmp = 0;
		char tmp[3] = {'\0','\0','\0'};
		char c;
		bool done = false;
		if( _state == ReadCommentExclamation )
		{
			while(!done)
			{
				c = GetChar();
Kirill Terekhov's avatar
Kirill Terekhov committed
362
363
364
365
366
367
368
369
370
371
				if( _state == Failure )
				{
					Report("Unexpected failure while skipping comments");
					done = true;
				}
				else if( _state == EndOfFile )
				{
					Report("Unexpected end of file while skipping comments");
					done = true;
				}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
				tmp[ntmp] = c;
				if( tmp[ntmp] == '>' && tmp[(ntmp-1+3)%3] == '-' && tmp[(ntmp-2+3)%3] == '-' ) 
				{
					_state = RetState;
					done = true;
				}
				ntmp = (ntmp+1)%3;
			}
		}
		else if( _state == ReadCommentQuestion )
		{
			while(!done)
			{
				c = GetChar();
Kirill Terekhov's avatar
Kirill Terekhov committed
386
387
388
389
390
391
392
393
394
395
				if( _state == Failure )
				{
					Report("Unexpected failure while skipping comments");
					done = true;
				}
				else if( _state == EndOfFile )
				{
					Report("Unexpected end of file while skipping comments");
					done = true;
				}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
				tmp[ntmp] = c;
				if( tmp[ntmp] == '>' && tmp[(ntmp-1+2)%2] == '?' ) 
				{
					_state = RetState;
					done = true;
				}
				ntmp = (ntmp+1)%2;
			}
		}
		else 
		{
			Report("Unexpected state %s while reading comments",StateName(_state).c_str());
			_state = Failure; //What are we doing here?
		}
	}

	std::string XMLReader::StateName(State s) const
	{
		switch(s)
		{
		case Intro: return "Intro";
		case WaitTag: return "WaitTag";
		case ReadTag: return "ReadTag";
		case ReadCommentExclamation: return "ReadCommentExclamation";
		case ReadCommentQuestion: return "ReadCommentQuestion";
		case WaitAttribute: return "WaitAttribute";
		case ReadAttribute: return "ReadAttribute";
		case WaitAttributeValue: return "WaitAttributeValue";
		case ReadAttributeValue: return "ReadAttributeValue";
		case ReadAttributeValueQuote: return "ReadAttributeValueQuote";
		case EndTag: return "EndTag";

		case ReadVector: return "ReadVector";

		case WaitContentsOpen:  return "WaitContentsOpen";
		case WaitContents:  return "WaitContents";
		case ReadContents: return "ReadContents";
		case ReadContentsVector: return "ReadContentsVector";
		case ReadContentsMultiplier: return "ReadContentsMultiplier";
		case ReadContentsMultiplierSkopes: return "ReadContentsMultiplierSkopes";
		case ReadContentsQuotes: return "ReadContentsQuotes";
		case EndContents: return "EndContents";

		case WaitCloseTag: return "WaitCloseTag";
		case ReadCloseTagSlash: return "WaitCloseTagSlash";
		case ReadCloseTagName: return "WaitCloseTagName";
		case EndOfFile: return "EndOfFile";
		case Failure: return "Failure";
		};
		return "Unspecified";
	}


	void XMLReader::Report(const char * fmt, ...) const
	{ 
		std::cout << get_Stream().src << ":row:" << get_Stream().linebreak << ":col:" << get_Stream().linechar << " ";
		{
			char stext[16384];
			va_list ap;
			if ( fmt == NULL ) {std::cout << std::endl; return;}
			va_start(ap,fmt);
			vsprintf(stext,fmt,ap);
			va_end(ap);
			std::cout << stext;
		}
		std::cout << std::endl;
	}

	XMLReader::XMLReader(std::string sourcename, std::istream & input) :intrp(),_state(Intro)
	{
		Stream add;
		add.src = sourcename;
		add.linebreak = 0;
		add.linechar = 0;
		add.hadlinebreak = 0;
		add.hadlinechar = 0;
		add.s = &input;
		inp.push_back(add); verbose = 0;
		if( get_iStream().fail() )
		{
			Report("Got a bad stream on input in %s",__FUNCTION__);
		}
	}

	void XMLReader::PushStream(std::string file) 
	{
		Stream add;
		add.linebreak = 0;
		add.linechar = 0;
		add.hadlinebreak = 0;
		add.hadlinechar = 0;
		add.src = file;
		add.s = new std::fstream(file.c_str(),std::ios::in);
		inp.push_back(add);
		if( get_iStream().fail() )
		{
			Report("Got a bad stream on input in %s",__FUNCTION__);
		}
	}
	void XMLReader::PopStream() 
	{
		if( inp.size() > 1 )
			delete static_cast<std::fstream *>(inp.back().s);
		inp.pop_back();
		if( _state == EndOfFile && !inp.empty() )
			_state = Intro;
	}

	bool XMLReader::ExpectOpenTag()
	{
		char c;
		bool done = false;
		if( !(_state == Intro) )
		{
			Report("Cannot expect open tag from state %s",StateName(_state).c_str());
			_state = Failure;
			return "";
		}
		while(!done)
		{
			c = GetChar(); 
			switch(_state)
			{
			case Intro:
				if( c == '<' )
				{
					if( verbose > 1 ) Report("info: encountered expected '<' symbol");
					_state = WaitTag;
					return true;
				}
				else if(!isspace(c))
				{
Kirill Terekhov's avatar
Kirill Terekhov committed
528
					if( verbose > 1 ) Report("info: encountered %x instead of expected '<'(%x) symbol",c,'<');
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
					RetChar();
					return false;
				}
				break;
			case EndOfFile: Report("Unexpected end of file while reading XML tag name"); done = true; break;
			case Failure: Report("Unrecoverable error while reading XML tag name"); done = true; break;
			default: Report("Unexpected state %s",StateName(_state).c_str()); done = true; break;
			}
		}
		return false;
	}

	std::string XMLReader::ReadOpenTag()
	{
		std::string ret;
		char c;
		bool done = false;
		if( !(_state == Intro || _state == WaitTag) )
		{
			Report("Cannot open tag from state %s",StateName(_state).c_str());
			_state = Failure;
			return "";
		}
		while(!done)
		{
			c = GetChar(); 
			switch(_state)
			{
			case Intro:
				if( c == '<' ) 
				{
					if( verbose > 1 ) Report("info: waiting tag name");
					_state = WaitTag;
				}
				else if( !isspace(c) ) //do not expect anything except for spacing
				{
					Report("Unexpected text character %c",c);
					_state = Failure;
					done = true;
				}
				break;
			case WaitTag:
				if( c == '?' ) 
				{
					if( verbose > 1 ) Report("info: skipping comments");
					_state = ReadCommentQuestion;
					SkipComments(WaitTag);
				}
				else if( c == '!' ) //can be ![CDATA[
				{
					c = GetChar(); //check next character
					if( c == '-' ) //this is going to be comment
					{
						c = GetChar(); //check next character
						if( c == '-' )
						{
							if( verbose > 1 ) Report("info: skipping comments");
							_state = ReadCommentExclamation;
							SkipComments(WaitTag);
						}
						else Report("unexpected character %c while reading comment",c);
					}
					else if( c == '[' ) // this is ![CDATA[
					{
						if( verbose > 1 ) Report("info: reading ![CDATA[");
						ret.push_back('!');
						ret.push_back(c);
						_state = ReadTag;
					}
					else Report("unexpected character %c while reading comment or ![CDATA[ block",c);
				}
				else if( c == '/' )
				{
					if( verbose > 1 ) Report("info: encountered closing slash");
					RetChar();
					_state = ReadCloseTagSlash;
					done = true;
				}
				else if( isalpha(c) )
				{
					if( verbose > 1 ) Report("info: reading tag name");
					ret.push_back(c);
					_state = ReadTag;
				}
				break;
			case ReadTag:
				if( isspace(c) ) 
				{
					if( verbose > 1 ) Report("info: waiting attribute name");
					done = true;
					_state = WaitAttribute;
				}
				else if( c == '/' || c == '>' )
				{
					if( verbose > 1 ) Report("info: tag ended");
					RetChar(); //push character back to the stream
					done = true;
					_state = EndTag;
				}
				else if( isalpha(c) || (!ret.empty() && isprint(c)) )
				{
					ret.push_back(c);
					if( ret == "![CDATA[" )
					{
						done = true;
						_state = EndTag;
					}
				}
				else Report("unexpected character %c in XML tag name",c);
				break;
			case EndOfFile: Report("Unexpected end of file while reading XML tag name"); done = true; break;
			case Failure: Report("Unrecoverable error while reading XML tag name"); done = true; break;
			default: Report("Unexpected state %s",StateName(_state).c_str()); done = true; break;
			}
		}
		if( verbose > 1 ) Report("info: opened tag %s",ret.c_str());
		return ret;
	}
	int XMLReader::ReadCloseTag()
	{
		char tmp[2];
		tmp[0] = GetChar();
		if( tmp[0] == '>' )
		{
			_state = Intro;
			if( verbose > 1 ) Report("info: closed tag");
			return 1; //tag was finished with >
		}
		else if( tmp[0] == '/' ) //close single stage tag
		{
			tmp[1] = GetChar();
			if( tmp[1] == '>' )
			{
				_state = Intro;
				if( verbose > 1 ) Report("info: closed tag");
				return 2; //tag was halted with />
			}
Kirill Terekhov's avatar
Kirill Terekhov committed
666
			Report("Encountered %x%x while expecting '/>'(%x%x) for tag closing",tmp[0],tmp[1],'/','>');
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
667
		}
Kirill Terekhov's avatar
Kirill Terekhov committed
668
		Report("Encountered %x while expecting '>'(%x) for tag closing",tmp[0],'>');
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
		_state = Failure;
		return 0;
	}
	bool XMLReader::isTagFinish() const {return _state == ReadCloseTagSlash;}

	bool XMLReader::ReadFinishTag(std::string TagName)
	{
		std::string name;
		bool done = false;
		char c;
		if( !(_state == Intro || _state == ReadCloseTagSlash) )
		{
			Report("Cannot read finish tag from state %s",StateName(_state).c_str());
			_state = Failure;
			return false;
		}
		if( _state == Intro ) _state = WaitCloseTag;
		while(!done)
		{
			c = GetChar();  
			switch(_state)
			{
			case WaitCloseTag:
				if( isspace(c) ) continue;
				if( c != '<' )
				{
					Report("Expected '<' instead of %c",c);
					_state = Failure;
					return false;
				}
				else _state = ReadCloseTagSlash;
				break;
			case ReadCloseTagSlash:
				if( c == '?' )
				{
					if( verbose > 1 ) Report("info: skipping comments");
					_state = ReadCommentQuestion;
					SkipComments(WaitCloseTag);
				}
				else if( c == '!' )
				{
					if( verbose > 1 ) Report("info: skipping comments");
					_state = ReadCommentExclamation;
					SkipComments(WaitCloseTag);
				}
				else if( c != '/' )
				{
					Report("Expected '/' instead of %c",c);
					_state = Failure;
					return false;
				}
				else _state = ReadCloseTagName;
				break;
			case ReadCloseTagName:
				if( c == '>' ) done = true;
				else if( isalpha(c) || (!name.empty() && isprint(c)) ) name.push_back(c);
				else Report("Unexpected symbol %c in tag name",c);
				break;
			case EndOfFile:
				Report("Unexpected end of file while searching for </%s>",TagName.c_str());
Kirill Terekhov's avatar
Kirill Terekhov committed
729
				return false;
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
730
731
732
733
734
			case Failure:
				Report("Unexpected failure while searching for </%s>",TagName.c_str());
				return false;
			default: Report("Unexpected state %s",StateName(_state).c_str()); return false;

Kirill Terekhov's avatar
Kirill Terekhov committed
735
736
			}
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
737
738
739
		if( verbose > 1 ) Report("info: finished tag %s",name.c_str());
		_state = Intro;
		return name == TagName;
Kirill Terekhov's avatar
Kirill Terekhov committed
740
	}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
741
742
743
744
745
746
747
748

	std::string XMLReader::AttributeName()
	{
		std::string ret;
		bool done = false;
		char c;
		if( _state == EndTag ) return "";
		if( _state != WaitAttribute )
Kirill Terekhov's avatar
Kirill Terekhov committed
749
750
751
752
		{
			Report("Attribute name was not expected, state %s",StateName(_state).c_str());
			done = true;
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
753
754
755
756
		while(!done)
		{
			c = GetChar();
			switch(_state)
Kirill Terekhov's avatar
Kirill Terekhov committed
757
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
			case WaitAttribute:
				if( isspace(c) ) continue;
				else if( c == '<' )
				{
					c = GetChar();
					if( c == '?' )
					{
						if( verbose > 1 ) Report("info: skipping comments");
						_state = ReadCommentQuestion;
						SkipComments(WaitAttribute);
					}
					else if( c == '!' )
					{
						if( verbose > 1 ) Report("info: skipping comments");
						_state = ReadCommentExclamation;
						SkipComments(WaitAttribute);
					}
					else 
					{
						Report("Expected a comment, got '<%c'",c);
						_state = Failure;
						done = true;
					}
				}
				else if( isalpha(c) ) 
				{
					if( verbose > 1 ) Report("info: reading attribute name");
					ret.push_back(c);
					_state = ReadAttribute;
				}
				else if( c == '>' || c == '/' )
				{
					if( verbose > 1 ) Report("info: tag ended");
					RetChar();
					done = true;
					_state = EndTag;
				}
				break;
			case ReadAttribute:
Kirill Terekhov's avatar
Kirill Terekhov committed
797
				if( c == '=' || isspace(c) ) 
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
798
799
800
801
802
				{
					if( c == '=' ) RetChar();
					_state = WaitAttributeValue;
					done = true;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
803
				else if( isalpha(c) ) ret.push_back(c);
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
				else 
				{
					Report("Unexpected symbol %c while reading attribute name",c);
					_state = Failure;
					done = true;
				}
				break;
			case EndOfFile:
				Report("Unexpected end of file while reading attribute name");
				done = true;
				break;
			case Failure:
				Report("Unexpected failure while reading attribute name");
				done = true;
				break;
			default: Report("Unexpected state %s",StateName(_state).c_str()); done = true; break;
			}
		}
		if( verbose > 1 ) Report("info: attribute name %s",ret.c_str());
		return ret;
	}

	std::string XMLReader::AttributeValue()
	{
		std::string ret;
		bool done = false;
		char c;
		if( _state == EndTag ) return "";
		if( _state != WaitAttributeValue )
Kirill Terekhov's avatar
Kirill Terekhov committed
833
834
835
836
		{
			Report("Attribute value was not expected, state %s",StateName(_state).c_str());
			done = true;
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
		while(!done)
		{
			c = GetChar();
			switch(_state)
			{
			case WaitAttributeValue:
				if( isspace(c) ) continue;
				else if( c == '=' )
				{
					if( verbose > 1 ) Report("info: reading attribute value");
					_state = ReadAttributeValue;
				}
				else if( c == '>' || c == '/' )
					Report("Unexpected end of XML tag while searching for '='");
				else Report("Unexpected character %c while searching for '='",c);
				break;
			case ReadAttributeValue:
Kirill Terekhov's avatar
Kirill Terekhov committed
854
855
				if( isspace(c) && ret.empty() ) continue;
				else if( c == '"' && ret.empty() ) 
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
				{
					if( verbose > 1 ) Report("info: reading attribute value in quotes");
					_state = ReadAttributeValueQuote;
				}
				else if( c == '>' || c =='/' )
				{
					if( verbose > 1 ) Report("info: end of tag");
					_state = EndTag;
					done = true;
				}
				else if( !isspace(c) ) ret.push_back(c);
				else if( isspace(c) )
				{
					if( verbose > 1 ) Report("info: end reading attribute value");
					_state = WaitAttribute;
					done = true;
				}
				else Report("Unexpected symbol %c while reading attribute value",c);
				break;
			case ReadAttributeValueQuote:
				if( c == '"' )
Kirill Terekhov's avatar
Kirill Terekhov committed
877
				{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
878
879
880
					if( verbose > 1 ) Report("info: end reading attribute value");
					_state = WaitAttribute;
					done = true;
Kirill Terekhov's avatar
Kirill Terekhov committed
881
				}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
				else if( !isprint(c) )
				{
					Report("Unprintable character %x encountered",c);
					_state = Failure;
					done = true;
				}
				else ret.push_back(c);
				break;
			case EndOfFile:
				Report("Unexpected end of file while reading attribute name");
				done = true;
				break;
			case Failure:
				Report("Unexpected failure while reading attribute name");
				done = true;
				break;
			default: Report("Unexpected state %s",StateName(_state).c_str()); done = true; break;
			}
		}
		if( verbose > 1 ) Report("info: attribute value %s",ret.c_str());
		return ret;
	}

	bool XMLReader::isTagEnded() const {return _state == EndTag;}

	bool XMLReader::ReadOpenContents()
	{
		std::string tmp;
		bool done = false;
		char c;
		if( _state != Intro )
		{
			Report("Cannot read contents opening from state %s",StateName(_state).c_str());
			_state = Failure;
			return false;
		}
		_state = WaitContentsOpen;
		while(!done)
		{
			c = GetChar();
			if( isspace(c) ) continue;
			else if( c == '<' || c == '!' || c == '[' || c == 'C' || c == 'D' || c == 'A' || c == 'T' || c == '?' || c == '-' )
				tmp.push_back(c);
			else Report("Unexpected character %c while reading '<![CDATA['",c);
			if( tmp.size() == 2 && tmp == "<?" )
			{
				tmp.clear();
				if( verbose > 1 ) Report("info: skipping comments");
				_state = ReadCommentQuestion;
				SkipComments(WaitContentsOpen);
Kirill Terekhov's avatar
Kirill Terekhov committed
932
			}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
933
			else if( tmp.size() == 4 && tmp == "<!--" )
Kirill Terekhov's avatar
Kirill Terekhov committed
934
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
				tmp.clear();
				if( verbose > 1 ) Report("info: skipping comments");
				_state = ReadCommentExclamation;
				SkipComments(WaitContentsOpen);
			}
			else if( tmp.size() == 9 )
			{
				if( tmp == "<![CDATA[" ) 
				{
					if( verbose > 1 ) Report("info: contents intro was read");
					_state = WaitContents;
					done = true;
				}
				else
				{
					Report("Expected '<![CDATA[' but got '%s'",tmp.c_str());
					_state = Failure;
					done = true;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
954
			}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
955
956
957
958
959
960
961
962
963
964
965
966
		}
		return _state == WaitContents;
	}

	std::string XMLReader::GetContentsWord()
	{
		std::string ret;
		char c;
		bool done = false;
		int testend = 0;
		if( _state == EndContents ) return "";
		if( _state != WaitContents )
Kirill Terekhov's avatar
Kirill Terekhov committed
967
		{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
			Report("Cannot read contents from state %s",StateName(_state).c_str());
			_state = Failure;
			return "";
		}
		while(!done)
		{
			c = GetChar();
			/*
			if( !isprint(c) )
			{
			Report("Unprintable character %x on input",c);
			_state = Failure;
			break;
			}
			*/
			if( c == ']' && !(_state == ReadContentsQuotes) )
				testend++;
			else if( c == '>' && testend == 2 )
			{
				if( ret[ret.size()-2] == ']' && ret[ret.size()-1] == ']' )
				{
					ret.resize(ret.size()-2);
					RetChar(); //return '>'
					_state = EndContents;
					break;
				}
				else testend = 0;
			}
			switch(_state)
Kirill Terekhov's avatar
Kirill Terekhov committed
997
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
			case WaitContents:
				if( isspace(c) ) continue;
				if( c == '{' )
				{
					ret.push_back(c);
					_state = ReadContentsVector;
				}
				else if( c == '*' )
				{
					ret.push_back(c);
					_state = ReadContentsMultiplier;
				}
				else if( c == '"' )
				{
					ret.push_back(c);
					_state = ReadContentsQuotes;
				}
				else
				{
					ret.push_back(c);
					_state = ReadContents;
				}
				break;
			case ReadContents:
				if( isspace(c) )
				{
					done = true;
					_state = WaitContents;
				}
				else if( c == '*' )
				{
					ret.push_back(c);
					_state = ReadContentsMultiplier;
				}
				else ret.push_back(c);
				break;
			case ReadContentsVector:
				if( c == '}' )
				{
					ret.push_back(c);
					_state = ReadContents;
				}
				else if( !isspace(c) ) ret.push_back(c);
				break;
			case ReadContentsMultiplier:
				if( isspace(c) )
				{
					if( ret[ret.size()-1] != '*' ) //maybe user have put a space after the multiplier
					{
						done = true;
						_state = WaitContents;
					}
				}
				else if( c == '(' && ret[ret.size()-1] == '*' ) //expression for the skope
				{
					ret.push_back(c);
					_state = ReadContentsMultiplierSkopes;
				}
				else ret.push_back(c);
				break;
			case ReadContentsMultiplierSkopes:
				if( c == ')' ) //do not expect anything beyond that
				{
					ret.push_back(c);
					_state = WaitContents;
					done = true;
				}
				else if( !isspace(c) ) ret.push_back(c);
				break;
			case ReadContentsQuotes:
				if( c == '"' )
				{
					if( ret[ret.size()-1] == '\\' ) //this was a guarded quote
					{
						ret.resize(ret.size()-1); //remove guard
						ret.push_back(c); //put skope
					}
					else //may have a multiplier after the closing quote
					{
						ret.push_back(c);
						_state = ReadContents;
					}
				}
				else ret.push_back(c);
				break;
			case EndOfFile:
				Report("Unexpected end of file while reading attribute name");
Kirill Terekhov's avatar
Kirill Terekhov committed
1085
				done = true;
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1086
1087
1088
1089
1090
1091
				break;
			case Failure:
				Report("Unexpected failure while reading attribute name");
				done = true;
				break;
			default: Report("Unexpected state %s",StateName(_state).c_str()); done = true; break;
Kirill Terekhov's avatar
Kirill Terekhov committed
1092
1093
			}
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
		return ret;
	}
	bool XMLReader::ReadCloseContents()
	{
		if( _state == EndContents && GetChar() == '>' )
		{
			_state = Intro;
			return true;
		}
		return false;
	}

	bool XMLReader::isContentsEnded() const
	{
		return _state == EndContents;
	}

	bool XMLReader::isFailure() const {return _state == Failure;}

	bool XMLReader::isEof() const {return _state == EndOfFile;}
1114
1115

#if defined(USE_MESH)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
	INMOST::ElementType XMLReader::atoes(const char * _str)
	{
		INMOST::ElementType type = INMOST::NONE;
		std::string stype(_str);
		if( stype == "Cells" ) type = INMOST::CELL;
		else if( stype == "Edges" ) type = INMOST::EDGE;
		else if( stype == "Faces" ) type = INMOST::FACE;
		else if( stype == "Nodes" ) type = INMOST::NODE;
		else if( stype == "Sets" ) type = INMOST::ESET;
		else if( stype == "Mesh" ) type = INMOST::MESH;
		else if( stype == "None" ) type = INMOST::NONE;
		else Report("Unexpected keyword %s expected Nodes,Edges,Faces,Cells or Sets",_str);
		return type;
	}

	INMOST::ElementType XMLReader::atoe(const char * _str)
	{
		INMOST::ElementType type = INMOST::NONE;
		std::string stype(_str);
		if( stype == "Cell" ) type = INMOST::CELL;
		else if( stype == "Edge" ) type = INMOST::EDGE;
		else if( stype == "Face" ) type = INMOST::FACE;
		else if( stype == "Node" ) type = INMOST::NODE;
		else if( stype == "Set" ) type = INMOST::ESET;
		else if( stype == "Mesh" ) type = INMOST::MESH;
		else if( stype == "None" ) type = INMOST::NONE;
		else Report("Unexpected keyword %s expected Node,Edge,Face,Cell,Set or Mesh",_str);
		return type;
	}

	std::pair<INMOST::ElementType,int> XMLReader::atoh(const char * _str)
	{
		std::string str(_str);
		if( str == "None" ) return std::make_pair(INMOST::NONE,0);
		if( str == "None:0" ) return std::make_pair(INMOST::NONE,0);
		size_t dots = str.find(':');
		if( dots == std::string::npos ) return std::make_pair(INMOST::NONE,1);
		std::string stype = str.substr(0,dots);
		std::string offset = str.substr(dots+1,std::string::npos);
		INMOST::ElementType type = atoe(stype.c_str());
		int ioffset = atoi(offset.c_str());
		if( type == INMOST::NONE ) Report("Cannot understand element type %s",stype.c_str());
		return std::make_pair(type,ioffset);
	}

	std::pair<std::string,std::pair<INMOST::ElementType,int> > XMLReader::atorh(const char * _str)
	{
		std::string str(_str);
		if( str == "None" ) return std::make_pair("",std::make_pair(INMOST::NONE,0));
		if( str == ":None:0" ) return std::make_pair("",std::make_pair(INMOST::NONE,0));
		size_t dots1 = str.find(':');
		if( dots1 == std::string::npos ) return std::make_pair("",std::make_pair(INMOST::NONE,1));
		size_t dots2 = str.find(':',dots1+1);
		std::string meshname = str.substr(0,dots1);
		std::string stype = str.substr(dots1+1,dots2-dots1);
		std::string offset = str.substr(dots2+1,std::string::npos);
		INMOST::ElementType type = atoe(stype.c_str());
		int ioffset = atoi(offset.c_str());
		if( type == INMOST::NONE ) Report("Cannot understand element type %s",stype.c_str());
		return std::make_pair(meshname,std::make_pair(type,ioffset));
	}
1177
1178
1179
#endif

#if defined(USE_AUTODIFF)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1180
1181
1182
1183
	INMOST::Storage::var XMLReader::atov(const char * _str)
	{
		INMOST::Sparse::Row entries;
		INMOST::Storage::real val;
Kirill Terekhov's avatar
Kirill Terekhov committed
1184
		if( !(_str[0] == '(' && _str[strlen(_str)-1] == ')' ) ) Report("Expected scopes for variable %s",_str);
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
		std::string str(_str+1,strlen(_str)-2);
		std::vector<std::string> decomposed;
		ParseCommaSeparated(str,decomposed,';');
		if( decomposed.size() < 2 || decomposed.size()%2 != 0 ) Report("Malformed variable %s",_str);
		val = atof(decomposed[0].c_str());
		entries.Resize(atoi(decomposed[1].c_str()));
		if( decomposed.size()/2-1 != entries.Size() ) Report("Number of derivatives do not correspond to the number of entries %s",_str);
		for(int q = 2; q < (int)entries.Size(); q+=2)
		{
			entries.GetValue(q) = atof(decomposed[q].c_str());
			entries.GetIndex(q) = atoi(decomposed[q+1].c_str());
		}
		return INMOST::variable(val,entries);
	}
1199
1200
#endif

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
	int XMLReader::EvaluateExpression(std::string expression)
	{
		//port short RPN version later from DiscretizationToolkit/GPRS/interpreter.cpp
		return (int)intrp.Evaluate(expression);
		return atoi(expression.c_str()); //stupid version for now
	}

	int XMLReader::ConvertMultiplier(std::string expression, int SetSize)
	{
		if( !expression.empty() )
		{
			//replace SetSize with value
			std::stringstream conv;
			conv << SetSize;
			size_t pos = 0;
			while((pos = expression.find("SetSize",pos)) != std::string::npos )
			{
				expression.replace(pos,7,conv.str());
				pos += conv.str().size();
			}
			return EvaluateExpression(expression);
		}
		else return 1;
	}

	void XMLReader::SplitValueMultiplier(std::string expression, std::string & value, std::string & multiplier)
	{
		size_t mult = expression.find('*');
		if( mult != std::string::npos )
		{
			value = expression.substr(0,mult);
			multiplier = expression.substr(mult+1,std::string::npos);
		}
		else
		{
			value = expression;
			multiplier = "";
		}
	}

	bool XMLReader::ParseBool(std::string word)
	{
		bool ret = false;
		if( word == "False" || word == "false" || word == "0" || word == "no" || word == "N" || word == "No" || word == "NO" ) ret = false;
		else if( word == "True" || word == "true" || word == "1" || word == "yes" || word == "Y" || word == "Yes" || word == "YES" ) ret = true;
		else Report("Cannot understand boolean value %s",word.c_str());
		return ret;
	}

	void XMLReader::ParseCommaSeparated(std::string word, std::vector<std::string> & parsed, char symbol)
	{
		parsed.clear();
		size_t comma_prev = 0, comma;
		std::string substr;
		do
		{
			comma = word.find(symbol,comma_prev);
			substr = word.substr(comma_prev,comma-comma_prev);
			parsed.push_back(sstrip(substr));
			comma_prev = comma+1;
		} while( comma != std::string::npos );
	}
1263

1264
#if defined(USE_MESH)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
	void XMLReader::ParseReal(std::string word, std::vector<INMOST::Storage::real> & Vector, int & Repeat, int SetSize)
	{
		//const char * debug = word.c_str();
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		//const char * debug_value = value.c_str();
		//const char * debug_multiplier = multiplier.c_str();
		if( value[0] == '{' ) //multiple elements
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				//const char * debug_substr = substr.c_str();
				Vector.push_back(atof(substr.c_str()));
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else Vector.push_back(atof(value.c_str())); //single element

		Repeat = ConvertMultiplier(multiplier,SetSize);    
	}
1291

1292
#if defined(USE_AUTODIFF)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
	void XMLReader::ParseVariable(std::string word, std::vector<INMOST::Storage::var> & Vector, int & Repeat, int SetSize)
	{
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		if( value[0] == '{' ) //multiple elements
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				Vector.push_back(atov(substr.c_str()));
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else Vector.push_back(atov(value.c_str())); //single element

		Repeat = ConvertMultiplier(multiplier,SetSize);    
	}
1315
#endif
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
	void XMLReader::ParseInteger(std::string word, std::vector<INMOST::Storage::integer> & Vector, int & Repeat, int SetSize)
	{
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		if( value[0] == '{' ) //multiple elements
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				Vector.push_back(atoi(substr.c_str()));
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else Vector.push_back(atoi(value.c_str())); //single element

		Repeat = ConvertMultiplier(multiplier,SetSize);    
	}
1338
#endif
1339

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
	void XMLReader::ParseBulk(std::string word, std::string & Vector, int & Repeat, int SetSize)
	{
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		if( value[0] == '"' ) //just text
		{
			Vector.insert(0, value.c_str()+1, value.size()-2);
		}
		else if( value[0] == '{' ) //multiple elements
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				if( substr.size() != 2 )
					Report("Unexpected size %d of substring %s in vector, expected 2",substr.size(),substr.c_str());
				Vector.push_back(atoc(substr.c_str()));
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else if( value.size() >= 2 && value.size()%2 == 0 )
		{
			for(int k = 0; k < (int)value.size(); k+=2 )
				Vector.push_back(atoc(value.c_str()+k)); //single element
		}
		else Report("Unexpected size of input string %s size %d",value.c_str(),value.size());
		Repeat = ConvertMultiplier(multiplier,SetSize);
	}
1372

1373
#if defined(USE_MESH)
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
	void XMLReader::ParseReference(std::string word, std::vector<std::pair<INMOST::ElementType,int> > & Vector, int & Repeat, int SetSize)
	{
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		if( value[0] == '{' )
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				Vector.push_back(atoh(substr.c_str()));
				if( Vector.back().first == INMOST::NONE && Vector.back().second == 1 )
					Report("Cannot convert handle to the element, %s",substr.c_str());
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else 
		{
			Vector.push_back(atoh(value.c_str())); 
			if( Vector.back().first == INMOST::NONE && Vector.back().second == 1 )
				Report("Cannot convert handle to the element, %s",value.c_str());
		}

		Repeat = ConvertMultiplier(multiplier,SetSize);
	}

	void XMLReader::ParseRemoteReference(std::string word, std::vector< std::pair<std::string,std::pair<INMOST::ElementType,int> > > & Vector, int & Repeat, int SetSize)
	{
		std::string value, multiplier;
		SplitValueMultiplier(word,value,multiplier);
		Vector.clear();
		if( value[0] == '{' )
		{
			size_t comma_prev = 1, comma;
			std::string substr;
			do
			{
				comma = value.find(',',comma_prev);
				if( comma == std::string::npos ) comma = value.find('}',comma_prev);
				substr = value.substr(comma_prev,comma-comma_prev);
				Vector.push_back(atorh(substr.c_str()));
				if( Vector.back().first == "" )
					Report("Cannot extract mesh name, %s",substr.c_str());
				if( Vector.back().second.first == INMOST::NONE && Vector.back().second.second == 1 )
					Report("Cannot convert handle to the element, %s",substr.c_str());
				comma_prev = comma+1;
			} while( value[comma] != '}' );
		}
		else 
		{
			Vector.push_back(atorh(value.c_str())); 
			if( Vector.back().first == "" )
				Report("Cannot extract mesh name, %s",value.c_str());
			if( Vector.back().second.first == INMOST::NONE && Vector.back().second.second == 1 )
				Report("Cannot convert handle to the element, %s",value.c_str());
		}

		Repeat = ConvertMultiplier(multiplier,SetSize);
	}
1437
#endif
1438

Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450






	XMLReader::XMLTag XMLReader::OpenTag()
	{
		std::string include = "";
		XMLTag ret;
		XMLAttrib attr;
		bool istag = ExpectOpenTag();
Kirill Terekhov's avatar
Kirill Terekhov committed
1451
1452
1453
		if( _state == Failure || _state == EndOfFile )
			ret.finish = 0; //there is an error
		else if( !istag )
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
			ret.finish = 5; //there is no tag opening, probably pure text
		else
		{
			ret.name = ReadOpenTag();
			if( ret.name == "![CDATA[" )
			{
				if( verbose > 1 ) Report("info: opened data block");
				ret.finish = 4; //report that there is a data block
			}
			else
			{
				if( !isTagFinish() ) //have not encountered '</' of the root tag
				{
					if( verbose > 1 ) Report("info: reading tag attributes");
					attr.name = AttributeName();
Kirill Terekhov's avatar
Kirill Terekhov committed
1469
					while(!isTagEnded() && !isFailure() && !isEof())
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
					{
						attr.value = AttributeValue();
						if( attr.name == "Include" ) //some file was included
							include = attr.value;
						else ret.attributes.push_back(attr);
						attr.name = AttributeName();
					}
					if( verbose > 1 ) Report("info: finalized tag reading");
					ret.finish = ReadCloseTag(); //retrive '>'
					if( !include.empty() )
					{
						if( verbose > 1 ) Report("info: switching to stream %s",(GetFolder(get_Stream().src) + "/" + include).c_str());

						PushStream((GetFolder(get_Stream().src) + "/" + include).c_str()); //switch to the included file
					}
				}
				else //encountered '</' of the root tag, no tag was red
				{
					if( verbose > 1 ) Report("info: encountered finalization of tag '</'");
					ret.name = "";
					ret.finish = 3;
				}
			}
		}
		if( verbose > 1 ) Report("info: return tag %s flag %d",ret.name.c_str(),ret.finish);
		return ret;
	}

	bool XMLReader::CloseTag(XMLTag & tag)
Kirill Terekhov's avatar
Kirill Terekhov committed
1499
	{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1500
		if( tag.finish == 3 ) 
Kirill Terekhov's avatar
Kirill Terekhov committed
1501
		{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1502
1503
			Report("%s:%d Trying to close the tag that is beyond the last tag",__FILE__,__LINE__);
			return false;
Kirill Terekhov's avatar
Kirill Terekhov committed
1504
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1505
1506
		else if( tag.finish == 2 ) return true; //no need to read anything
		else if( tag.finish == 0 ) return false; //there was a Failure
Kirill Terekhov's avatar
Kirill Terekhov committed
1507
1508
		else
		{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
			if( verbose > 1 ) Report("info: going to finish tag %s",tag.name.c_str());
			return ReadFinishTag(tag.name);
		}
	}

	std::string XMLReader::ReadUntil(std::string stop)
	{
		char c;
		std::string ret;
		do
		{
			c = GetChar();
Kirill Terekhov's avatar
Kirill Terekhov committed
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
			if( _state == Failure )
			{
				Report("Unexpected failure while searching for %s",stop.c_str());
				break;
			}
			else if( _state == Failure )
			{
				Report("Unexpected end of file while searching for %s",stop.c_str());
				break;
			}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
			ret.push_back(c);
		}
		while( ret.size() < stop.size() || ret.substr(ret.size()-stop.size()) != stop );

		return ret;
	}



	int XMLReader::ReadXMLSub(XMLTree & root)
	{
		if( verbose )
		{
			Report("info: processing children of %s",root.GetName().c_str());
			WAITNL;
		}
		for(XMLTag t = OpenTag(); !t.Finalize(); t = OpenTag())
		{
			if( verbose )
			{
				Report("info: processing child %s of tag %s, flag %d",t.GetName().c_str(),root.GetName().c_str(),t.finish);
				WAITNL;
			}
			if( t.Finalize() )
			{
				if( verbose )
				{
					Report("info: finalize tag");
					WAITNL;
				}
				break;
			}
			else if( t.RawData() )
			{
				std::string data = ReadUntil("<"); //read until next tag opening
				data.resize(data.size()-1); //drop '<'
				//remove trailing spaces
				while( !data.empty() && isspace(data[data.size()-1]) ) data.resize(data.size()-1);
				if( verbose )
				{
					Report("info: encountered raw data, %s",data.c_str());
					WAITNL;
				}
				root.contents += data;
				RetChar(); //return '<' back into stream
				_state = Intro; //change state to read next tag
			}
			else if( t.BlockData() )
Kirill Terekhov's avatar
Kirill Terekhov committed
1579
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1580
1581
1582
1583
1584
1585
1586
1587
1588
				std::string data = ReadUntil("]]>");
				data.resize(data.size()-3); //drop ]]>
				if( verbose )
				{
					Report("info: encountered block data, %s",data.c_str());
					WAITNL;
				}
				root.contents += data; //read until end of block data
				_state = Intro; //change state to read next tag
Kirill Terekhov's avatar
Kirill Terekhov committed
1589
			}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1590
			else if( t.Failure() ) 
Kirill Terekhov's avatar
Kirill Terekhov committed
1591
			{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
				Report("Failed opening XML tag");
				WAITNL;
				return -1;
			}
			else
			{
				if( verbose )
				{
					Report("info: attached new child %s to %s",t.GetName().c_str(),root.GetName().c_str());
					WAITNL;
				}
				root.children.push_back(XMLTree());
				root.children.back().tag = t;
				if( root.children.back().tag.Process() )
				{
					if( verbose > 1 ) Report("info: calling ReadXMLSub for tree node");
					if( ReadXMLSub(root.children.back()) == -1 )
						return -1;
				}
				else if( verbose > 1 ) Report("info: no ReadXMLSub, child is tree leaf");

				if( verbose > 1 ) Report("info: closing xml tag %s",root.children.back().tag.GetName().c_str());

				if( !CloseTag(root.children.back().tag) )
				{
					Report("Failed closing XML tag");
					WAITNL;
					return -1;
				}
Kirill Terekhov's avatar
Kirill Terekhov committed
1621
1622
			}
		}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1623
1624
1625
1626
1627
1628
		if( verbose )
		{
			Report("info: end processing children of %s",root.GetName().c_str());
			WAITNL;
		}
		return 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
1629
	}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1630
1631

	XMLReader::XMLTree XMLReader::ReadXML()
Kirill Terekhov's avatar
Kirill Terekhov committed
1632
	{
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1633
1634
1635
1636
1637
1638
1639
		XMLTree root;
		root.tag = OpenTag();
		if( verbose ) Report("info: root tag name %s",root.GetName().c_str());
		if( ReadXMLSub(root) == -1 )
			Report("Failed reading XML file");
		CloseTag(root.tag);
		return root;
Kirill Terekhov's avatar
Kirill Terekhov committed
1640
	}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1641

Kirill Terekhov's avatar
Kirill Terekhov committed
1642
1643
1644
1645
1646
	std::ostream & Tabs(std::ostream & output, int num)
	{
		while(num > 0) {output.put('\t'); --num;}
		return output;
	}
Kirill Terekhov's avatar
Kirill Terekhov committed
1647
1648
1649
1650
1651
1652
1653
1654
1655


	int XMLReader::XMLTree::FindChild(std::string name, int offset) const
	{
		for(int k = offset+1; k < NumChildren(); ++k)
			if( GetChild(k).GetName() == name )
				return k;
		return NumChildren();
	}
Kirill Terekhov's avatar
Updates    
Kirill Terekhov committed
1656

Kirill Terekhov's avatar
Kirill Terekhov committed
1657
1658
1659
1660
1661
1662
1663
1664
1665
	int XMLReader::XMLTree::FindAttrib(std::string name, int offset) const
	{
		for(int k = offset+1; k < NumAttrib(); ++k)
			if( GetAttrib(k).name == name )
				return k;
		return NumAttrib();
	}
	
	
Kirill Terekhov's avatar
Kirill Terekhov committed
1666
	void WriteXML(const XMLReader::XMLTree & t, std::ostream & output, int offset)
Kirill Terekhov's avatar
Kirill Terekhov committed
1667
1668
1669
1670
	{
		Tabs(output,offset) << "<" << t.GetName();
		for(int k = 0; k < t.NumAttrib(); ++k)
		{
Kirill Terekhov's avatar
Kirill Terekhov committed
1671
			const XMLReader::XMLAttrib & attr = t.GetAttrib(k);
Kirill Terekhov's avatar
Kirill Terekhov committed
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
			output << std::endl;;
			Tabs(output,offset+1) << attr.name << "=\"" << attr.value << "\"";
		}
		if( t.tag.Stub() ) output << "/";
		output << ">" << std::endl;
		if( t.tag.Stub() ) return;
		for(int k = 0; k < t.NumChildren(); ++k)
			WriteXML(t.GetChild(k),output,offset+1);
		if( !t.GetContents().empty() )
			Tabs(output,offset+1) << "<![CDATA[" << t.GetContents() << "]]>" << std::endl;
		Tabs(output,offset) << "</" << t.GetName() << ">" << std::endl;
	}
1684
}