summaryrefslogtreecommitdiffstats
path: root/src/uscxml/transform/ChartToVHDL.cpp
blob: f37ad7ef87d003d078bebe14406532e07233fb7c (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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
305
306
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
332
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
528
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
666
667
668
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/**
 *  @file
 *  @author     2015-2016 Jens Heuschkel (heuschkel@tk.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "uscxml/transform/ChartToVHDL.h"
#include "uscxml/debug/Complexity.h"
#include <DOM/io/Stream.hpp>
#include <iostream>
#include "uscxml/UUID.h"
#include "uscxml/DOMUtils.h"
#include <math.h>
#include <boost/algorithm/string.hpp>
#include <glog/logging.h>

#include <algorithm>
#include <iomanip>

#include <sstream>

#define CONST_TRANS_SPONTANIOUS "HWE_NOW"
#define CONST_EVENT_ANY "HWE_ANY"

namespace uscxml {

using namespace Arabica::DOM;
using namespace Arabica::XPath;

Transformer ChartToVHDL::transform(const Interpreter& other) {
	ChartToVHDL* c2c = new ChartToVHDL(other);

	return boost::shared_ptr<TransformerImpl>(c2c);
}

ChartToVHDL::ChartToVHDL(const Interpreter& other) : ChartToC(other), _eventTrie(".") {
}

ChartToVHDL::~ChartToVHDL() {
}

void ChartToVHDL::checkDocument() {
	// filter unsupported stuff
	Arabica::XPath::NodeSet<std::string> unsupported;

	std::set<std::string> elements;
	elements.insert(_nsInfo.xmlNSPrefix + "datamodel");
	elements.insert(_nsInfo.xmlNSPrefix + "data");
	elements.insert(_nsInfo.xmlNSPrefix + "assign");
	elements.insert(_nsInfo.xmlNSPrefix + "donedata");
	elements.insert(_nsInfo.xmlNSPrefix + "content");
	elements.insert(_nsInfo.xmlNSPrefix + "param");
	elements.insert(_nsInfo.xmlNSPrefix + "script");

	elements.insert(_nsInfo.xmlNSPrefix + "parallel");
	elements.insert(_nsInfo.xmlNSPrefix + "history");

	elements.insert(_nsInfo.xmlNSPrefix + "if"); // implicit elseif und else
	elements.insert(_nsInfo.xmlNSPrefix + "foreach");
	elements.insert(_nsInfo.xmlNSPrefix + "send");
	elements.insert(_nsInfo.xmlNSPrefix + "cancel");
	elements.insert(_nsInfo.xmlNSPrefix + "invoke");
	elements.insert(_nsInfo.xmlNSPrefix + "finalize");
	unsupported = DOMUtils::inDocumentOrder(elements, _scxml);

	std::stringstream ss;
	if (unsupported.size() > 0) {
		for (int i = 0; i < unsupported.size(); i++) {
			ss << "  " << DOMUtils::xPathForNode(unsupported[i]) << " unsupported" << std::endl;
		}
		throw std::runtime_error("Unsupported elements found:\n" + ss.str());
	}

	elements.clear();
	elements.insert(_nsInfo.xmlNSPrefix + "transition");
	unsupported = DOMUtils::inDocumentOrder(elements, _scxml);

	for (int i = 0; i < unsupported.size(); i++) {
		Element<std::string> transition(unsupported[i]);
		if (HAS_ATTR(transition, "cond")) {
			ERROR_PLATFORM_THROW("transition with conditions not supported!");
		}
		if (!HAS_ATTR(transition, "target")) {
			ERROR_PLATFORM_THROW("targetless transition not supported!");
		}
	}

}

void ChartToVHDL::findEvents() {
	// elements with an event attribute
	NodeSet<std::string> withEvent;
	withEvent.push_back(InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "raise", _scxml, true));
	withEvent.push_back(InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "send", _scxml, true));
	withEvent.push_back(InterpreterImpl::filterChildElements(_nsInfo.xmlNSPrefix + "transition", _scxml, true));

	for (size_t i = 0; i < withEvent.size(); i++) {
		if (HAS_ATTR_CAST(withEvent[i], "event")) {
			// TODO: tokenize!
			if (ATTR_CAST(withEvent[i], "event") != "*")
				_eventTrie.addWord(ATTR_CAST(withEvent[i], "event"));
		}
	}
}

void ChartToVHDL::writeTo(std::ostream& stream) {
	// same preparations as the C transformation
	prepare();

//    checkDocument();
	findEvents();
//    _eventTrie.dump();


	writeTypes(stream);
	writeFiFo(stream);
	writeOptimalTransitionSetSelection(stream);
	writeExitSet(stream);
	writeEntrySet(stream);
	writeFSM(stream);
}


void ChartToVHDL::writeFSM(std::ostream & stream) {

	// create hardware top level
	stream << "-- FSM Logic" << std::endl;
	writeIncludes(stream);
	stream << "entity fsm_scxml is" << std::endl;
	stream << "port(" << std::endl;
	stream << "    --inputs" << std::endl;
	stream << "    clk  :in    std_logic;" << std::endl;
	stream << "    rst  :in    std_logic;" << std::endl;
	stream << "    en   :in    std_logic;" << std::endl;
	stream << "    next_event_i    :in  event_type;" << std::endl;
	stream << "    next_event_en_i :in  std_logic;" << std::endl;
	stream << "    --outputs" << std::endl;
	stream << "    completed_o :out std_logic;" << std::endl;
	stream << "    error_o     :out std_logic;" << std::endl;
	stream << "    current_state_o  :out state_type" << std::endl;
	stream << ");" << std::endl;
	stream << "end fsm_scxml; " << std::endl;

	stream << std::endl;
	stream << std::endl;
	stream << "architecture behavioral of fsm_scxml is " << std::endl;
	stream << std::endl;

	// Add signals and components
	writeSignals(stream);

	stream << std::endl;
	stream << "begin" << std::endl;
	stream << std::endl;
	// signal mapping
	writeModuleInstantiation(stream);

	// write fsm architecture
	writeNextStateLogic(stream);
	//        writeOutputLogic(stream);
	writeErrorHandler(stream);

	stream << std::endl;
	stream << "end behavioral; " << std::endl;
	stream << "-- END FSM Logic" << std::endl;
}

#if 0
void ChartToVHDL::writeTopDown(std::ostream & stream) {
	// create hardware top level
	stream << "-- top level" << std::endl;
	writeIncludes(stream);
	stream << "entity top_scxml is" << std::endl;
	stream << "port(" << std::endl;
	stream << "    --inputs" << std::endl;
	stream << "    clk\t:in    std_logic;" << std::endl;
	stream << "    rst\t:in    std_logic;" << std::endl;
	stream << "    --outputs" << std::endl;
	stream << "    completed_o\t:out    std_logic;" << std::endl;
	stream << "    result_o\t:out    std_logic;" << std::endl;
	stream << "    error_o\t:out    std_logic" << std::endl;
	stream << ");" << std::endl;
	stream << "end top_scxml; " << std::endl;
	stream << std::endl;
	stream << std::endl;
	stream << "architecture behavioral of top_scxml is " << std::endl;
	stream << std::endl;

	// Add signals and components
	writeSignals(stream);

	stream << std::endl;
	stream << "begin" << std::endl;
	stream << std::endl;
	// signal mapping
	writeModuleInstantiation(stream);

	// write fsm architecture
	writeNextStateLogic(stream);
	writeOutputLogic(stream);

	stream << std::endl;
	stream << "end behavioral; " << std::endl;
}
#endif

void ChartToVHDL::writeTypes(std::ostream & stream) {
	std::string seperator = "";

	stream << "-- required global types" << std::endl;
	stream << "library IEEE;" << std::endl;
	stream << "use IEEE.std_logic_1164.all;" << std::endl;
	stream << std::endl;
	stream << "package machine" << _md5 << " is" << std::endl;
	// create state type
	stream << "  type state_type is std_logic_vector( ";
	stream << _states.size() - 1;
	stream << " downto 0)" << std::endl;

	//TODO complete
	// create event type
	stream << "  type event_type is (";
	seperator = "";
//	for (int i = 0; i < _events.size(); i++) {
//		stream << seperator;
//		stream << _events[i];
//		seperator = ", ";
//	}
	if (seperator.size() == 0) {
		stream << "NO_EVENTS";
	}
	stream << ");" << std::endl;

	stream << "end machine" << _md5 << ";" << std::endl;
	stream << std::endl;
	stream << "-- END needed global types" << std::endl;
}

void ChartToVHDL::writeIncludes(std::ostream & stream) {
	// Add controler specific stuff here
	stream << "library IEEE;" << std::endl;
	stream << "use IEEE.std_logic_1164.all;" << std::endl;
	stream << "use work.machine" << _md5 << ".all;" << std::endl;
	stream << std::endl;
}

void ChartToVHDL::writeFiFo(std::ostream & stream) {
	// taken from: http://www.deathbylogic.com/2013/07/vhdl-standard-fifo/
	// alternativly take fifo logic for a ram device: http://www.eng.auburn.edu/~strouce/class/elec4200/vhdlmods.pdf
	stream << "-- standard FIFO buffer" << std::endl;
	writeIncludes(stream);
	stream << "" << std::endl;
	stream << "entity std_fifo is" << std::endl;
	stream << "generic (" << std::endl;
	stream << "  constant FIFO_DEPTH  : positive := 256" << std::endl;
	stream << ");" << std::endl;
	stream << "port ( " << std::endl;
	stream << "  clk      : in  std_logic;" << std::endl;
	stream << "  rst      : in  std_logic;" << std::endl;
	stream << "  write_en  : in  std_logic;" << std::endl;
	stream << "  read_en     : in  std_logic;" << std::endl;
	stream << "  data_in     : in  event_type;" << std::endl;
	stream << "  data_out  : out event_type;" << std::endl;
	stream << "  empty       : out std_logic;" << std::endl;
	stream << "  full        : out std_logic" << std::endl;
	stream << ");" << std::endl;
	stream << "end std_fifo;" << std::endl;
	stream << "" << std::endl;
	stream << "architecture behavioral of std_fifo is" << std::endl;
	stream << "begin" << std::endl;
	stream << "-- Memory Pointer Process" << std::endl;
	stream << "fifo_proc : process (clk)" << std::endl;
	stream << "  type FIFO_Memory is array (0 to FIFO_DEPTH - 1) of event_type;" << std::endl;
	stream << "  variable Memory : FIFO_Memory;" << std::endl;
	stream << "" << std::endl;
	stream << "  variable Head : natural range 0 to FIFO_DEPTH - 1;" << std::endl;
	stream << "  variable Tail : natural range 0 to FIFO_DEPTH - 1;" << std::endl;
	stream << "" << std::endl;
	stream << "  variable Looped : boolean;" << std::endl;
	stream << "begin" << std::endl;
	stream << "  if rising_edge(clk) then" << std::endl;
	stream << "    if rst = '1' then" << std::endl;
	stream << "      Head := 0;" << std::endl;
	stream << "      Tail := 0;" << std::endl;
	stream << "" << std::endl;
	stream << "      Looped := false;" << std::endl;
	stream << "" << std::endl;
	stream << "      full  <= '0';" << std::endl;
	stream << "      empty <= '1';" << std::endl;
	stream << "    else" << std::endl;
	stream << "      if (read_en = '1') then" << std::endl;
	stream << "        if ((Looped = true) or (Head /= Tail)) then" << std::endl;
	stream << "          -- Update data output" << std::endl;
	stream << "          data_out <= Memory(Tail);" << std::endl;
	stream << "          " << std::endl;
	stream << "          -- Update Tail pointer as needed" << std::endl;
	stream << "          if (Tail = FIFO_DEPTH - 1) then" << std::endl;
	stream << "            Tail := 0;" << std::endl;
	stream << "            " << std::endl;
	stream << "            Looped := false;" << std::endl;
	stream << "          else" << std::endl;
	stream << "            Tail := Tail + 1;" << std::endl;
	stream << "          end if;" << std::endl;
	stream << "" << std::endl;
	stream << "        end if;" << std::endl;
	stream << "      end if;" << std::endl;
	stream << "" << std::endl;
	stream << "      if (write_en = '1') then" << std::endl;
	stream << "        if ((Looped = false) or (Head /= Tail)) then" << std::endl;
	stream << "          -- Write Data to Memory" << std::endl;
	stream << "          Memory(Head) := data_in;" << std::endl;
	stream << "          " << std::endl;
	stream << "          -- Increment Head pointer as needed" << std::endl;
	stream << "          if (Head = FIFO_DEPTH - 1) then" << std::endl;
	stream << "            Head := 0;" << std::endl;
	stream << "            " << std::endl;
	stream << "            Looped := true;" << std::endl;
	stream << "          else" << std::endl;
	stream << "            Head := Head + 1;" << std::endl;
	stream << "          end if;" << std::endl;
	stream << "        end if;" << std::endl;
	stream << "      end if;" << std::endl;
	stream << "" << std::endl;
	stream << "      -- Update empty and full flags" << std::endl;
	stream << "      if (Head = Tail) then" << std::endl;
	stream << "        if Looped then" << std::endl;
	stream << "          full <= '1';" << std::endl;
	stream << "        else" << std::endl;
	stream << "          empty <= '1';" << std::endl;
	stream << "        end if;" << std::endl;
	stream << "      else" << std::endl;
	stream << "        empty  <= '0';" << std::endl;
	stream << "        full  <= '0';" << std::endl;
	stream << "      end if;" << std::endl;
	stream << "    end if;" << std::endl;
	stream << "  end if;" << std::endl;
	stream << "end process;" << std::endl;
	stream << "" << std::endl;
	stream << "end behavioral;" << std::endl;
	stream << "-- END standard FIFO buffer" << std::endl;
}

void ChartToVHDL::writeSignals(std::ostream & stream) {
	// create needed internal signals
	stream << "-- system signals" << std::endl;
	stream << "signal stall : std_logic;" << std::endl;
	stream << "-- state signals" << std::endl;
	stream << "signal next_state : state_type;" << std::endl;
	stream << "signal current_state : state_type;" << std::endl;

	for (int i = 0; i < _states.size(); i++) {
		Element<std::string> state(_states[i]);
		stream << "signal " << ATTR(state, "id") << "_curr : current_state("
		       << toStr(i) << ");" << std::endl;
		stream << "signal " << ATTR(state, "id") << "_next : next_state("
		       << toStr(i) << ");" << std::endl;
	}
	stream << std::endl;
	stream << "-- event signals" << std::endl;
	stream << "signal int_event_write_en : std_logic;" << std::endl;
	stream << "signal int_event_read_en : std_logic;" << std::endl;
	stream << "signal int_event_empty : std_logic;" << std::endl;
	stream << "signal int_event_input : event_type;" << std::endl;
	stream << "signal int_event_output : event_type;" << std::endl;
	stream << "signal next_event_re : std_logic;" << std::endl;
	stream << "signal next_event : event_type;" << std::endl;
	stream << "signal event_consumed : std_logic;" << std::endl;
	stream << std::endl;
	stream << "-- transition signals" << std::endl;
	stream << "signal transition_spntaneous_en : std_logic;" << std::endl;

	for (int i = 0; i < _transitions.size(); i++) {
		Element<std::string> transition(_transitions[i]);
		stream << "signal in_optimal_transition_set_" << ATTR(transition, "postFixOrder") << "_sig : std_logic;"
		       << std::endl;
	}

	stream << std::endl;
	stream << "-- error signals" << std::endl;
	stream << "signal reg_error_out : std_logic;" << std::endl;
	stream << "signal error_full_int_event_fifo : std_logic;" << std::endl;
	stream << std::endl;

	// add needed components
	stream << "-- event FIFO" << std::endl;
	stream << "component std_fifo is" << std::endl;
	stream << "port ( " << std::endl;
	stream << "	clk		: in  std_logic;" << std::endl;
	stream << "	rst		: in  std_logic;" << std::endl;
	stream << "	write_en	: in  std_logic;" << std::endl;
	stream << "	read_en         : in  std_logic;" << std::endl;
	stream << "	data_in         : in  event_type;" << std::endl;
	stream << "	data_out	: out event_type;" << std::endl;
	stream << "	empty           : out std_logic;" << std::endl;
	stream << "	full            : out std_logic" << std::endl; // we calculate how much we need
	stream << ");" << std::endl;
	stream << "end component;" << std::endl;
	stream << std::endl;
}

void ChartToVHDL::writeModuleInstantiation(std::ostream & stream) {
	// tmp mapping for events
	stream << "error_o <= reg_error_out; " << std::endl;
	stream << "stall <= not en; " << std::endl;
	stream << std::endl;

	stream << "next_event_re <= not int_event_empty and not stall; " << std::endl;
	stream << "next_event <= int_event_output; " << std::endl;
	stream << "int_event_write_en <= next_event_en_i; " << std::endl;
	stream << "int_event_input <= next_event_i; " << std::endl;
	stream << "int_event_read_en <= not transition_spontanous_en and not stall; " << std::endl;
	stream << std::endl;

	// instantiate event fifo
	stream << "int_event_fifo : component std_fifo " << std::endl;
	stream << "port map ( " << std::endl;
	stream << "	clk         => clk," << std::endl;
	stream << "	rst         => rst," << std::endl;
	stream << "	write_en    => int_event_write_en," << std::endl;
	stream << "	read_en     => int_event_read_en," << std::endl;
	stream << "	data_in     => int_event_input," << std::endl;
	stream << "	data_out    => int_event_output," << std::endl;
	stream << "	empty       => int_event_empty," << std::endl;
	stream << "	full        => error_full_int_event_fifo" << std::endl; // we calculate how much we need
	stream << ");" << std::endl;
	stream << std::endl;
}

void ChartToVHDL::writeErrorHandler(std::ostream & stream) {
	// sets error output signal if an error occures somewhere
	stream << "-- error handler" << std::endl;
	stream << "-- sets error output signal if an error occures somewhere" << std::endl;
	stream << "error_handler : process (clk, rst) " << std::endl;
	stream << "begin" << std::endl;
	stream << "    if rst = '1' then" << std::endl;
	stream << "        reg_error_out <= '0';" << std::endl;
	stream << "    elsif rising_edge(clk) then" << std::endl;
	stream << "        reg_error_out <= error_full_int_event_fifo;" << std::endl;
	stream << "    end if;" << std::endl;
	stream << "end process;" << std::endl;
	stream << std::endl;
}

std::string ChartToVHDL::eventNameEscape(const std::string& eventName) {
	std::string escaped = escape(eventName);
	boost::replace_all(escaped, ".", "_");
	return escaped;
}

void ChartToVHDL::writeOptimalTransitionSetSelection(std::ostream & stream) {
	stream << "-- optimal transition set selection" << std::endl;
	for (size_t i = 0; i < _transitions.size(); i++) {
		Element<std::string> transition(_transitions[i]);
		std::string conflicts = ATTR(transition, "conflictBools");

		stream << "in_optimal_transition_set_" << ATTR(transition, "postFixOrder") << "_sig "
		       << "<= " << (HAS_ATTR(transition, "event") ? "(not spontaneous_sig)" : "spontaneous_sig") << " and " << std::endl
		       << "  state_active_" << ATTR(transition, "source") << "_sig and not ( '0' " << std::endl;
		for (size_t j = 0; j < i; j++) {
			if (conflicts[j] == '1') {
				stream << "    or in_optimal_transition_set_" << toStr(j) << "_sig" << std::endl;
			}
		}
		stream << "  )";
		if (HAS_ATTR(transition, "event")) {
			stream << " and ( '0' " << std::endl;;

			// find all matching event literals
			std::list<std::string> eventDescs = tokenizeIdRefs(ATTR(transition, "event"));
			for (std::list<std::string>::iterator descIter = eventDescs.begin(); descIter != eventDescs.end(); descIter++) {
				std::list<TrieNode*> eventNames = _eventTrie.getWordsWithPrefix((*descIter) == "*" ? "" : *descIter);
				for (std::list<TrieNode*>::iterator eventIter = eventNames.begin(); eventIter != eventNames.end(); eventIter++) {
					stream << "    or event_" << eventNameEscape((*eventIter)->value) << "_sig" << std::endl;
				}
			}
			stream << "  )";

		}
		stream << ";" << std::endl;
	}

}

void ChartToVHDL::writeExitSet(std::ostream & stream) {
	stream << "-- exit set selection" << std::endl;

	for (size_t i = 0; i < _states.size(); i++) {
		Element<std::string> state(_states[i]);
		std::string completion = ATTR(state, "completionBools");
		std::string ancestors = ATTR(state, "ancBools");
		std::string children = ATTR(state, "childBools");
		std::string parent = ATTR(state, "parent");

		stream << "in_exit_set_" << toStr(i) << "_sig "
		       << "<= state_active_ " << toStr(i) << "_sig and ('0'" << std::endl;
		for (size_t j = 0; j < _transitions.size(); j++) {
			Element<std::string> transition(_transitions[j]);
			std::string exitSet = ATTR(transition, "exitSetBools");
			if (exitSet[i] == '1') {
				stream << "  or in_optimal_transition_set_" << toStr(j) << "_sig " << std::endl;
			}
		}

		stream << ")";
		stream << ";" << std::endl;

	}
}

void ChartToVHDL::writeEntrySet(std::ostream & stream) {
	stream << "-- entry set selection" << std::endl;

	for (size_t i = 0; i < _states.size(); i++) {
		Element<std::string> state(_states[i]);
		std::string completion = ATTR(state, "completionBools");
		std::string ancestors = ATTR(state, "ancBools");
		std::string children = ATTR(state, "childBools");
		std::string parent = ATTR(state, "parent");

		stream << "in_complete_entry_set_up_" << toStr(i) << "_sig <= ('0'" << std::endl;

		for (size_t j = 0; j < _transitions.size(); j++) {
			Element<std::string> transition(_transitions[j]);
//            std::cout << transition;
			std::string targetSet = ATTR(transition, "targetBools");
			if (targetSet[i] == '1') {
				stream << "  or in_optimal_transition_set_" << toStr(j) << std::endl;
			}
		}
		if (isCompound(state)) {
			for (size_t j = 0; j < _states.size(); j++) {
				if (children[j] != '1')
					continue;

				stream << "  or in_complete_entry_set_up_" << toStr(j) << "_sig" << std::endl;
			}

		}
		stream << ");" << std::endl;

	}

	for (size_t i = 0; i < _states.size(); i++) {
		Element<std::string> state(_states[i]);
		std::string completion = ATTR(state, "completionBools");
		std::string ancestors = ATTR(state, "ancBools");
		std::string children = ATTR(state, "childBools");
		std::string parent = ATTR(state, "parent");

		if (parent.size() == 0) {
			continue; // TODO: FixMe <scxml>
		}

		stream << "in_complete_entry_set_" << toStr(i) << "_sig <= (in_complete_entry_set_up_" << toStr(i) << "_sig or (" << std::endl;

		if (isParallel(Element<std::string>(_states[strTo<size_t>(parent)]))) {
			stream << "  in_complete_entry_set_" << toStr(parent) << "_sig" << std::endl;
		} else if (isCompound(Element<std::string>(_states[strTo<size_t>(parent)]))) {
			stream << "  default_completion_" << toStr(parent) << "_sig" << std::endl;

			for (size_t j = 0; j < _states.size(); j++) {
				if (children[j] != '1')
					continue;
				stream << "  and not (is_active" << toStr(j) << "_sig and not in_exit_set_" << toStr(j) << "_sig)" << std::endl;

			}
		}

		stream << ");" << std::endl;

	}
}

//TODO write event generator
// wie die letzten beiden states erkennen
// process bauen der bei fail 0 ausgibt und bei accept 1

void ChartToVHDL::writeNextStateLogic(std::ostream & stream) {
	stream << "-- state logic" << std::endl;
	stream << "-- only gets active when state changes (microstep?) " << std::endl;
	stream << "state_decode_proc: process(current_state)" << std::endl;
	stream << "begin" << std::endl;

	std::stringstream nextStateBuffer;
	for (int i = 0; i < _states.size(); i++) {
		Element<std::string> state(_states[i]);

		// calculate event choices
		// _transitions is sorted in Postfix order
		// by stating with smalest index the most important
		// will be written first
		std::vector< Element<std::string> > choices;
		std::string spntaneous_trans_sig = "";
		for (int j = 0; j < _transitions.size(); j++) {
			Element<std::string> transition(_transitions[j]);
			if (ATTR_CAST(transition.getParentNode(), "id") == ATTR(state, "id")) {
				choices.push_back(transition);
				if (ATTR(transition, "event") == CONST_TRANS_SPONTANIOUS) {
					spntaneous_trans_sig = ATTR(transition, "id");
					// FIXME hofully there are just single spntaneous transitions allowed
					// else we have to handle this
				}
			}
		}

		// calculate incomming transitions (for later use)
		std::vector< Element<std::string> > incommingTransitions;
		for (int j = 0; j < _transitions.size(); j++) {
			Element<std::string> transition(_transitions[j]);
			if (ATTR_CAST(transition, "target") == ATTR(state, "id")) {
				incommingTransitions.push_back(transition);
			}
		}

		if (choices.size() > 0) {// if no outgoing transitions (maybe final state :D) we don't write anything

			stream << "  if ( " << ATTR(state, "id") << " = '1' ) then" << std::endl;
			stream << "    if ( transition_spntaneous_en = '1' ) then" << std::endl;
			// enable spntaneous transition (if any) and disable all other
			for (int j = 0; j < choices.size(); j++) {
				Element<std::string> transition(choices[j]);
				if (ATTR(transition, "id") == spntaneous_trans_sig) {
					stream << "      " << ATTR(transition, "id") << "_sig <= '1';" << std::endl;
				} else {
					stream << "      " << ATTR(transition, "id") << "_sig <= '0';" << std::endl;
				}
			}

			stream << "    elsif ( next_event_re = '1' ) then" << std::endl;
			// if no spntaneous transition enables, look at events
			// since there is just one event at a time, we use case statement
			// to check transitions matching in postfix order
			// FIXME hopefully there is just one transition per state and event at a time
			stream << "    case next_event is" << std::endl;
			bool hasWildcardTransition = false;
			for (int j = 0; j < choices.size(); j++) {
				Element<std::string> transition(choices[j]);
				std::string eventName = ATTR(transition, "event");
				if (eventName == CONST_EVENT_ANY) {
					eventName = "others";
					hasWildcardTransition = true;
				}
				stream << "      when " << eventName << " =>" << std::endl;
				// activate transition and deactivete others
				for (int k = 0; k < choices.size(); k++) {
					Element<std::string> tmp_t(choices[k]);
					if (ATTR(tmp_t, "event") == ATTR(transition, "event")) {
						stream << "        " << ATTR(tmp_t, "id") << "_sig <= '1';" << std::endl;
					} else {
						stream << "        " << ATTR(tmp_t, "id") << "_sig <= '0';" << std::endl;
					}
				}
			}
			if (!hasWildcardTransition) {
				// if there is no others we create one for deactivating everything
				stream << "      when others =>" << std::endl;
				for (int j = 0; j < choices.size(); j++) {
					Element<std::string> tmp_t(choices[j]);
					stream << "        " << ATTR(tmp_t, "id") << "_sig <= '0';" << std::endl;
				}
			}
			stream << "    end case;" << std::endl;
			//TODO umkehren oder other abfangen
			//stream << "    when others =>" << std::endl;
			//stream << "     next_state <= current_state;" << std::endl;

			stream << "    else" << std::endl;
			// no enabled event ? disable all transitions (looks like we have to wait)
			for (int j = 0; j < choices.size(); j++) {
				Element<std::string> transition(choices[j]);
				stream << "      " << ATTR(transition, "id") << "_sig <= '0';" << std::endl;
			}
			stream << "    end if;" << std::endl;
			stream << "  end if;" << std::endl;
			stream << std::endl;
		}
		// write next state calculation in buffer for later use
		nextStateBuffer << ATTR(state, "id") << "_next <= ( ( '0'";
		std::string seperator = "  or  ";
		for (int j = 0; j < incommingTransitions.size(); j++) {
			nextStateBuffer << seperator
			                << ATTR(incommingTransitions[j], "id") << "_sig";
		}
		nextStateBuffer << " ) or ";
		nextStateBuffer << "( ( not ( '0'";
		seperator = "  or  ";
		for (int j = 0; j < choices.size(); j++) {
			nextStateBuffer << seperator
			                << ATTR(choices[j], "id") << "_sig";
		}
		nextStateBuffer << " ) ) and " << ATTR(state, "id")
		                << "_curr ));" << std::endl;
	}
	stream << "end process;" << std::endl;
	stream << std::endl;
	// write outgoing transition buffer
	stream << nextStateBuffer.str() << std::endl;

	// updater for current state
	stream << "-- update current state" << std::endl;
	stream << "state_proc: process(clk, rst, stall)" << std::endl;
	stream << "begin" << std::endl;
	stream << "    if rst = '1' then" << std::endl;
	stream << "        current_state <= (others => '0');" << std::endl;
//	stream << "        " << _initState << "_curr <= '1';" << std::endl;
	stream << "    elsif (rising_edge(clk) and stall = '0') then" << std::endl;
	stream << "        current_state <= next_state;" << std::endl;
	stream << "    end if;" << std::endl;
	stream << "end process;" << std::endl;
	stream << std::endl;
}

void ChartToVHDL::writeOutputLogic(std::ostream & stream) {
	stream << "-- output logic" << std::endl;
	stream << "output_proc: process(current_state)" << std::endl;
	stream << "begin" << std::endl;
	stream << "    case current_state is" << std::endl;

	for (int i = 0; i < _states.size(); i++) {
		//TODO
		// if end state set completed and result
		// on entry events generated here
	}

	stream << "    when others =>" << std::endl;
	stream << "        completed_o <= '0';" << std::endl;
	stream << "        result_o <= '0';" << std::endl;

	stream << "end case;" << std::endl;
	stream << "end process;" << std::endl;
	stream << std::endl;
}

}