aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/couscous/backends/python/PythonWriter.java
blob: 781db7171e9468f1a84fa5e9efe1fed390d5bd65 (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
package org.zwobble.couscous.backends.python;

import com.google.common.base.Strings;

public class PythonWriter {
    private static final int SPACES_PER_INDENT = 4;
    private final StringBuilder builder = new StringBuilder();
    private int depth = 0;
    
    public String asString() {
        return builder.toString();
    }

    public void writeInteger(int value) {
        builder.append(value);
    }

    public void writeStringLiteral(String value) {
        builder.append("\"");
        builder.append(value);
        builder.append("\"");
    }

    public void writeKeyword(String keyword) {
        builder.append(keyword);
    }

    public void writeSpace() {
        builder.append(" ");
    }

    public void writeIdentifier(String name) {
        builder.append(name);
    }

    public void writeSymbol(String symbol) {
        builder.append(symbol);
    }

    public void startBlock() {
        depth++;
        writeSymbol(":");
        builder.append("\n");
    }

    public void endBlock() {
        depth--;
    }

    public void writeStatement(Action action) {
        startStatement();
        action.run();
        endStatement();
    }

    private void startStatement() {
        builder.append(Strings.repeat(" ", depth * SPACES_PER_INDENT));
    }

    private void endStatement() {
        if (builder.charAt(builder.length() - 1) != '\n') {
            builder.append("\n");   
        }
    }
    
    interface Action {
        void run();
    }
}