implregex.c 15.2 KB
Newer Older
1 2 3
/*
 * This file is part of GtkSourceView
 *
4 5 6
 * Copyright 1999, 2000 Scott Wimer
 * Copyright 2004, Matthias Clasen <mclasen@redhat.com>
 * Copyright 2005 - 2007, Marco Barisione <marco@barisione.org>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Copyright 2020 Christian Hergert <chergert@redhat.com>
 *
 * GtkSourceView is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * GtkSourceView is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "config.h"

27 28 29 30
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include <string.h>

31
#include "implregex-private.h"
32
#include "gtksourcetrace.h"
33 34 35

struct _ImplRegex
{
36 37 38 39 40 41 42 43 44
	int                    ref_count;
	char                  *pattern;
	gsize                  compile_flags;
	gsize                  match_flags;
	pcre2_compile_context *context;
	pcre2_code            *code;
	PCRE2_SPTR             name_table;
	int                    name_count;
	int                    name_entry_size;
45 46 47 48
};

struct _ImplMatchInfo
{
49 50 51 52 53 54 55 56 57
	gsize             compile_flags;
	gsize             match_flags;
	ImplRegex        *regex;
	const char       *string;
	gsize             string_len;
	pcre2_match_data *match_data;
	PCRE2_SIZE       *offsets;
	int               n_groups;
	gsize             start_pos;
58 59
};

60 61
static gsize
translate_compile_flags (GRegexCompileFlags flags)
62
{
63 64 65 66 67 68 69 70 71 72
	gsize ret = 0;

	if (!(flags & G_REGEX_RAW))
		ret |= (PCRE2_UTF | PCRE2_NO_UTF_CHECK);

	if (flags & G_REGEX_ANCHORED)
		ret |= PCRE2_ANCHORED;

	if (flags & G_REGEX_CASELESS)
		ret |= PCRE2_CASELESS;
73

74 75
	if (flags & G_REGEX_EXTENDED)
		ret |= PCRE2_EXTENDED;
76

77 78 79 80
	ret |= PCRE2_UCP;
	ret |= PCRE2_BSR_UNICODE;

	return ret;
81 82
}

83 84
static gsize
translate_match_flags (GRegexMatchFlags flags)
85
{
86
	gsize ret = 0;
87

88 89
	if (flags & G_REGEX_MATCH_ANCHORED)
		ret |= PCRE2_ANCHORED;
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
	return ret;
}

static gboolean
set_regex_error (GError **error,
                 int      rc)
{
	if (rc > 0)
	{
		return FALSE;
	}

	if (error != NULL)
	{
		guchar errstr[128];

		pcre2_get_error_message (rc, errstr, sizeof errstr - 1);
		errstr[sizeof errstr - 1] = 0;

		g_set_error_literal (error,
		                     G_REGEX_ERROR,
		                     G_REGEX_ERROR_MATCH,
		                     (const gchar *)errstr);
	}

	return TRUE;
117 118 119 120 121 122 123 124
}

ImplRegex *
impl_regex_new (const char          *pattern,
                GRegexCompileFlags   compile_options,
                GRegexMatchFlags     match_options,
                GError             **error)
{
125
	pcre2_compile_context *context;
126
	ImplRegex *regex;
127 128 129 130 131 132 133
	PCRE2_SIZE erroffset;
	int errnumber = -1;
#ifdef GTK_SOURCE_PROFILER_ENABLED
	char *message = NULL;

	GTK_SOURCE_PROFILER_BEGIN_MARK;
#endif
134 135

	g_return_val_if_fail (pattern != NULL, NULL);
136
	g_return_val_if_fail (strstr (pattern, "\\K") == NULL, NULL);
137

138
	context = pcre2_compile_context_create (NULL);
139

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
	regex = g_slice_new0 (ImplRegex);
	regex->ref_count = 1;
	regex->context = context;
	regex->pattern = g_strdup (pattern);
	regex->compile_flags = translate_compile_flags (compile_options);
	regex->match_flags = translate_match_flags (match_options);

	if (compile_options & G_REGEX_NEWLINE_LF)
		pcre2_set_newline (context, PCRE2_NEWLINE_LF);
	else if (compile_options & G_REGEX_NEWLINE_CR)
		pcre2_set_newline (context, PCRE2_NEWLINE_CR);
	else if (compile_options & G_REGEX_NEWLINE_CRLF)
		pcre2_set_newline (context, PCRE2_NEWLINE_CRLF);
	else if (compile_options & G_REGEX_NEWLINE_ANYCRLF)
		pcre2_set_newline (context, PCRE2_NEWLINE_ANYCRLF);

	regex->code = pcre2_compile ((PCRE2_SPTR)pattern,
	                             PCRE2_ZERO_TERMINATED,
	                             regex->compile_flags,
	                             &errnumber,
	                             &erroffset,
	                             context);

	if (regex->code == NULL)
164
	{
165 166 167 168 169 170 171 172 173 174 175 176 177
		char errmsg[128];

		pcre2_get_error_message (errnumber, (guchar *)errmsg, sizeof errmsg-1);
		errmsg[sizeof errmsg-1] = 0;

		g_set_error (error,
		             G_REGEX_ERROR,
		             G_REGEX_ERROR_COMPILE,
		             "%s: offset %d of pattern %s",
		             errmsg,
		             (int)erroffset,
		             pattern);
		impl_regex_unref (regex);
178 179 180
		return NULL;
	}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	pcre2_pattern_info (regex->code, PCRE2_INFO_NAMECOUNT, &regex->name_count);

	if (regex->name_count > 0)
	{
		pcre2_pattern_info (regex->code,
		                    PCRE2_INFO_NAMEENTRYSIZE,
		                    &regex->name_entry_size);
		pcre2_pattern_info (regex->code,
		                    PCRE2_INFO_NAMETABLE,
		                    &regex->name_table);
	}

#ifdef GTK_SOURCE_PROFILER_ENABLED
	if (GTK_SOURCE_PROFILER_ACTIVE)
		message = g_strdup_printf ("compile=%lx match=%lx pattern=%s",
		                           regex->compile_flags,
		                           regex->match_flags,
		                           regex->pattern);
	GTK_SOURCE_PROFILER_END_MARK (G_STRFUNC, message);
	g_free (message);
#endif
202 203 204 205 206 207 208 209 210 211 212 213

	return regex;
}

const char *
impl_regex_get_pattern (const ImplRegex *regex)
{
	g_return_val_if_fail (regex != NULL, NULL);

	return regex->pattern;
}

214 215 216 217 218 219 220 221 222 223 224
ImplRegex *
impl_regex_ref (ImplRegex *regex)
{
	g_return_val_if_fail (regex != NULL, NULL);
	g_return_val_if_fail (regex->ref_count > 0, NULL);

	regex->ref_count++;

	return regex;
}

225 226 227 228 229 230 231 232 233 234 235
void
impl_regex_unref (ImplRegex *regex)
{
	g_return_if_fail (regex != NULL);
	g_return_if_fail (regex->ref_count > 0);

	regex->ref_count--;

	if (regex->ref_count == 0)
	{
		g_clear_pointer (&regex->pattern, g_free);
236 237
		g_clear_pointer (&regex->code, pcre2_code_free);
		g_clear_pointer (&regex->context, pcre2_compile_context_free);
238 239 240 241
		g_slice_free (ImplRegex, regex);
	}
}

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
static ImplMatchInfo *
impl_match_info_new (ImplRegex        *regex,
                     GRegexMatchFlags  match_options,
                     const char       *string,
                     gssize            string_len)
{
	ImplMatchInfo *match_info;

	g_assert (regex != NULL);
	g_assert (string != NULL);
	g_assert (string_len <= strlen (string));

	if (string_len < 0)
	{
		string_len = strlen (string);
	}

	match_info = g_slice_new0 (ImplMatchInfo);
	match_info->regex = impl_regex_ref (regex);
	match_info->match_flags = regex->match_flags | translate_match_flags (match_options);
	match_info->start_pos = -1;
	match_info->n_groups = -1;
	match_info->string = string;
	match_info->string_len = string_len;
	match_info->match_data = pcre2_match_data_create_from_pattern (regex->code, NULL);

	if (match_info->match_data == NULL)
	{
		g_error ("Failed to allocate match data");
	}

	match_info->offsets = pcre2_get_ovector_pointer (match_info->match_data);

	return match_info;
}

278 279 280
void
impl_match_info_free (ImplMatchInfo *match_info)
{
281 282 283 284 285 286 287 288 289 290 291 292 293
	if (match_info != NULL)
	{
		g_clear_pointer (&match_info->match_data, pcre2_match_data_free);
		g_clear_pointer (&match_info->regex, impl_regex_unref);
		match_info->string = NULL;
		match_info->string_len = 0;
		match_info->compile_flags = 0;
		match_info->match_flags = 0;
		match_info->n_groups = 0;
		match_info->start_pos = 0;
		match_info->offsets = NULL;
		g_slice_free (ImplMatchInfo, match_info);
	}
294 295 296 297 298 299 300 301 302
}

gboolean
impl_regex_match (const ImplRegex   *regex,
                  const char        *string,
                  GRegexMatchFlags   match_options,
                  ImplMatchInfo    **match_info)
{
	g_return_val_if_fail (regex != NULL, FALSE);
303 304
	g_return_val_if_fail (regex->code != NULL, FALSE);
	g_return_val_if_fail (string != NULL, FALSE);
305

306
	return impl_regex_match_full (regex, string, -1, 0, match_options, match_info, NULL);
307 308 309 310 311 312
}

char *
impl_match_info_fetch (const ImplMatchInfo *match_info,
                       int                  match_num)
{
313 314 315
	int begin =  -1;
	int end =  -1;

316
	g_return_val_if_fail (match_info != NULL, NULL);
317 318 319 320 321 322 323 324 325 326 327 328 329
	g_return_val_if_fail (match_info->string != NULL, NULL);
	g_return_val_if_fail (match_info->offsets != NULL, NULL);
	g_return_val_if_fail (impl_match_info_matches (match_info), NULL);

	if (impl_match_info_fetch_pos (match_info, match_num, &begin, &end))
	{
		if (begin >= 0 && end >= 0)
		{
			return g_strndup (match_info->string + begin, end - begin);
		}

		return g_strdup ("");
	}
330

331
	return NULL;
332 333 334 335 336 337
}

char *
impl_match_info_fetch_named (const ImplMatchInfo *match_info,
                             const char          *name)
{
338 339 340
	int begin = -1;
	int end = -1;

341 342
	g_return_val_if_fail (match_info != NULL, NULL);

343 344 345 346 347 348 349 350 351 352
	if (match_info->start_pos < match_info->string_len)
	{
		if (impl_match_info_fetch_named_pos (match_info, name, &begin, &end))
		{
			if (begin >= 0 && end >= 0)
			{
				return g_strndup (match_info->string + begin, end - begin);
			}
		}
	}
353

354
	return NULL;
355 356 357 358 359 360
}

char *
impl_regex_replace_eval (const ImplRegex        *regex,
                         const char             *string,
                         gssize                  string_len,
361
                         gsize                   start_position,
362 363 364 365 366
                         GRegexMatchFlags        match_options,
                         ImplRegexEvalCallback   eval,
                         gpointer                user_data,
                         GError                **error)
{
367 368 369 370 371
	ImplMatchInfo *match_info;
	GString *result;
	gsize str_pos = 0;
	gboolean done = FALSE;
	GError *tmp_error = NULL;
372 373

	g_return_val_if_fail (regex != NULL, NULL);
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	g_return_val_if_fail (string != NULL, NULL);
	g_return_val_if_fail (eval != NULL, NULL);

	if (string_len < 0)
	{
		string_len = strlen (string);
	}

	result = g_string_sized_new (string_len);

	/* run down the string making matches. */
	impl_regex_match_full (regex,
	                       string,
	                       string_len,
	                       start_position,
	                       match_options,
	                       &match_info,
	                       &tmp_error);

	g_assert (match_info != NULL);

	while (!done && impl_match_info_matches (match_info))
	{
		g_string_append_len (result,
		                     string + str_pos,
		                     match_info->offsets[0] - str_pos);
		done = (*eval) (match_info, result, user_data);
		str_pos = match_info->offsets[1];
		impl_match_info_next (match_info, &tmp_error);
	}

	impl_match_info_free (match_info);

	if (tmp_error != NULL)
	{
		g_propagate_error (error, tmp_error);
		g_string_free (result, TRUE);
		return NULL;
	}

	g_string_append_len (result, string + str_pos, string_len - str_pos);

	return g_string_free (result, FALSE);
