MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
normalizers.cpp
Go to the documentation of this file.
1#include <algorithm>
2#include <iterator>
3#include <numeric>
4#include <ranges>
5
7#include <fe/assert.h>
8
9#include <mim/axm.h>
10#include <mim/def.h>
11#include <mim/driver.h>
12#include <mim/tuple.h>
13#include <mim/world.h>
14
16
18using Ranges = fe::Vector<Range>;
19
20namespace mim::plug::regex {
21
22template<quant id>
23const Def* normalize_quant(const Def* type, const Def* callee, const Def* arg) {
24 auto& world = type->world();
25
26 // quantifiers are idempotent
27 if (Axm::isa(id, arg)) return arg;
28
29 if constexpr (id == quant::plus) {
30 // (\d?)+ and (\d*)+ == \d*
31 if (auto optional_app = Axm::isa(quant::optional, arg))
32 return world.call(quant::star, optional_app->arg());
33 else if (auto star_app = Axm::isa(quant::star, arg))
34 return arg;
35 } else if constexpr (id == quant::star) {
36 // (\d?)* and (\d+)* == \d*
37 if (auto quant_app = Axm::isa<quant>(arg)) return world.app(callee, quant_app->arg());
38 } else if constexpr (id == quant::optional) {
39 // (\d*)? and (\d+)? == \d*
40 if (auto star_app = Axm::isa(quant::star, arg))
41 return arg;
42 else if (auto plus_app = Axm::isa(quant::plus, arg))
43 return world.call(quant::star, plus_app->arg());
44 }
45
46 return {};
47}
48
49template<class ConjOrDisj>
51 assert(!args.empty());
52 auto& world = args.front()->world();
53 return std::accumulate(args.begin() + 1, args.end(), args.front(), [&world](const Def* lhs, const Def* rhs) {
54 return world.call<ConjOrDisj, false>(Defs{lhs, rhs});
55 });
56}
57
58const Def* normalize_conj(const Def* type, const Def* callee, const Def* arg) {
59 auto& world = type->world();
60 world.log().d("conj {}: {} ({})", callee, type, arg);
61
62 if (auto a = Lit::isa(arg->arity())) {
63 switch (*a) {
64 case 0: return world.lit_tt();
65 case 1: return arg;
66 default:
67 if (auto args = detail::flatten_in_arg<conj>(arg); !args.empty())
68 return make_binary_tree<conj>(args);
69 else
70 return world.annex<empty>();
71 }
72 }
73
74 return {};
75}
76
77bool compare_re(const Def* lhs, const Def* rhs) {
78 auto lhs_range = Axm::isa<range>(lhs);
79 auto rhs_range = Axm::isa<range>(rhs);
80 // sort ranges by increasing lower bound
81 if (lhs_range && rhs_range) return Lit::as(lhs_range->arg()->proj(0)) < Lit::as(rhs_range->arg()->proj(0));
82 // ranges to the end
83 if (lhs_range) return false;
84 if (rhs_range) return true;
85
86 return lhs->gid() < rhs->gid(); // make irreflexive
87}
88
90 std::stable_sort(args.begin(), args.end(), &compare_re);
91 {
92 auto new_end = std::unique(args.begin(), args.end());
93 args.erase(new_end, args.end());
94 }
95}
96
97bool is_in_range(Range range, nat_t needle) { return needle >= range.first && needle <= range.second; }
98
99auto get_range(const Def* rng) -> Range {
100 auto rng_match = Axm::isa<range, false>(rng);
101 return {Lit::as<std::uint8_t>(rng_match->arg(0)), Lit::as<std::uint8_t>(rng_match->arg(1))};
102}
103
104struct app_range {
106 const Def* operator()(Range rng) { return w.call<range>(Defs{w.lit_i8(rng.first), w.lit_i8(rng.second)}); }
107};
108
109void merge_ranges(DefVec& args) {
110 auto ranges_begin = args.begin();
111 while (ranges_begin != args.end() && !Axm::isa<range>(*ranges_begin))
112 ranges_begin++;
113 if (ranges_begin == args.end()) return;
114
115 Ranges old_ranges;
116 auto& world = (*ranges_begin)->world();
117
118 std::transform(ranges_begin, args.end(), std::back_inserter(old_ranges), get_range);
119
120 auto new_ranges = automaton::merge_ranges(old_ranges, [&world](std::string_view msg) { world.log().d("{}", msg); });
121
122 // invalidates ranges_begin
123 args.erase(ranges_begin, args.end());
124 std::transform(new_ranges.begin(), new_ranges.end(), std::back_inserter(args), app_range{world});
125
126 make_vector_unique(args);
127}
128
129template<cls A, cls B>
130bool equals_any(const Def* cls0, const Def* cls1) {
131 return (Axm::isa(A, cls0) && Axm::isa(B, cls1)) || (Axm::isa(A, cls1) && Axm::isa(B, cls0));
132}
133
134bool equals_any(const Def* lhs, const Def* rhs) {
135 auto check_arg_equiv = [](const Def* lhs, const Def* rhs) {
136 if (auto rng_lhs = Axm::isa<range>(lhs))
137 if (auto not_rhs = Axm::isa<not_>(rhs)) {
138 if (auto rng_rhs = Axm::isa<range>(not_rhs->arg())) return rng_lhs == rng_rhs;
139 }
140 return false;
141 };
142
143 return check_arg_equiv(lhs, rhs) || check_arg_equiv(rhs, lhs);
144}
145
146bool equals_any(Defs lhs, Defs negated_rhs) {
147 auto is_range = [](const Def* d) { return Axm::isa<range>(d); };
148 auto to_range = std::views::filter(is_range) | std::views::transform(get_range);
149 auto rhs_view = negated_rhs | to_range;
150
151 if (std::ranges::distance(rhs_view) != std::ranges::distance(negated_rhs)) return false;
152
153 return std::ranges::includes(lhs | to_range, rhs_view);
154}
155
156const Def* normalize_disj(const Def* type, const Def*, const Def* arg) {
157 auto& world = type->world();
158 if (auto a = Lit::isa(arg->arity())) {
159 switch (*a) {
160 case 0: return world.lit_ff();
161 case 1: return arg;
162 default:
163 auto new_args = detail::flatten_in_arg<disj>(arg);
164
165 const bool contains_any
166 = std::ranges::find_if(new_args, [](const Def* ax) -> bool { return Axm::isa<any>(ax); })
167 != new_args.end();
168 const bool contains_empty
169 = std::ranges::find_if(new_args, [](const Def* ax) -> bool { return Axm::isa<empty>(ax); })
170 != new_args.end();
171
172 auto make_any = [&world, contains_empty]() {
173 if (contains_empty)
174 // (any|) matches everything, including empty string
175 // don't normalize again, as we'd just run into this normalizer again..
176 return world.call<disj, false>(Defs{world.annex<any>(), world.annex<empty>()});
177 else
178 return world.annex<any>();
179 };
180
181 if (contains_any) return make_any();
182 make_vector_unique(new_args);
183 merge_ranges(new_args);
184
185 const Def* to_remove = nullptr;
186 for (const auto* cls0 : new_args) {
187 for (const auto* cls1 : new_args)
188 if (equals_any(cls0, cls1)) return make_any();
189
190 if (auto not_rhs = Axm::isa<not_>(cls0)) {
191 if (auto disj_rhs = Axm::isa<disj>(not_rhs->arg())) {
192 auto rngs = detail::flatten_in_arg<disj>(disj_rhs->arg());
193 make_vector_unique(rngs);
194 if (equals_any(new_args, rngs)) return make_any();
195 }
196 }
197 }
198
199 erase(new_args, to_remove);
200 world.log().d("final ranges: {}", fe::Join(new_args));
201
202 if (new_args.size() > 2) return make_binary_tree<disj>(new_args);
203 if (new_args.size() > 1) return world.call<disj, false>(new_args);
204 return new_args.back();
205 }
206 }
207 return {};
208}
209
210const Def* normalize_range(const Def* type, const Def* callee, const Def* arg) {
211 auto& world = type->world();
212 auto [lhs, rhs] = arg->projs<2>();
213
214 if (!lhs->isa<Var>() && !rhs->isa<Var>()) // before first PE.
215 if (lhs->as<Lit>()->get() > rhs->as<Lit>()->get()) return world.raw_app(type, callee, {rhs, lhs});
216
217 return {};
218}
219
220const Def* any_unwanted_for_not(const Def* arg) {
221 if (auto ax = Axm::isa<regex::range>(arg)) return nullptr;
222 if (auto ax = Axm::isa<regex::not_>(arg)) return nullptr;
223 if (auto ax = Axm::isa<regex::any>(arg)) return nullptr;
224 if (auto disj = Axm::isa<regex::disj>(arg)) {
225 for (const auto* disj_arg : disj->args())
226 if (auto ret = any_unwanted_for_not(disj_arg)) return ret;
227 return nullptr;
228 }
229 return arg;
230}
231
232const Def* normalize_not(const Def*, const Def* callee, const Def* arg) {
233 if (auto unwanted = any_unwanted_for_not(arg)) {
234 arg->blame("regex.not_ must only be used with regex.disj, regex.range, regex.any and regex.not_: {} {}", callee,
235 arg)
236 .n("found unwanted: {}", unwanted)
237 .bail();
238 }
239 return {};
240}
241
243
244} // namespace mim::plug::regex
static auto isa(const Def *def)
Definition axm.h:112
Base class for all Defs.
Definition def.h:273
auto projs(F f) const
Splits this Def via Def::projections into an Array (if A == std::dynamic_extent) or std::array (other...
Definition def.h:440
fe::Error & blame(fe::cite_string< Args... > s, Args &&... args) const
Reports an error that blames this; chain Error::n for Notes and Error::bail to throw.
Definition def.h:310
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
Definition def.h:294
const Def * arity() const
Number of elements available to Extract / Insert (may be dynamic).
Definition def.cpp:592
static std::optional< T > isa(const Def *def)
Definition def.h:937
T get() const
Definition def.h:924
static T as(const Def *def)
Definition def.h:943
A variable introduced by a binder (mutable).
Definition def.h:825
The World represents the whole program and manages creation of MimIR nodes (Defs).
Definition world.h:40
fe::Vector< Range > Ranges
automaton::Range Range
std::pair< std::uint64_t, std::uint64_t > Range
std::optional< Range > merge_ranges(Range a, Range b) noexcept
The regex Plugin
Definition lower_regex.h:5
void merge_ranges(DefVec &args)
void make_vector_unique(DefVec &args)
auto get_range(const Def *rng) -> Range
bool is_in_range(Range range, nat_t needle)
const Def * normalize_conj(const Def *type, const Def *callee, const Def *arg)
const Def * normalize_range(const Def *type, const Def *callee, const Def *arg)
const Def * normalize_disj(const Def *type, const Def *, const Def *arg)
const Def * normalize_quant(const Def *type, const Def *callee, const Def *arg)
const Def * normalize_not(const Def *, const Def *callee, const Def *arg)
bool compare_re(const Def *lhs, const Def *rhs)
const Def * make_binary_tree(Defs args)
const Def * any_unwanted_for_not(const Def *arg)
bool equals_any(const Def *cls0, const Def *cls1)
u64 nat_t
Definition types.h:37
fe::View< const Def * > Defs
Definition def.h:91
fe::Vector< const Def * > DefVec
Definition def.h:93
#define MIM_regex_NORMALIZER_IMPL
Definition autogen.h:107
const Def * operator()(Range rng)