1#!/usr/bin/env python
2
3# helper for building C program source text
4
5from compilationException import *
6
7
8class ProgramSerializer(object):
9    def __init__(self):
10        self.program = ""
11        self.eol = "\n"
12        self.currentIndent = 0
13        self.INDENT_AMOUNT = 4  # default indent amount
14
15    def __str__(self):
16        return self.program
17
18    def increaseIndent(self):
19        self.currentIndent += self.INDENT_AMOUNT
20
21    def decreaseIndent(self):
22        self.currentIndent -= self.INDENT_AMOUNT
23        if self.currentIndent < 0:
24            raise CompilationException(True, "Negative indentation level")
25
26    def toString(self):
27        return self.program
28
29    def space(self):
30        self.append(" ")
31
32    def newline(self):
33        self.program += self.eol
34
35    def endOfStatement(self, addNewline):
36        self.append(";")
37        if addNewline:
38            self.newline()
39
40    def append(self, string):
41        self.program += str(string)
42
43    def appendFormat(self, format, *args):
44        string = format.format(*args)
45        self.append(string)
46
47    def appendLine(self, string):
48        self.append(string)
49        self.newline()
50
51    def emitIndent(self):
52        self.program += " " * self.currentIndent
53
54    def blockStart(self):
55        self.append("{")
56        self.newline()
57        self.increaseIndent()
58
59    def blockEnd(self, addNewline):
60        self.decreaseIndent()
61        self.emitIndent()
62        self.append("}")
63        if addNewline:
64            self.newline()
65