417 418 419 420 421 422
}

gboolean
impl_regex_match_full (const ImplRegex   *regex,
                       const char        *string,
                       gssize             string_len,
423
                       gsize              start_position,
424 425 426 427
                       GRegexMatchFlags   match_options,
                       ImplMatchInfo    **match_info,
                       GError           **error)
{
428 429
	ImplMatchInfo *local_match_info = NULL;
	gboolean ret = FALSE;
430 431

	g_return_val_if_fail (regex != NULL, FALSE);
432 433 434 435 436 437 438 439 440 441 442
	g_return_val_if_fail (regex->code != NULL, FALSE);
	g_return_val_if_fail (match_options == 0, FALSE);
	g_return_val_if_fail (string != NULL, FALSE);

	if (string_len < 0)
	{
		string_len = strlen (string);
	}

	local_match_info = impl_match_info_new ((ImplRegex *)regex, match_options, string, string_len);
	local_match_info->start_pos = start_position;
443

444
	ret = impl_match_info_next (local_match_info, error);
445 446 447

	if (match_info != NULL)
	{
448
		*match_info = g_steal_pointer (&local_match_info);
449 450 451
	}
	else
	{
452
		impl_match_info_free (local_match_info);
453 454 455 456 457 458 459
	}

	return ret;
}

