summaryrefslogtreecommitdiff
path: root/src/codegen/print.cc
blob: 31784ea5b75167af70569ab59e2bd52c2adc2264 (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
#include <iostream>

#include "src/codegen/print.h"
#include "src/globals.h"

namespace re2c
{

bool is_print (uint32_t c)
{
	return c >= 0x20 && c < 0x7F;
}

bool is_space (uint32_t c)
{
	switch (c)
	{
		case '\t':
		case '\f':
		case '\v':
		case '\n':
		case '\r':
		case ' ':
			return true;
		default:
			return false;
	}
}

char hexCh(uint32_t c)
{
	static const char * sHex = "0123456789ABCDEF";
	return sHex[c & 0x0F];
}

void prtChOrHex(std::ostream& o, uint32_t c)
{
	if (opts->encoding.type () != Enc::EBCDIC
		&& (is_print (c) || is_space (c)))
	{
		o << '\'';
		prtCh(o, c);
		o << '\'';
	}
	else
	{
		prtHex(o, c);
	}
}

void prtHex(std::ostream& o, uint32_t c)
{
	o << "0x";
	const uint32_t cunit_size = opts->encoding.szCodeUnit ();
	if (cunit_size >= 4)
	{
		o << hexCh (c >> 28u)
			<< hexCh (c >> 24u)
			<< hexCh (c >> 20u)
			<< hexCh (c >> 16u);
	}
	if (cunit_size >= 2)
	{
		o << hexCh (c >> 12u)
			<< hexCh (c >> 8u);
	}
	o << hexCh (c >> 4u)
		<< hexCh (c);
}

void prtCh(std::ostream& o, uint32_t c)
{
	const bool dot = opts->target == opt_t::DOT;

	switch (c)
	{
		case '\'':
		o << (dot ? "'" : "\\'");
		break;

		case '"':
		o << (dot ? "\\\"" : "\"");
		break;

		case '\n':
		o << (dot ? "\\\\n" : "\\n");
		break;

		case '\t':
		o << (dot ? "\\\\t" : "\\t");
		break;

		case '\v':
		o << (dot ? "\\\\v" : "\\v");
		break;

		case '\b':
		o << (dot ? "\\\\b" : "\\b");
		break;

		case '\r':
		o << (dot ? "\\\\r" : "\\r");
		break;

		case '\f':
		o << (dot ? "\\\\f" : "\\f");
		break;

		case '\a':
		o << (dot ? "\\\\a" :"\\a");
		break;

		case '\\':
		o << "\\\\"; // both .dot and C/C++ code expect "\\"
		break;

		default:
		o << static_cast<char> (c);
		break;
	}
}

void prtChOrHexForSpan(std::ostream& o, uint32_t c)
{
	if (opts->encoding.type () != Enc::EBCDIC
		&& is_print (c)
		&& (c != ']'))
	{
		prtCh(o, c);
	}
	else
	{
		prtHex(o, c);
	}
}

void printSpan(std::ostream& o, uint32_t lb, uint32_t ub)
{
	o << "[";
	if ((ub - lb) == 1)
	{
		prtChOrHexForSpan(o, lb);
	}
	else
	{
		prtChOrHexForSpan(o, lb);
		o << "-";
		prtChOrHexForSpan(o, ub - 1);
	}
	o << "]";
}

} // end namespace re2c