Skip to content

Commit 38d8560

Browse files
committed
literal int cleanup
1 parent 80019c3 commit 38d8560

18 files changed

Lines changed: 346 additions & 142 deletions

convert_to_hex.py

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Convert decimal integer literals to hexadecimal format with 'u' suffix.
4+
Processes all .c and .h files in src/ and drivers/ directories.
5+
This version properly handles identifiers and only converts actual numeric literals.
6+
"""
7+
8+
import os
9+
import re
10+
import sys
11+
from pathlib import Path
12+
13+
14+
def is_identifier_char(c):
15+
"""Check if character can be part of an identifier."""
16+
return c.isalnum() or c == '_'
17+
18+
19+
def process_line(line):
20+
"""
21+
Process a single line and convert decimal literals to hex.
22+
Only converts standalone numeric literals, not numbers within identifiers.
23+
"""
24+
result = []
25+
i = 0
26+
in_string = False
27+
in_char = False
28+
escape_next = False
29+
30+
while i < len(line):
31+
if escape_next:
32+
result.append(line[i])
33+
escape_next = False
34+
i += 1
35+
continue
36+
37+
char = line[i]
38+
39+
if char == '\\':
40+
escape_next = True
41+
result.append(char)
42+
i += 1
43+
continue
44+
45+
if char == '"' and not in_char:
46+
in_string = not in_string
47+
result.append(char)
48+
i += 1
49+
continue
50+
51+
if char == "'" and not in_string:
52+
in_char = not in_char
53+
result.append(char)
54+
i += 1
55+
continue
56+
57+
if in_string or in_char:
58+
result.append(char)
59+
i += 1
60+
continue
61+
62+
if len(result) > 0 and is_identifier_char(result[-1]):
63+
result.append(char)
64+
i += 1
65+
continue
66+
67+
if i + 1 < len(line) and char == '0' and line[i+1] in 'xX':
68+
result.append(char)
69+
result.append(line[i+1])
70+
i += 2
71+
while i < len(line) and (line[i] in '0123456789ABCDEFabcdef' or line[i] in 'uUlL'):
72+
result.append(line[i])
73+
i += 1
74+
continue
75+
76+
if char.isdigit():
77+
num_str = ''
78+
j = i
79+
80+
while j < len(line) and line[j].isdigit():
81+
num_str += line[j]
82+
j += 1
83+
84+
suffix_chars = ''
85+
while j < len(line) and line[j] in 'uUlL':
86+
suffix_chars += line[j]
87+
j += 1
88+
89+
next_char = line[j] if j < len(line) else ''
90+
91+
if is_identifier_char(next_char):
92+
result.append(num_str)
93+
result.append(suffix_chars)
94+
i = j
95+
continue
96+
97+
value = int(num_str)
98+
hex_str = f"0x{value:X}u"
99+
result.append(hex_str)
100+
i = j
101+
continue
102+
103+
result.append(char)
104+
i += 1
105+
106+
return ''.join(result)
107+
108+
109+
def process_file(filepath):
110+
"""
111+
Process a single file and convert decimal literals to hex.
112+
"""
113+
try:
114+
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
115+
lines = f.readlines()
116+
117+
modified = False
118+
new_lines = []
119+
120+
for line in lines:
121+
original = line.rstrip('\n')
122+
processed_line = process_line(original)
123+
new_lines.append(processed_line + '\n' if line.endswith('\n') else processed_line)
124+
125+
if processed_line != original:
126+
modified = True
127+
128+
if modified:
129+
with open(filepath, 'w', encoding='utf-8') as f:
130+
f.writelines(new_lines)
131+
return True
132+
133+
return False
134+
135+
except Exception as e:
136+
print(f"Error processing {filepath}: {e}", file=sys.stderr)
137+
return False
138+
139+
140+
def should_skip_file(filepath):
141+
"""
142+
Determine if a file should be skipped.
143+
"""
144+
filename = os.path.basename(filepath)
145+
return filename in ['HeliOS.h', 'config.h']
146+
147+
148+
def process_directory(directory):
149+
"""
150+
Process all C source files in the directory.
151+
"""
152+
directory = Path(directory)
153+
154+
if not directory.exists():
155+
print(f"Warning: Directory {directory} does not exist")
156+
return 0, 0
157+
158+
processed_count = 0
159+
skipped_count = 0
160+
161+
for root, dirs, files in os.walk(directory):
162+
for filename in files:
163+
if not filename.endswith(('.c', '.h')):
164+
continue
165+
166+
filepath = os.path.join(root, filename)
167+
168+
if should_skip_file(filepath):
169+
print(f"Skipping: {filepath}")
170+
skipped_count += 1
171+
continue
172+
173+
if process_file(filepath):
174+
print(f"Modified: {filepath}")
175+
processed_count += 1
176+
else:
177+
print(f"No changes: {filepath}")
178+
179+
return processed_count, skipped_count
180+
181+
182+
def main():
183+
"""
184+
Main entry point.
185+
"""
186+
print("Converting decimal integer literals to hexadecimal...")
187+
print("=" * 60)
188+
189+
total_processed = 0
190+
total_skipped = 0
191+
192+
for directory in ['src', 'drivers']:
193+
print(f"\nProcessing {directory}/ directory:")
194+
print("-" * 60)
195+
processed, skipped = process_directory(directory)
196+
total_processed += processed
197+
total_skipped += skipped
198+
199+
print("\n" + "=" * 60)
200+
print(f"Summary: {total_processed} files modified, {total_skipped} files skipped")
201+
202+
203+
if __name__ == '__main__':
204+
main()

drivers/block/block_driver.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ typedef struct BlockDeviceState_s {
1010
Byte_t currentTransferMode;
1111
} BlockDeviceState_t;
1212
static BlockDeviceState_t state = {
13-
0
13+
0x0u
1414
};
1515
static Return_t __PrepareBlockIORequest__(const Byte_t operation_, BlockIORequest_t **request_, Size_t *configSize_);
1616
static Return_t __BlockDeviceReadBlockRAW__(Byte_t **data_);

drivers/block/block_driver.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
#define BLOCK_CMD_READ_MULTIPLE 0x02u
3434
#define BLOCK_CMD_WRITE_SINGLE 0x03u
3535
#define BLOCK_CMD_WRITE_MULTIPLE 0x04u
36-
#define BLOCK_DEFAULT_SECTOR_SIZE 512u
36+
#define BLOCK_DEFAULT_SECTOR_SIZE 0x200u
3737
typedef struct BlockDeviceConfig_s {
3838
Byte_t command;
3939
HalfWord_t ioDriverUID;

drivers/char/char_driver.c

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ typedef struct CharDeviceState_s {
1717
Byte_t currentTransferMode;
1818
} CharDeviceState_t;
1919
static CharDeviceState_t state = {
20-
0
20+
0x0u
2121
};
2222
static Return_t __PrepareCharIORequest__(const Byte_t operation_, CharIORequest_t **request_, Size_t *configSize_);
2323
static Return_t __CharDeviceReadRAW__(Byte_t **data_, Size_t *bytesRead_);
@@ -74,8 +74,8 @@ Return_t TO_FUNCTION(DEVICE_NAME, _config)(Device_t *device_, Size_t *size_, Add
7474
state.protocol = cfg->protocol;
7575
state.lineMode = cfg->lineMode;
7676
state.baudRate = cfg->baudRate;
77-
state.rxBufferSize = (0 == cfg->rxBufferSize) ? CHAR_DEFAULT_RX_BUFFER_SIZE : cfg->rxBufferSize;
78-
state.txBufferSize = (0 == cfg->txBufferSize) ? CHAR_DEFAULT_TX_BUFFER_SIZE : cfg->txBufferSize;
77+
state.rxBufferSize = (0x0u == cfg->rxBufferSize) ? CHAR_DEFAULT_RX_BUFFER_SIZE : cfg->rxBufferSize;
78+
state.txBufferSize = (0x0u == cfg->txBufferSize) ? CHAR_DEFAULT_TX_BUFFER_SIZE : cfg->txBufferSize;
7979
if((CHAR_PROTOCOL_RAW == state.protocol) && (CHAR_LINE_RAW == state.lineMode)) {
8080
state.initialized = true;
8181
cfg->rxBufferSize = state.rxBufferSize;
@@ -194,10 +194,10 @@ Return_t TO_FUNCTION(DEVICE_NAME, _simple_read)(Device_t *device_, Byte_t *data_
194194
if(__PointerIsNotNull__(data_) && state.initialized) {
195195
Byte_t *byteData = null;
196196
Size_t bytesRead = 0x0u;
197-
state.currentByteCount = 1;
197+
state.currentByteCount = 0x1u;
198198
if(OK(__CharDeviceReadRAW__(&byteData, &bytesRead))) {
199-
if(bytesRead > 0) {
200-
*data_ = byteData[0];
199+
if(bytesRead > 0x0u) {
200+
*data_ = byteData[0x0u];
201201
__KernelFreeMemory__(byteData);
202202
__ReturnOk__();
203203
} else {
@@ -215,7 +215,7 @@ Return_t TO_FUNCTION(DEVICE_NAME, _simple_read)(Device_t *device_, Byte_t *data_
215215
Return_t TO_FUNCTION(DEVICE_NAME, _simple_write)(Device_t *device_, Byte_t data_) {
216216
FUNCTION_ENTER;
217217
if(state.initialized) {
218-
state.currentByteCount = 1;
218+
state.currentByteCount = 0x1u;
219219
if(OK(__CharDeviceWriteRAW__(&data_))) {
220220
__ReturnOk__();
221221
} else {
@@ -237,7 +237,7 @@ static Return_t __PrepareCharIORequest__(const Byte_t operation_,
237237
request->operation = operation_;
238238
request->byteCount = state.currentByteCount;
239239
request->transferMode = state.currentTransferMode;
240-
request->timeoutMs = 1000;
240+
request->timeoutMs = 0x3E8u;
241241
*request_ = request;
242242
*configSize_ = sizeof(CharIORequest_t);
243243
__ReturnOk__();
@@ -294,9 +294,9 @@ static HalfWord_t __CircularBufferSpace__(const HalfWord_t head_,
294294
const HalfWord_t tail_,
295295
const HalfWord_t size_) {
296296
if(head_ >= tail_) {
297-
return (size_ - (head_ - tail_) - 1);
297+
return (size_ - (head_ - tail_) - 0x1u);
298298
} else {
299-
return (tail_ - head_ - 1);
299+
return (tail_ - head_ - 0x1u);
300300
}
301301
}
302302
static HalfWord_t __CircularBufferAvailable__(const HalfWord_t head_,

drivers/char/char_driver.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@
3131
#define CHAR_PROTOCOL_RAW 0xFFu
3232
#define CHAR_LINE_RAW 0x00u
3333
#define CHAR_LINE_COOKED 0x01u
34-
#define CHAR_DEFAULT_RX_BUFFER_SIZE 256u
35-
#define CHAR_DEFAULT_TX_BUFFER_SIZE 256u
34+
#define CHAR_DEFAULT_RX_BUFFER_SIZE 0x100u
35+
#define CHAR_DEFAULT_TX_BUFFER_SIZE 0x100u
3636
typedef struct CharDeviceConfig_s {
3737
Byte_t command;
3838
HalfWord_t ioDriverUID;

drivers/ramdisk/ramdisk_driver.c

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#include "ramdisk_driver.h"
22
static Byte_t ramdisk[RAMDISK_SIZE_BYTES] = {
3-
0
3+
0x0u
44
};
55
typedef struct RAMDiskState_s {
66
Word_t currentPosition;
@@ -11,20 +11,20 @@ typedef struct RAMDiskState_s {
1111
Base_t initialized;
1212
} RAMDiskState_t;
1313
static RAMDiskState_t state = {
14-
0
14+
0x0u
1515
};
1616
#define __UpdateReadStats__(bytes_) \
1717
do { \
1818
state.currentPosition += (bytes_); \
1919
state.bytesRead += (bytes_); \
2020
state.readOperations++; \
21-
} while (0)
21+
} while (0x0u)
2222
#define __UpdateWriteStats__(bytes_) \
2323
do { \
2424
state.currentPosition += (bytes_); \
2525
state.bytesWritten += (bytes_); \
2626
state.writeOperations++; \
27-
} while (0)
27+
} while (0x0u)
2828
#define __ValidateBufferParams__(size_, data_) \
2929
(__PointerIsNotNull__(size_) && __PointerIsNotNull__(data_) && (0x0u < *(size_)))
3030
static Return_t __ValidateAndTruncateSize__(Size_t requested_, Size_t *actual_);
@@ -79,7 +79,7 @@ Return_t TO_FUNCTION(DEVICE_NAME, _config)(Device_t *device_, Size_t *size_, Add
7979
BlockIOInfo_t *info = (BlockIOInfo_t *) config_;
8080
info->command = BLOCK_IO_CMD_GET_INFO;
8181
info->totalSizeBytes = RAMDISK_SIZE_BYTES;
82-
info->nativeBlockSize = 1;
82+
info->nativeBlockSize = 0x1u;
8383
info->supportsRandomAccess = true;
8484
info->requiresErase = false;
8585
__ReturnOk__();
@@ -168,7 +168,7 @@ Return_t TO_FUNCTION(DEVICE_NAME, _simple_read)(Device_t *device_, Byte_t *data_
168168
if(__PointerIsNotNull__(data_)) {
169169
if(state.currentPosition < RAMDISK_SIZE_BYTES) {
170170
*data_ = ramdisk[state.currentPosition];
171-
__UpdateReadStats__(1);
171+
__UpdateReadStats__(0x1u);
172172
__ReturnOk__();
173173
} else {
174174
__AssertOnElse__();
@@ -182,7 +182,7 @@ Return_t TO_FUNCTION(DEVICE_NAME, _simple_write)(Device_t *device_, Byte_t data_
182182
FUNCTION_ENTER;
183183
if(state.currentPosition < RAMDISK_SIZE_BYTES) {
184184
ramdisk[state.currentPosition] = data_;
185-
__UpdateWriteStats__(1);
185+
__UpdateWriteStats__(0x1u);
186186
__ReturnOk__();
187187
} else {
188188
__AssertOnElse__();

0 commit comments

Comments
 (0)