gboolean
impl_match_info_fetch_pos (const ImplMatchInfo *match_info,
460
                           guint                match_num,
461 462 463 464
                           int                 *start_pos,
                           int                 *end_pos)
{
	g_return_val_if_fail (match_info != NULL, FALSE);
465 466 467 468 469 470 471
	g_return_val_if_fail (match_info->match_data != NULL, FALSE);
	g_return_val_if_fail (match_info->offsets != NULL, FALSE);

	if (match_info->n_groups > 0 && match_num < match_info->n_groups)
	{
		if (start_pos)
			*start_pos = match_info->offsets[2*match_num];
472

473 474 475 476 477 478 479
		if (end_pos)
			*end_pos = match_info->offsets[2*match_num+1];

		return TRUE;
	}

	return FALSE;
480 481 482 483 484 485 486 487
}

gboolean
impl_match_info_fetch_named_pos (const ImplMatchInfo *match_info,
                                 const char          *name,
                                 int                 *start_pos,
                                 int                 *end_pos)
{
488 489
	PCRE2_SPTR tabptr;

490
	g_return_val_if_fail (match_info != NULL, FALSE);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	g_return_val_if_fail (match_info->match_data != NULL, FALSE);
	g_return_val_if_fail (match_info->regex != NULL, FALSE);
	g_return_val_if_fail (start_pos != NULL, FALSE);
	g_return_val_if_fail (end_pos != NULL, FALSE);

	tabptr = match_info->regex->name_table;

	for (gsize i = 0; i < match_info->regex->name_count; i++)
	{
		PCRE2_SIZE n = (tabptr[0] << 8) | tabptr[1];

		if (g_strcmp0 (name, (const char *)(tabptr+2)) == 0)
		{
			return impl_match_info_fetch_pos (match_info, n, start_pos, end_pos);
		}

		tabptr += match_info->regex->name_entry_size;
	}

	return FALSE;
}

