mirror of
https://github.com/RGBCube/serenity
synced 2025-10-13 19:52:19 +00:00

This commit is a mix of several commits, squashed into one because the commits before 'Move regex to own Library and fix all the broken stuff' were not fixable in any elegant way. The commits are listed below for "historical" purposes: - AK: Add options/flags and Errors for regular expressions Flags can be provided for any possible flavour by adding a new scoped enum. Handling of flags is done by templated Options class and the overloaded '|' and '&' operators. - AK: Add Lexer for regular expressions The lexer parses the input and extracts tokens needed to parse a regular expression. - AK: Add regex Parser and PosixExtendedParser This patchset adds a abstract parser class that can be derived to implement different parsers. A parser produces bytecode to be executed within the regex matcher. - AK: Add regex matcher This patchset adds an regex matcher based on the principles of the T-REX VM. The bytecode pruduced by the respective Parser is put into the matcher and the VM will recursively execute the bytecode according to the available OpCodes. Possible improvement: the recursion could be replaced by multi threading capabilities. To match a Regular expression, e.g. for the Posix standard regular expression matcher use the following API: ``` Pattern<PosixExtendedParser> pattern("^.*$"); auto result = pattern.match("Well, hello friends!\nHello World!"); // Match whole needle EXPECT(result.count == 1); EXPECT(result.matches.at(0).view.starts_with("Well")); EXPECT(result.matches.at(0).view.end() == "!"); result = pattern.match("Well, hello friends!\nHello World!", PosixFlags::Multiline); // Match line by line EXPECT(result.count == 2); EXPECT(result.matches.at(0).view == "Well, hello friends!"); EXPECT(result.matches.at(1).view == "Hello World!"); EXPECT(pattern.has_match("Well,....")); // Just check if match without a result, which saves some resources. ``` - AK: Rework regex to work with opcodes objects This patchsets reworks the matcher to work on a more structured base. For that an abstract OpCode class and derived classes for the specific OpCodes have been added. The respective opcode logic is contained in each respective execute() method. - AK: Add benchmark for regex - AK: Some optimization in regex for runtime and memory - LibRegex: Move regex to own Library and fix all the broken stuff Now regex works again and grep utility is also in place for testing. This commit also fixes the use of regex.h in C by making `regex_t` an opaque (-ish) type, which makes its behaviour consistent between C and C++ compilers. Previously, <regex.h> would've blown C compilers up, and even if it didn't, would've caused a leak in C code, and not in C++ code (due to the existence of `OwnPtr` inside the struct). To make this whole ordeal easier to deal with (for now), this pulls the definitions of `reg*()` into LibRegex. pros: - The circular dependency between LibC and LibRegex is broken - Eaiser to test (without accidentally pulling in the host's libc!) cons: - Using any of the regex.h functions will require the user to link -lregex - The symbols will be missing from libc, which will be a big surprise down the line (especially with shared libs). Co-Authored-By: Ali Mohammad Pur <ali.mpfard@gmail.com>
257 lines
7.8 KiB
Text
257 lines
7.8 KiB
Text
/*
|
|
* Copyright (c) 2020, Emanuel Sprung <emanuel.sprung@gmail.com>
|
|
* All rights reserved.
|
|
*
|
|
* Redistribution and use in source and binary forms, with or without
|
|
* modification, are permitted provided that the following conditions are met:
|
|
*
|
|
* 1. Redistributions of source code must retain the above copyright notice, this
|
|
* list of conditions and the following disclaimer.
|
|
*
|
|
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
|
* this list of conditions and the following disclaimer in the documentation
|
|
* and/or other materials provided with the distribution.
|
|
*
|
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include "RegexError.h"
|
|
#include "RegexLexer.h"
|
|
#include "RegexOptions.h"
|
|
#include <AK/Forward.h>
|
|
#include <AK/Types.h>
|
|
#include <AK/Vector.h>
|
|
|
|
namespace AK {
|
|
namespace regex {
|
|
|
|
#define ENUMERATE_OPCODES \
|
|
__ENUMERATE_OPCODE(Compare) \
|
|
__ENUMERATE_OPCODE(Jump) \
|
|
__ENUMERATE_OPCODE(ForkJump) \
|
|
__ENUMERATE_OPCODE(ForkStay) \
|
|
__ENUMERATE_OPCODE(SaveLeftCaptureGroup) \
|
|
__ENUMERATE_OPCODE(SaveRightCaptureGroup) \
|
|
__ENUMERATE_OPCODE(SaveLeftNamedCaptureGroup) \
|
|
__ENUMERATE_OPCODE(SaveRightNamedCaptureGroup) \
|
|
__ENUMERATE_OPCODE(CheckBegin) \
|
|
__ENUMERATE_OPCODE(CheckEnd) \
|
|
__ENUMERATE_OPCODE(Exit)
|
|
|
|
enum class OpCode : u8 {
|
|
#define __ENUMERATE_OPCODE(x) x,
|
|
ENUMERATE_OPCODES
|
|
#undef __ENUMERATE_OPCODE
|
|
};
|
|
|
|
enum class CharacterCompareType : u8 {
|
|
Undefined,
|
|
Inverse,
|
|
AnySingleCharacter,
|
|
OrdinaryCharacter,
|
|
OrdinaryCharacters,
|
|
CharacterClass,
|
|
RangeExpression,
|
|
RangeExpressionDummy,
|
|
};
|
|
|
|
enum class CharacterClass : u8 {
|
|
Alnum,
|
|
Cntrl,
|
|
Lower,
|
|
Space,
|
|
Alpha,
|
|
Digit,
|
|
Print,
|
|
Upper,
|
|
Blank,
|
|
Graph,
|
|
Punct,
|
|
Xdigit,
|
|
};
|
|
|
|
class ByteCodeValue {
|
|
public:
|
|
union CompareValue {
|
|
CompareValue(const CharacterClass value)
|
|
: character_class(value)
|
|
{
|
|
}
|
|
CompareValue(const char value1, const char value2)
|
|
: range_values { value1, value2 }
|
|
{
|
|
}
|
|
const CharacterClass character_class;
|
|
const struct {
|
|
const char from;
|
|
const char to;
|
|
} range_values;
|
|
};
|
|
|
|
union {
|
|
const OpCode op_code;
|
|
const char* string;
|
|
const char ch;
|
|
const int number;
|
|
const size_t positive_number;
|
|
const CompareValue compare_value;
|
|
const CharacterCompareType compare_type;
|
|
};
|
|
|
|
const char* name() const;
|
|
static const char* name(OpCode);
|
|
|
|
ByteCodeValue(const OpCode value)
|
|
: op_code(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const char* value)
|
|
: string(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const char value)
|
|
: ch(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const int value)
|
|
: number(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const size_t value)
|
|
: positive_number(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const CharacterClass value)
|
|
: compare_value(value)
|
|
{
|
|
}
|
|
ByteCodeValue(const char value1, const char value2)
|
|
: compare_value(value1, value2)
|
|
{
|
|
}
|
|
ByteCodeValue(const CharacterCompareType value)
|
|
: compare_type(value)
|
|
{
|
|
}
|
|
|
|
~ByteCodeValue() = default;
|
|
};
|
|
|
|
struct CompareTypeAndValuePair {
|
|
CharacterCompareType type;
|
|
ByteCodeValue value;
|
|
};
|
|
|
|
struct ParserResult {
|
|
Vector<ByteCodeValue> m_bytes;
|
|
size_t m_match_groups;
|
|
size_t m_min_match_length;
|
|
Error m_error;
|
|
Token m_error_token;
|
|
};
|
|
|
|
template<class T>
|
|
class Parser {
|
|
public:
|
|
explicit Parser(Lexer& lexer)
|
|
: m_parser_state(lexer)
|
|
{
|
|
}
|
|
|
|
Parser(Lexer& lexer, T options)
|
|
: m_parser_state(lexer, options)
|
|
{
|
|
}
|
|
|
|
virtual ~Parser() = default;
|
|
|
|
virtual ParserResult parse(T options = {}, EngineOptions engine_options = {});
|
|
bool has_error() const { return m_parser_state.m_error != Error::NoError; }
|
|
Error error() const { return m_parser_state.m_error; }
|
|
|
|
protected:
|
|
virtual bool parse_internal(Vector<ByteCodeValue>&, size_t& min_length) = 0;
|
|
|
|
bool match(TokenType type) const;
|
|
bool match(char ch) const;
|
|
Token consume();
|
|
Token consume(TokenType type, Error error = Error::InvalidPattern);
|
|
bool consume(const String&);
|
|
void reset();
|
|
bool done() const;
|
|
|
|
bool set_error(Error error);
|
|
|
|
void insert_bytecode_compare_values(Vector<ByteCodeValue>&, Vector<CompareTypeAndValuePair>&&);
|
|
void insert_bytecode_group_capture_left(Vector<ByteCodeValue>& stack);
|
|
void insert_bytecode_group_capture_right(Vector<ByteCodeValue>& stack);
|
|
void insert_bytecode_group_capture_left(Vector<ByteCodeValue>& stack, const StringView& name);
|
|
void insert_bytecode_group_capture_right(Vector<ByteCodeValue>& stack, const StringView& name);
|
|
void insert_bytecode_alternation(Vector<ByteCodeValue>& stack, Vector<ByteCodeValue>&&, Vector<ByteCodeValue>&&);
|
|
void insert_bytecode_repetition_min_max(Vector<ByteCodeValue>& bytecode_to_repeat, size_t minimum, Optional<size_t> maximum);
|
|
void insert_bytecode_repetition_n(Vector<ByteCodeValue>& stack, Vector<ByteCodeValue>& bytecode_to_repeat, size_t n);
|
|
void insert_bytecode_repetition_min_one(Vector<ByteCodeValue>& bytecode_to_repeat, bool greedy);
|
|
void insert_bytecode_repetition_any(Vector<ByteCodeValue>& bytecode_to_repeat, bool greedy);
|
|
void insert_bytecode_repetition_zero_or_one(Vector<ByteCodeValue>& bytecode_to_repeat, bool greedy);
|
|
|
|
struct ParserState {
|
|
Lexer& lexer;
|
|
Token current_token;
|
|
Error error = Error::NoError;
|
|
Token error_token { TokenType::Eof, 0, StringView(nullptr) };
|
|
Vector<ByteCodeValue> bytecode;
|
|
size_t capture_groups_count { 0 };
|
|
size_t named_capture_groups_count { 0 };
|
|
size_t match_length_minimum { 0 };
|
|
OptionsType regex_options;
|
|
explicit ParserState(Lexer& lexer)
|
|
: lexer(lexer)
|
|
, current_token(lexer.next())
|
|
{
|
|
}
|
|
explicit ParserState(Lexer& lexer, Optional<OptionsType> regex_options)
|
|
: lexer(lexer)
|
|
, current_token(lexer.next())
|
|
, regex_options(regex_options.value_or({}))
|
|
{
|
|
}
|
|
};
|
|
|
|
ParserState m_parser_state;
|
|
};
|
|
|
|
class PosixExtendedParser final : public Parser<PosixOptions> {
|
|
public:
|
|
explicit PosixExtendedParser(Lexer& lexer)
|
|
: Parser(lexer) {};
|
|
PosixExtendedParser(Lexer& lexer, Optional<OptionsType> regex_options)
|
|
: Parser(lexer, regex_options) {};
|
|
~PosixExtendedParser() = default;
|
|
|
|
private:
|
|
bool match_repetition_symbol();
|
|
bool match_ordinary_characters();
|
|
|
|
bool parse_internal(Vector<ByteCodeValue>&, size_t&) override;
|
|
|
|
bool parse_root(Vector<ByteCodeValue>&, size_t&);
|
|
bool parse_sub_expression(Vector<ByteCodeValue>&, size_t&);
|
|
bool parse_bracket_expression(Vector<ByteCodeValue>&, size_t&);
|
|
bool parse_repetition_symbol(Vector<ByteCodeValue>&, size_t&);
|
|
};
|
|
}
|
|
}
|
|
|
|
using AK::regex::ParserResult;
|
|
using AK::regex::PosixExtendedParser;
|