summaryrefslogtreecommitdiffstats
path: root/source/compiler-core/slang-pretty-writer.cpp
blob: 682b02c1e1438a7536f2cbcd644b4d02624aceca (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
#include "slang-pretty-writer.h"

#include "../core/slang-string-escape-util.h"

namespace Slang
{

void PrettyWriter::writeRaw(char const* begin, char const* end)
{
    SLANG_ASSERT(end >= begin);
    writeRaw(UnownedStringSlice(begin, end));
}

void PrettyWriter::adjust()
{
    // Only indent if at start of a line
    if (m_startOfLine)
    {
        // Output current indentation
        m_builder.appendRepeatedChar(' ', m_indent * 4);
        m_startOfLine = false;
    }
}

void PrettyWriter::dedent()
{
    SLANG_ASSERT(m_indent > 0);
    m_indent--;
}

void PrettyWriter::write(const UnownedStringSlice& slice)
{
    const auto end = slice.end();
    auto start = slice.begin();

    while (start < end)
    {
        const char* cur = start;

        // Search for \n if there is one
        while (cur < end && *cur != '\n')
            cur++;

        // If there were some chars, adjust and write
        if (cur > start)
        {
            adjust();
            writeRaw(UnownedStringSlice(start, cur));
        }

        if (cur < end && *cur == '\n')
        {
            writeRawChar('\n');
            // Skip the CR
            cur++;
            // Mark we are at the start of a line
            m_startOfLine = true;
        }

        start = cur;
    }
}

void PrettyWriter::writeEscapedString(const UnownedStringSlice& slice)
{
    adjust();
    auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp);
    StringEscapeUtil::appendQuoted(handler, slice, m_builder);
}

void PrettyWriter::maybeComma()
{
    if (auto state = m_commaState)
    {
        if (!state->needComma)
        {
            state->needComma = true;
            return;
        }
    }

    write(toSlice(",\n"));
}

} // namespace Slang