ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
parser.c
Go to the documentation of this file.
1
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define MANPAGE_INITIAL_PARSE_CAPACITY 16
12
13#include <defer.h>
15#include <libplatform/filesystem.h>
16#include <ascii-chat/log/log.h>
17#include <ascii-chat/common.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <ctype.h>
23
24// ============================================================================
25// Helper Functions
26// ============================================================================
27
36static bool is_marker_line(const char *line, const char **type_out, char **section_out) {
37 if (!line) {
38 return false;
39 }
40
41 // Skip leading whitespace
42 const char *p = line;
43 while (isspace((unsigned char)*p)) {
44 p++;
45 }
46
47 // Check for groff comment: .\ " or ."
48 if (strncmp(p, ".\\\"", 3) != 0 && strncmp(p, ".\"", 2) != 0) {
49 return false;
50 }
51
52 // Skip comment marker
53 if (p[0] == '.' && p[1] == '\\' && p[2] == '"') {
54 p += 3;
55 } else if (p[0] == '.' && p[1] == '"') {
56 p += 2;
57 }
58
59 // Skip whitespace after comment marker
60 while (isspace((unsigned char)*p)) {
61 p++;
62 }
63
64 // Check for marker pattern: TYPE-START: SECTION or TYPE-END: SECTION
65 const char *type = NULL;
66 const char *section_start = NULL;
67
68 if (strncmp(p, "AUTO-START:", 11) == 0) {
69 type = "AUTO";
70 section_start = p + 11;
71 } else if (strncmp(p, "AUTO-END:", 9) == 0) {
72 type = "AUTO";
73 section_start = p + 9;
74 } else if (strncmp(p, "MANUAL-START:", 13) == 0) {
75 type = "MANUAL";
76 section_start = p + 13;
77 } else if (strncmp(p, "MANUAL-END:", 11) == 0) {
78 type = "MANUAL";
79 section_start = p + 11;
80 } else if (strncmp(p, "MERGE-START:", 12) == 0) {
81 type = "MERGE";
82 section_start = p + 12;
83 } else if (strncmp(p, "MERGE-END:", 10) == 0) {
84 type = "MERGE";
85 section_start = p + 10;
86 } else {
87 return false;
88 }
89
90 // Skip whitespace before section name
91 while (isspace((unsigned char)*section_start)) {
92 section_start++;
93 }
94
95 // Extract section name (until end of line)
96 const char *section_end = section_start;
97 while (*section_end && *section_end != '\n' && *section_end != '\r') {
98 section_end++;
99 }
100
101 if (section_end > section_start) {
102 if (type_out) {
103 *type_out = type;
104 }
105 if (section_out) {
106 size_t len = section_end - section_start;
107 *section_out = SAFE_MALLOC(len + 1, char *);
108 memcpy(*section_out, section_start, len);
109 (*section_out)[len] = '\0';
110 // Trim trailing whitespace
111 char *s = *section_out + len - 1;
112 while (s >= *section_out && isspace((unsigned char)*s)) {
113 *s-- = '\0';
114 }
115 }
116 return true;
117 }
118
119 return false;
120}
121
125static bool is_section_header(const char *line, char **section_name_out) {
126 if (!line) {
127 return false;
128 }
129
130 // Skip leading whitespace
131 const char *p = line;
132 while (isspace((unsigned char)*p)) {
133 p++;
134 }
135
136 // Check for .SH directive
137 if (strncmp(p, ".SH", 3) != 0) {
138 return false;
139 }
140
141 p += 3;
142
143 // Skip whitespace
144 while (isspace((unsigned char)*p)) {
145 p++;
146 }
147
148 // Extract section name (until end of line)
149 const char *name_start = p;
150 const char *name_end = name_start;
151 while (*name_end && *name_end != '\n' && *name_end != '\r') {
152 name_end++;
153 }
154
155 if (name_end > name_start) {
156 size_t len = name_end - name_start;
157 *section_name_out = SAFE_MALLOC(len + 1, char *);
158 memcpy(*section_name_out, name_start, len);
159 (*section_name_out)[len] = '\0';
160 // Trim trailing whitespace
161 char *s = *section_name_out + len - 1;
162 while (s >= *section_name_out && isspace((unsigned char)*s)) {
163 *s-- = '\0';
164 }
165 // Remove quotes if present
166 len = strlen(*section_name_out);
167 if (len >= 2 && (*section_name_out)[0] == '"' && (*section_name_out)[len - 1] == '"') {
168 memmove(*section_name_out, *section_name_out + 1, len - 2);
169 (*section_name_out)[len - 2] = '\0';
170 }
171 return true;
172 }
173
174 return false;
175}
176
180static section_type_t type_string_to_enum(const char *type_str) {
181 if (!type_str) {
183 }
184 if (strcmp(type_str, "AUTO") == 0) {
185 return SECTION_TYPE_AUTO;
186 }
187 if (strcmp(type_str, "MANUAL") == 0) {
188 return SECTION_TYPE_MANUAL;
189 }
190 if (strcmp(type_str, "MERGE") == 0) {
191 return SECTION_TYPE_MERGE;
192 }
194}
195
199static asciichat_error_t parse_sections_internal(FILE *f, parsed_section_t **out_sections, size_t *out_count) {
200 if (!f || !out_sections || !out_count) {
201 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
202 }
203
204 parsed_section_t *sections = NULL;
205 size_t capacity = MANPAGE_INITIAL_PARSE_CAPACITY;
206 size_t count = 0;
207 // NOLINTNEXTLINE(clang-analyzer-unix.Errno) - SAFE_MALLOC handles error
208 sections = SAFE_MALLOC(capacity * sizeof(parsed_section_t), parsed_section_t *);
209
210 char *line = NULL;
211 size_t line_len = 0;
212 size_t line_num = 0;
213
214 parsed_section_t *current_section = NULL;
215 char *current_content = NULL;
216 size_t current_content_capacity = 4096;
217 size_t current_content_len = 0;
218 current_content = SAFE_MALLOC(current_content_capacity, char *);
219
220 // Track markers for current section
221 const char *current_type = NULL;
222 char *current_marker_section = NULL;
223 bool in_marked_section = false;
224
225 while (platform_getline(&line, &line_len, f) != -1) {
226 line_num++;
227
228 const char *marker_type = NULL;
229 char *marker_section = NULL;
230 bool is_marker = is_marker_line(line, &marker_type, &marker_section);
231
232 char *section_header_name = NULL;
233 bool is_header = is_section_header(line, &section_header_name);
234
235 if (is_marker) {
236 // Check if this is a START marker
237 if (strstr(line, "-START:") != NULL) {
238 // Start of a marked section
239 current_type = marker_type;
240 if (current_marker_section) {
241 SAFE_FREE(current_marker_section);
242 }
243 current_marker_section = marker_section;
244 in_marked_section = true;
245 marker_section = NULL; // Ownership transferred
246 } else if (strstr(line, "-END:") != NULL) {
247 // End of marked section
248 if (marker_section) {
249 SAFE_FREE(marker_section);
250 }
251 in_marked_section = false;
252 current_type = NULL;
253 if (current_marker_section) {
254 SAFE_FREE(current_marker_section);
255 current_marker_section = NULL;
256 }
257 } else {
258 if (marker_section) {
259 SAFE_FREE(marker_section);
260 }
261 }
262 }
263
264 if (is_header) {
265 // Finalize previous section if exists
266 if (current_section) {
267 if (current_content && current_content_len > 0) {
268 current_section->content = current_content;
269 current_section->content_len = current_content_len;
270 current_content = NULL;
271 current_content_capacity = 4096;
272 current_content_len = 0;
273 current_content = SAFE_MALLOC(current_content_capacity, char *);
274 } else {
275 SAFE_FREE(current_content);
276 current_content = NULL;
277 current_content_capacity = 4096;
278 current_content_len = 0;
279 current_content = SAFE_MALLOC(current_content_capacity, char *);
280 }
281 }
282
283 // Start new section
284 if (count >= capacity) {
285 capacity *= 2;
286 sections = SAFE_REALLOC(sections, capacity * sizeof(parsed_section_t), parsed_section_t *);
287 }
288
289 current_section = &sections[count++];
290 memset(current_section, 0, sizeof(parsed_section_t));
291 current_section->section_name = section_header_name;
292 current_section->start_line = line_num;
293 current_section->end_line = line_num;
294 current_section->type = in_marked_section ? type_string_to_enum(current_type) : SECTION_TYPE_UNMARKED;
295 current_section->has_markers = in_marked_section;
296
297 // Append header line to content
298 size_t line_strlen = strlen(line);
299 if (current_content_len + line_strlen + 1 >= current_content_capacity) {
300 current_content_capacity = (current_content_len + line_strlen + 1) * 2;
301 current_content = SAFE_REALLOC(current_content, current_content_capacity, char *);
302 }
303 memcpy(current_content + current_content_len, line, line_strlen);
304 current_content_len += line_strlen;
305 current_content[current_content_len] = '\0';
306 } else if (current_section) {
307 // Append line to current section content
308 size_t line_strlen = strlen(line);
309 if (current_content_len + line_strlen + 1 >= current_content_capacity) {
310 current_content_capacity = (current_content_len + line_strlen + 1) * 2;
311 current_content = SAFE_REALLOC(current_content, current_content_capacity, char *);
312 }
313 memcpy(current_content + current_content_len, line, line_strlen);
314 current_content_len += line_strlen;
315 current_content[current_content_len] = '\0';
316 current_section->end_line = line_num;
317 }
318 }
319
320 // Finalize last section
321 if (current_section && current_content && current_content_len > 0) {
322 current_section->content = current_content;
323 current_section->content_len = current_content_len;
324 } else if (current_content) {
325 SAFE_FREE(current_content);
326 }
327
328 if (current_marker_section) {
329 SAFE_FREE(current_marker_section);
330 }
331 if (line) {
332 free(line);
333 }
334
335 *out_sections = sections;
336 *out_count = count;
337 log_debug("Parsed %zu sections from file", count);
338 return ASCIICHAT_OK;
339}
340
341// ============================================================================
342// Public API
343// ============================================================================
344
345asciichat_error_t manpage_parser_parse_file(FILE *f, parsed_section_t **out_sections, size_t *out_count) {
346 if (!f || !out_sections || !out_count) {
347 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
348 }
349
350 return parse_sections_internal(f, out_sections, out_count);
351}
352
353asciichat_error_t manpage_parser_parse_memory(const char *content, size_t content_len, parsed_section_t **out_sections, size_t *out_count) {
354 if (!content || content_len == 0 || !out_sections || !out_count) {
355 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
356 }
357
358 // Create temporary file from memory
359 FILE *tmp = platform_tmpfile();
360 if (!tmp) {
361 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to create temporary file for memory parsing");
362 }
363
364 defer(fclose(tmp));
365
366 // Write content to temporary file
367 // Write content_len + 1 to include the null terminator.
368 // The embedded string is content_len + 1 bytes (content_len chars + null terminator).
369 // platform_getline() needs the null terminator to properly handle EOF.
370 size_t bytes_to_write = content_len + 1;
371 size_t written = fwrite(content, 1, bytes_to_write, tmp);
372 if (written != bytes_to_write) {
373 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to write complete content to temporary file");
374 }
375
376 // Rewind to beginning for reading
377 if (fseek(tmp, 0, SEEK_SET) != 0) {
378 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to rewind temporary file");
379 }
380
381 // Parse using common function
382 asciichat_error_t err = parse_sections_internal(tmp, out_sections, out_count);
383
384 return err;
385}
386
387void manpage_parser_free_sections(parsed_section_t *sections, size_t count) {
388 if (!sections) {
389 return;
390 }
391
392 for (size_t i = 0; i < count; i++) {
393 if (sections[i].section_name) {
394 SAFE_FREE(sections[i].section_name);
395 }
396 if (sections[i].content) {
397 SAFE_FREE(sections[i].content);
398 }
399 }
400
401 SAFE_FREE(sections);
402}
403
404const parsed_section_t *manpage_parser_find_section(const parsed_section_t *sections, size_t count, const char *section_name) {
405 if (!sections || !section_name) {
406 return NULL;
407 }
408
409 for (size_t i = 0; i < count; i++) {
410 if (sections[i].section_name && strcmp(sections[i].section_name, section_name) == 0) {
411 return &sections[i];
412 }
413 }
414
415 return NULL;
416}
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
FILE * platform_tmpfile(void)
Definition filesystem.c:32
#define SAFE_REALLOC(ptr, size, cast)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
section_type_t
Owned slice of a parsed roff man-page section.
Definition manpage.h:33
@ SECTION_TYPE_MERGE
Intelligently merged: auto + manual content.
Definition manpage.h:36
@ SECTION_TYPE_UNMARKED
No marker found, defaults to MANUAL.
Definition manpage.h:37
@ SECTION_TYPE_AUTO
Fully auto-generated, manual edits lost on regeneration.
Definition manpage.h:34
@ SECTION_TYPE_MANUAL
Manually maintained, never touched by generator.
Definition manpage.h:35
asciichat_error_t manpage_parser_parse_file(FILE *f, parsed_section_t **out_sections, size_t *out_count)
Parse man page sections from a FILE handle.
Definition parser.c:345
const parsed_section_t * manpage_parser_find_section(const parsed_section_t *sections, size_t count, const char *section_name)
Find section by name.
Definition parser.c:404
#define MANPAGE_INITIAL_PARSE_CAPACITY
Definition parser.c:11
asciichat_error_t manpage_parser_parse_memory(const char *content, size_t content_len, parsed_section_t **out_sections, size_t *out_count)
Parse man page sections from memory buffer.
Definition parser.c:353
void manpage_parser_free_sections(parsed_section_t *sections, size_t count)
Free parsed sections array.
Definition parser.c:387
Man page template parsing and section extraction.
🔤 String Manipulation and Shell Escaping Utilities
Owned slice of a parsed roff man-page section.
Definition manpage.h:48
bool has_markers
True if marked with AUTO/MANUAL/MERGE markers.
Definition manpage.h:55
char * content
Full section content (including .SH header).
Definition manpage.h:51
size_t content_len
Length of content.
Definition manpage.h:52
size_t end_line
Line number where section ends (1-based).
Definition manpage.h:54
size_t start_line
Line number where section starts (1-based).
Definition manpage.h:53
section_type_t type
Section type (AUTO/MANUAL/MERGE/UNMARKED).
Definition manpage.h:50
char * section_name
Section name (e.g., "ENVIRONMENT", "OPTIONS").
Definition manpage.h:49