Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
regex_match.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
10/**
11 * @file regex_match.c
12 * @brief VM opcode snippet for OP_REGEX_MATCH (POSIX full-match).
13 *
14 * This opcode checks whether a regular expression pattern matches the entire
15 * input string. It uses POSIX regex APIs on UNIX platforms and provides a
16 * graceful fallback elsewhere.
17 *
18 * Behavior (stack effects):
19 * - Pops: pattern (string), input (string)
20 * - Pushes: result (int) — 1 if the pattern matches the whole input string,
21 * 0 otherwise. On invalid regex, returns 0.
22 *
23 * Platform notes:
24 * - On non-UNIX platforms (no POSIX regex available), this opcode returns 0
25 * without error.
26 *
27 * Errors:
28 * - If operands are not strings, the VM prints a runtime type error and exits.
29 *
30 * Example:
31 * - pattern = "[a-z]+", input = "hello" -> 1
32 * - pattern = "[a-z]+", input = "hello!" -> 0 (not a full match)
33 */
34
35/* Regex full-match opcode using POSIX regex */
36#ifdef __unix__
37#include <regex.h>
38#endif
39
43 if (str.type != VAL_STRING || pattern.type != VAL_STRING) {
44 fprintf(stderr, "Runtime type error: REGEX_MATCH expects (string, string)\n");
45 exit(1);
46 }
47#ifndef __unix__
48 /* Not supported on non-UNIX: return 0 gracefully */
50 int truth = 0;
53 break;
54#else
55 regex_t rx;
56 int rc = regcomp(&rx, pattern.s ? pattern.s : "", REG_EXTENDED);
57 if (rc != 0) {
58 /* invalid regex -> false */
61 push_value(vm, make_int(0));
62 break;
63 }
64 regmatch_t m;
65 int ok = regexec(&rx, str.s ? str.s : "", 1, &m, 0) == 0;
66 int truth = 0;
67 if (ok) {
68 /* full match means the match spans whole string */
69 if (m.rm_so == 0 && str.s) {
70 size_t slen = strlen(str.s);
71 truth = (m.rm_eo == (regoff_t)slen) ? 1 : 0;
72 }
73 }
74 regfree(&rx);
78 break;
79#endif
80}
@ OP_REGEX_MATCH
Definition bytecode.h:107
int ok
Definition contains.c:38
CURLcode rc
Definition download.c:71
char * pattern
Definition findall.c:52
Value m
Definition has_key.c:27
free_value(pattern)
Value str
Definition regex_match.c:42
push_value(vm, make_int(truth))
int truth
Definition regex_match.c:50
Tagged union representing a Fun value.
Definition value.h:68
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_STRING
Definition value.h:53
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230