gboolean
impl_match_info_matches (const ImplMatchInfo *match_info)
{
	g_return_val_if_fail (match_info != NULL, FALSE);
	g_return_val_if_fail (match_info->n_groups != 0, FALSE);

	return match_info->n_groups > 0;
}

gboolean
impl_match_info_next (ImplMatchInfo  *match_info,
                      GError        **error)
{
	gssize prev_end;
	gssize prev_begin;
	int rc;

	GTK_SOURCE_PROFILER_BEGIN_MARK;

	g_assert (match_info != NULL);
	g_assert (match_info->regex != NULL);
	g_assert (match_info->regex->code != NULL);
	g_assert (match_info->offsets == pcre2_get_ovector_pointer (match_info->match_data));

again:
	match_info->n_groups = -1;

	if (match_info->start_pos >= match_info->string_len)
	{
		return FALSE;
	}

	prev_begin = match_info->offsets[0];
	prev_end = match_info->offsets[1];

	rc = pcre2_match (match_info->regex->code,
	                  (PCRE2_SPTR)match_info->string,
	                  match_info->string_len,
	                  match_info->start_pos,
	                  match_info->match_flags,
	                  match_info->match_data,
	                  NULL);

	if (set_regex_error (error, rc))
	{
		match_info->n_groups = -1;
		match_info->start_pos = match_info->string_len + 1;
		return FALSE;
	}

	if (prev_end == match_info->offsets[1])
	{
		const char *next = g_utf8_next_char (match_info->string + prev_end);

		if (match_info->start_pos > match_info->string_len)
		{
			match_info->start_pos = match_info->string_len + 1;
			match_info->n_groups = -1;
			return FALSE;
		}

		match_info->start_pos = next - match_info->string;
	}
	else
	{
		match_info->start_pos = match_info->offsets[1];
	}

	if (match_info->n_groups >= 0 &&
	    prev_begin == match_info->offsets[0] &&
	    prev_end == match_info->offsets[1])
	{
		goto again;
	}

	match_info->n_groups = rc;

	g_assert (match_info->offsets == pcre2_get_ovector_pointer (match_info->match_data));
	g_assert (impl_match_info_matches (match_info));

	GTK_SOURCE_PROFILER_END_MARK (G_STRFUNC, NULL);
594

595
	return impl_match_info_matches (match_info);
596
}