Coverage Report

Created: 2026-12-01 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hobbes/lib/hobbes/lang/pat/dfa.C
Line
Count
Source
1
#include <hobbes/hobbes.H>
2
#include <hobbes/util/llvm.H>
3
#include <hobbes/lang/pat/dfa.H>
4
#include <hobbes/lang/pat/regex.H>
5
#include <hobbes/lang/pat/print.H>
6
#include <hobbes/util/perf.H>
7
#include <cstddef>
8
#include <limits>
9
#include <sstream>
10
#include <fstream>
11
12
#include <hobbes/eval/cc.H>
13
#include <hobbes/eval/cexpr.H>
14
15
namespace hobbes {
16
17
stateidx_t nullState = static_cast<stateidx_t>(-1);
18
19
// match DFA state defs
20
0
MState::MState(int cid) : refs(0), isPrimMatchRoot(false), cid(cid) { }
21
0
int MState::case_id() const { return this->cid; }
22
23
0
LoadVars::LoadVars(const Defs& ds, stateidx_t next) : ds(ds), next(next) { }
24
0
const LoadVars::Defs& LoadVars::defs() const { return this->ds; }
25
0
stateidx_t LoadVars::nextState() const { return this->next; }
26
27
0
std::string LoadVars::stamp() {
28
0
  std::ostringstream ss;
29
0
  ss << "l";
30
0
  for (const auto& d : this->ds) {
31
0
    ss << "." << d.first << "=" << reinterpret_cast<void*>(d.second.get()); // assumes that we deliberately share equivalent expressions
32
0
  }
33
0
  ss << "." << this->next;
34
0
  return ss.str();
35
0
}
36
37
0
SwitchVal::SwitchVal(const std::string& var, const Jumps& jmps, stateidx_t def) : var(var), jmps(jmps), def(def) { }
38
0
const std::string& SwitchVal::switchVar() const { return this->var; }
39
0
const SwitchVal::Jumps& SwitchVal::jumps() const { return this->jmps; }
40
0
stateidx_t SwitchVal::defaultState() const { return this->def; }
41
42
0
std::string SwitchVal::stamp() {
43
0
  std::ostringstream ss;
44
0
  ss << "s." << this->var;
45
0
  for (const auto& j : this->jmps) {
46
0
    ss << ".";
47
0
    j.first->show(ss);
48
0
    ss << ":" << j.second;
49
0
  }
50
0
  ss << "." << this->def;
51
0
  return ss.str();
52
0
}
53
54
0
SwitchVariant::SwitchVariant(const std::string& var, const CtorJumps& jmps, stateidx_t def) : var(var), jmps(jmps), def(def) { }
55
0
const std::string& SwitchVariant::switchVar() const { return this->var; }
56
0
const SwitchVariant::CtorJumps& SwitchVariant::jumps() const { return this->jmps; }
57
0
stateidx_t SwitchVariant::defaultState() const { return this->def; }
58
59
0
std::string SwitchVariant::stamp() {
60
0
  std::ostringstream ss;
61
0
  ss << "c." << this->var;
62
0
  for (const auto& j : this->jmps) {
63
0
    ss << "." << j.first << "=" << j.second;
64
0
  }
65
0
  ss << "." << this->def;
66
0
  return ss.str();
67
0
}
68
69
0
FinishExpr::FinishExpr(const ExprPtr& exp) : exp(exp) { }
70
0
const ExprPtr& FinishExpr::expr() const { return this->exp; }
71
72
0
std::string FinishExpr::stamp() {
73
0
  std::ostringstream ss;
74
0
  ss << "e." << reinterpret_cast<void*>(this->exp.get());
75
0
  return ss.str();
76
0
}
77
78
// make a trivial state that performs a single action and continues
79
0
MStatePtr actAndThen(const ExprPtr& e, stateidx_t s) {
80
0
  LoadVars::Defs ds;
81
0
  ds.push_back(LoadVars::Def(freshName(), e));
82
0
  return MStatePtr(new LoadVars(ds, s));
83
0
}
84
85
// make a primitive value switch, validating exhaustiveness
86
0
MStatePtr makeSwitch(const MDFA* dfa, const std::string& switchVar, const SwitchVal::Jumps& jmps, stateidx_t defState) {
87
0
  if (defState != nullState) {
88
    // if we've only got a default switch and no cases, just use the default case
89
    // otherwise if this would be a 'switch' on unit, don't bother (just pass the type equality through)
90
    //  -- only the first option can match for unit (or default if there's only a default)
91
0
    if (jmps.empty()) {
92
0
      return dfa->states[defState];
93
0
    } else if (isUnit(jmps[0].first->primType())) {
94
0
      if (dfa->inPrimSel) {
95
0
        return dfa->states[jmps[0].second];
96
0
      }
97
0
      return actAndThen(assume(var(switchVar, dfa->rootLA), primty("unit"), dfa->rootLA), jmps[0].second);
98
0
    } else {
99
0
      return MStatePtr(new SwitchVal(switchVar, jmps, defState));
100
0
    }
101
0
  } else {
102
0
    if (!jmps.empty()) {
103
0
      MonoTypePtr sty = jmps[0].first->primType();
104
105
0
      if (const Prim* pty = is<Prim>(sty)) {
106
0
        if (pty->name() == "bool" && jmps.size() == 2) {
107
0
          return MStatePtr(new SwitchVal(switchVar, list(jmps[0]), jmps[1].second));
108
0
        } else if ((pty->name() == "char" || pty->name() == "byte") && jmps.size() == 256) {
109
0
          return MStatePtr(new SwitchVal(switchVar, SwitchVal::Jumps(jmps.begin(), jmps.end() - 1), jmps[jmps.size() - 1].second));
110
0
        } else if (pty->name() == "unit") {
111
0
          return actAndThen(assume(var(switchVar, dfa->rootLA), primty("unit"), dfa->rootLA), jmps[0].second);
112
0
        }
113
0
      }
114
0
    }
115
0
    throw annotated_error(dfa->rootLA, "Inexhaustive patterns in match expression");
116
0
  }
117
0
}
118
119
// increment the ref count for a given state in the DFA
120
0
void addRef(MDFA* dfa, stateidx_t s) {
121
0
  dfa->states[s]->refs += 1;
122
0
}
123
124
// add a state to the DFA and return its index
125
// (if the state already exists in the DFA, increment its reference count and return it)
126
0
stateidx_t addState(MDFA* dfa, const MStatePtr& state, bool addref = true) {
127
0
  StatesIdx::const_iterator si = dfa->statesIdx.find(state->stamp());
128
0
  if (si != dfa->statesIdx.end()) {
129
0
    dfa->states[si->second]->refs += addref ? 1 : 0;
130
0
    return si->second;
131
0
  }
132
133
  // create a new state, give it a ref count, determine which states it leads to
134
0
  stateidx_t s = dfa->states.size();
135
0
  dfa->states.push_back(state);
136
0
  dfa->statesIdx[state->stamp()] = s;
137
0
  state->refs += addref ? 1 : 0;
138
0
  return s;
139
0
}
140
141
// memoize common expressions
142
0
ExprPtr varName(MDFA* dfa, const std::string& vn) {
143
0
  VarNames::const_iterator ve = dfa->varExps.find(vn);
144
0
  if (ve != dfa->varExps.end()) {
145
0
    return ve->second;
146
0
  }
147
148
0
  ExprPtr r = var(vn, dfa->rootLA);
149
0
  dfa->varExps[vn] = r;
150
0
  return r;
151
0
}
152
153
0
ExprPtr arrayElement(MDFA* dfa, const std::string& vn, size_t i) {
154
0
  VarArrayElem::const_iterator ae = dfa->elementExps.find(vn);
155
0
  if (ae != dfa->elementExps.end()) {
156
0
    auto ie = ae->second.find(i);
157
0
    if (ie != ae->second.end()) {
158
0
      return ie->second;
159
0
    }
160
0
  }
161
162
0
  ExprPtr r = fncall(var("element", dfa->rootLA), list(varName(dfa, vn), ExprPtr(new Long(i, dfa->rootLA))), dfa->rootLA);
163
0
  dfa->elementExps[vn][i] = r;
164
0
  return r;
165
0
}
166
167
0
ExprPtr charArrElement(MDFA* dfa, const std::string& packFn, const std::string& vn, size_t i) {
168
0
  VarArrayElem::const_iterator ae = dfa->elementExps.find(vn);
169
0
  if (ae != dfa->elementExps.end()) {
170
0
    auto ie = ae->second.find(i);
171
0
    if (ie != ae->second.end()) {
172
0
      return ie->second;
173
0
    }
174
0
  }
175
176
0
  ExprPtr r = fncall(var(packFn, dfa->rootLA), list(varName(dfa, vn), ExprPtr(new Long(i, dfa->rootLA))), dfa->rootLA);
177
0
  dfa->elementExps[vn][i] = r;
178
0
  return r;
179
0
}
180
181
0
ExprPtr openArray(MDFA* dfa, const std::string& vn) {
182
0
  return fncall(var("openArrayView", dfa->rootLA), list(varName(dfa, vn)), dfa->rootLA);
183
0
}
184
185
0
ExprPtr arraySize(MDFA* dfa, const std::string& vn) {
186
0
  VarArrayLen::const_iterator al = dfa->sizeExps.find(vn);
187
0
  if (al != dfa->sizeExps.end()) {
188
0
    return al->second;
189
0
  }
190
191
0
  ExprPtr r = fncall(var("size", dfa->rootLA), list(varName(dfa, vn)), dfa->rootLA);
192
0
  dfa->sizeExps[vn] = r;
193
0
  return r;
194
0
}
195
196
0
ExprPtr field(MDFA* dfa, const std::string& vn, const std::string& fn) {
197
0
  VarStructField::const_iterator vsf = dfa->fieldExps.find(vn);
198
0
  if (vsf != dfa->fieldExps.end()) {
199
0
    auto sf = vsf->second.find(fn);
200
0
    if (sf != vsf->second.end()) {
201
0
      return sf->second;
202
0
    }
203
0
  }
204
205
0
  ExprPtr r = proj(varName(dfa, vn), fn, dfa->rootLA);
206
0
  dfa->fieldExps[vn][fn] = r;
207
0
  return r;
208
0
}
209
210
// produce a copy of a pattern table, without the head row
211
0
void tableTail(PatternRows* out, const PatternRows& in) {
212
0
  out->resize(in.size() - 1);
213
0
  for (size_t r = 1; r < in.size(); ++r) {
214
0
    (*out)[r - 1] = in[r];
215
0
  }
216
0
}
217
218
// eliminate unused columns from a table
219
0
void dropUnusedColumns(PatternRows* out, const PatternRows& in) {
220
0
  if (in.empty()) {
221
0
    return;
222
0
  }
223
224
0
  std::set<size_t> usedColumns;
225
0
  for (size_t c = 0; c < in[0].patterns.size(); ++c) {
226
0
    bool hasUse = false;
227
0
    for (const auto &r : in) {
228
0
      if (is<MatchAny>(r.patterns[c]) == nullptr) {
229
0
        hasUse = true;
230
0
        break;
231
0
      }
232
0
    }
233
0
    if (hasUse) {
234
0
      usedColumns.insert(c);
235
0
    }
236
0
  }
237
238
0
  if (usedColumns.size() == in[0].patterns.size()) {
239
0
    *out = in;
240
0
  } else {
241
0
    for (const auto &r : in) {
242
0
      Patterns ps;
243
0
      for (const auto c : usedColumns) {
244
0
        ps.push_back(r.patterns[c]);
245
0
      }
246
0
      out->push_back(PatternRow(ps, r.guard, r.result));
247
0
    }
248
0
  }
249
0
}
250
251
// split a row on a column written into an output table
252
0
void copyRowWithoutColumn(PatternRows* out, const PatternRow& row, size_t c) {
253
0
  Patterns ps;
254
0
  for (size_t ci = 0; ci < row.patterns.size(); ++ci) {
255
0
    if (ci != c) {
256
0
      ps.push_back(row.patterns[ci]);
257
0
    }
258
0
  }
259
0
  out->push_back(PatternRow(ps, row.guard, row.result));
260
0
}
261
262
// stick some patterns on the front of a pattern row
263
0
void prependPatterns(PatternRow* row, const Patterns& ps) {
264
0
  row->patterns.insert(row->patterns.begin(), ps.begin(), ps.end());
265
0
}
266
267
// get the sub-patterns in an array match
268
0
Patterns arrayPatterns(const MatchArray& ma) {
269
0
  Patterns r;
270
0
  r.reserve(ma.size());
271
0
  for (size_t i = 0; i < ma.size(); ++i) {
272
0
    r.push_back(ma.pattern(i));
273
0
  }
274
0
  return r;
275
0
}
276
277
// create an array of dummy "match anything" patterns
278
0
Patterns arrayAnyMatches(size_t n) {
279
0
  static PatternPtr pany(new MatchAny("_", LexicalAnnotation::null()));
280
0
  Patterns r;
281
0
  r.resize(n);
282
0
  for (size_t i = 0; i < n; ++i) { r[i] = pany; }
283
0
  return r;
284
0
}
285
286
// pull out the patterns from a record match
287
0
Patterns recordFieldPatterns(const MatchRecord& mr) {
288
0
  Patterns r;
289
0
  r.resize(mr.size());
290
0
  for (size_t i = 0; i < mr.size(); ++i) {
291
0
    r[i] = mr.pattern(i).second;
292
0
  }
293
0
  return r;
294
0
}
295
296
///////////////////////////////////////////////////
297
// makeSplitState
298
//
299
//   Purpose:
300
//     Creates a DFA state by splitting a pattern table on a given column generically
301
//
302
//   Inputs:
303
//     MType  ::: * - the match type split on
304
//     SValue ::: * - the primitive value type to switch on
305
//     svalueF :: MType -> SValue - extracts a primitive switch value from a match value
306
//     makeMatchRow :: MType*Row*Column -> [Row] | Produce a new row after having matched with the match value in the given row/column
307
//     makeMatchAnyRow :: SValue*Row*Column -> [Row] | Produce a new row from the given row/column after having switched on the given primitive value
308
//     makeNextState   :: Var*DFA*[Row] -> State     | Produce a successor state for a match on the given variable with a given DFA and successor match table
309
//     makeSwitchState :: Var*DFA*[(SValue,State)]*State | Produce a switch state on the given variable with the given set of value/state pairs and a default state
310
//
311
//   Outputs:
312
//     A DFA state description performing the required split
313
///////////////////////////////////////////////////
314
template <
315
  typename MType,
316
  typename SValue,
317
  SValue (*svalueF)(const MType&),
318
  void (*makeMatchRow)(const MType&, PatternRows*, const PatternRow&, size_t),
319
  void (*makeMatchAnyRow)(SValue, PatternRows*, const PatternRow&, size_t),
320
  stateidx_t (*makeNextState)(const std::string&, SValue, MDFA*, const PatternRows&),
321
  MStatePtr (*makeSwitchState)(const std::string&, MDFA*, const std::vector< std::pair<SValue, stateidx_t> >&, stateidx_t),
322
  typename SVLT = std::less<SValue>
323
>
324
0
MStatePtr makeSplitState(MDFA* dfa, const PatternRows& ps, size_t c) {
325
0
  using Branches = std::map<SValue, PatternRows, SVLT>;
326
0
  using BranchOrder = std::map<SValue, size_t>;
327
328
0
  Branches    bs;
329
0
  BranchOrder bos;
330
0
  Idxs        anys;
331
0
  PatternRows def;
332
333
  // accumulate branches for fixed cases
334
0
  for (size_t r = 0; r < ps.size(); ++r) {
335
0
    if (const MType* mt = is<MType>(ps[r].patterns[c])) {
336
0
      SValue sv = svalueF(*mt);
337
0
      if (bs.find(sv) == bs.end()) {
338
0
        bos[sv] = bs.size(); // remember branch introduction order (this is important for variants)
339
0
      }
340
0
      PatternRows& outrs = bs[sv];
341
342
      // the first time through this branch, we need to make sure that prior match-any rows are prepended
343
0
      if (outrs.empty()) {
344
0
        for (auto i : anys) {
345
0
          makeMatchAnyRow(sv, &outrs, ps[i], c);
346
0
        }
347
0
      }
348
349
      // add this row to the fixed branch
350
0
      makeMatchRow(*mt, &outrs, ps[r], c);
351
0
    } else if (is<MatchAny>(ps[r].patterns[c])) {
352
      // record where this match-any came from, then append it to all states recorded so far
353
0
      anys.push_back(r);
354
355
0
      for (auto b = bs.begin(); b != bs.end(); ++b) {
356
0
        makeMatchAnyRow(b->first, &b->second, ps[r], c);
357
0
      }
358
0
    } else {
359
0
      throw annotated_error(dfa->rootLA, "Internal error, invalid pattern table received");
360
0
    }
361
0
  }
362
363
  // now accumulate 'catch-all' rows into the default state
364
0
  for (auto i : anys) {
365
0
    copyRowWithoutColumn(&def, ps[i], c);
366
0
  }
367
368
  // finally, pull the branch and default jumps together (in introduction order) and make the new state
369
0
  using Jump = std::pair<SValue, stateidx_t>;
370
0
  using Jumps = std::vector<Jump>;
371
0
  Jumps jmps;
372
373
0
  jmps.resize(bs.size());
374
0
  for (const auto& b : bs) {
375
0
    jmps[bos[b.first]] = Jump(b.first, makeNextState(ps[0].patterns[c]->name(), b.first, dfa, b.second));
376
0
  }
377
378
0
  stateidx_t defState = !def.empty() ? makeDFAState(dfa, def) : nullState;
379
380
0
  return makeSwitchState(ps[0].patterns[c]->name(), dfa, jmps, defState);
381
0
}
Unexecuted instantiation: _ZN6hobbes14makeSplitStateINS_12MatchLiteralESt10shared_ptrINS_9PrimitiveEETnPFT0_RKT_EXadL_ZNS_8litValueERKS1_EETnPFvS8_PSt6vectorINS_10PatternRowESaISE_EERKSE_mEXadL_ZNS_15makeLitSplitRowESC_SH_SJ_mEETnPFvS5_SH_SJ_mEXadL_ZNS_12makeLSAnyRowES4_SH_SJ_mEETnPFmRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_PNS_4MDFAERKSG_EXadL_ZNS_15makeLSSuccStateESV_S4_SX_SZ_EETnPFS2_INS_6MStateEESV_SX_RKSD_ISt4pairIS5_mESaIS15_EEmEXadL_ZNS_15makeLSCvtSwitchESV_SX_RKSD_IS14_IS4_mESaIS1C_EEmEENS_9PrimPtrLTEEES13_SX_SZ_m
Unexecuted instantiation: _ZN6hobbes14makeSplitStateINS_12MatchLiteralESt10shared_ptrINS_9PrimitiveEETnPFT0_RKT_EXadL_ZNS_8litValueERKS1_EETnPFvS8_PSt6vectorINS_10PatternRowESaISE_EERKSE_mEXadL_ZNS_15makeLitSplitRowESC_SH_SJ_mEETnPFvS5_SH_SJ_mEXadL_ZNS_12makeLSAnyRowES4_SH_SJ_mEETnPFmRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_PNS_4MDFAERKSG_EXadL_ZNS_15makeLSSuccStateESV_S4_SX_SZ_EETnPFS2_INS_6MStateEESV_SX_RKSD_ISt4pairIS5_mESaIS15_EEmEXadL_ZNS_12makeLSSwitchESV_SX_RKSD_IS14_IS4_mESaIS1C_EEmEENS_9PrimPtrLTEEES13_SX_SZ_m
Unexecuted instantiation: _ZN6hobbes14makeSplitStateINS_10MatchArrayEmTnPFT0_RKT_EXadL_ZNS_6maSizeERKS1_EETnPFvS5_PSt6vectorINS_10PatternRowESaISB_EERKSB_mEXadL_ZNS_13makeASplitRowES9_SE_SG_mEETnPFvS2_SE_SG_mEXadL_ZNS_12makeASAnyRowEmSE_SG_mEETnPFmRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES2_PNS_4MDFAERKSD_EXadL_ZNS_15makeASSuccStateESS_mSU_SW_EETnPFSt10shared_ptrINS_6MStateEESS_SU_RKSA_ISt4pairIS2_mESaIS13_EEmEXadL_ZNS_12makeASSwitchESS_SU_RKSA_IS12_ImmESaIS1A_EEmEESt4lessImEEES11_SU_SW_m
Unexecuted instantiation: _ZN6hobbes14makeSplitStateINS_12MatchVariantENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEETnPFT0_RKT_EXadL_ZNS_7varCtorERKS1_EETnPFvSB_PSt6vectorINS_10PatternRowESaISH_EERKSH_mEXadL_ZNS_19makeVariantSplitRowESF_SK_SM_mEETnPFvS8_SK_SM_mEXadL_ZNS_12makeVSAnyRowES7_SK_SM_mEETnPFmRKS7_S8_PNS_4MDFAERKSJ_EXadL_ZNS_15makeVSSuccStateESS_S7_SU_SW_EETnPFSt10shared_ptrINS_6MStateEESS_SU_RKSG_ISt4pairIS8_mESaIS13_EEmEXadL_ZNS_12makeVSSwitchESS_SU_RKSG_IS12_IS7_mESaIS1A_EEmEESt4lessIS7_EEES11_SU_SW_m
382
383
// split on a primitive column into a switch state
384
0
PrimitivePtr litValue(const MatchLiteral& ml) { return ml.equivConstant(); }
385
0
void makeLitSplitRow(const MatchLiteral&, PatternRows* out, const PatternRow& r, size_t c) { copyRowWithoutColumn(out, r, c); }
386
0
void makeLSAnyRow(PrimitivePtr, PatternRows* out, const PatternRow& r, size_t c) { copyRowWithoutColumn(out, r, c); }
387
0
stateidx_t makeLSSuccState(const std::string&, PrimitivePtr, MDFA* dfa, const PatternRows& nps) { return makeDFAState(dfa, nps); }
388
389
0
MStatePtr makeLSSwitch(const std::string& switchVar, MDFA* dfa, const SwitchVal::Jumps& jmps, stateidx_t defState) {
390
0
  return makeSwitch(dfa, switchVar, jmps, defState);
391
0
}
392
393
0
MStatePtr makeLSCvtSwitch(const std::string& switchVar, MDFA* dfa, const SwitchVal::Jumps& jmps, stateidx_t defState) {
394
0
  std::string cvn = switchVar + ".cvt";
395
0
  LoadVars::Defs ds;
396
0
  ds.push_back(LoadVars::Def(cvn, fncall(var("convert", dfa->rootLA), list(var(switchVar, dfa->rootLA)), dfa->rootLA)));
397
0
  return MStatePtr(new LoadVars(ds, addState(dfa, makeLSSwitch(cvn, dfa, jmps, defState))));
398
0
}
399
400
0
bool forConvertibility(const PatternPtr& p) {
401
0
  if (const MatchLiteral* ml = is<MatchLiteral>(p)) {
402
0
    return ml->expression() != ExprPtr();
403
0
  } else {
404
0
    return false;
405
0
  }
406
0
}
407
408
0
MStatePtr makeLiteralState(MDFA* dfa, const PatternRows& ps, size_t c) {
409
0
  if (forConvertibility(ps[0].patterns[c])) {
410
0
    return
411
0
      makeSplitState<
412
0
        MatchLiteral,
413
0
        PrimitivePtr,
414
0
        &litValue,
415
0
        &makeLitSplitRow,
416
0
        &makeLSAnyRow,
417
0
        &makeLSSuccState,
418
0
        &makeLSCvtSwitch,
419
0
        PrimPtrLT
420
0
      >
421
0
      (dfa, ps, c);
422
0
  } else {
423
0
    return
424
0
      makeSplitState<
425
0
        MatchLiteral,
426
0
        PrimitivePtr,
427
0
        &litValue,
428
0
        &makeLitSplitRow,
429
0
        &makeLSAnyRow,
430
0
        &makeLSSuccState,
431
0
        &makeLSSwitch,
432
0
        PrimPtrLT
433
0
      >
434
0
      (dfa, ps, c);
435
0
  }
436
0
}
437
438
// split on array match columns into a length load and switch
439
0
size_t maSize(const MatchArray& ma) { return ma.size(); }
440
441
0
void makeASplitRow(const MatchArray& ma, PatternRows* out, const PatternRow& r, size_t c) {
442
0
  copyRowWithoutColumn(out, r, c);
443
0
  prependPatterns(&out->back(), arrayPatterns(ma));
444
0
}
445
446
0
void makeASAnyRow(size_t len, PatternRows* out, const PatternRow& r, size_t c) {
447
0
  copyRowWithoutColumn(out, r, c);
448
0
  prependPatterns(&out->back(), arrayAnyMatches(len));
449
0
}
450
451
0
stateidx_t makeASSuccState(const std::string& arrayVar, size_t len, MDFA* dfa, const PatternRows& nps) {
452
0
  LoadVars::Defs ds;
453
0
  for (size_t i = 0; i < len; ++i) {
454
0
    ds.push_back(LoadVars::Def(arrayVar + "." + str::from(i + 1), arrayElement(dfa, arrayVar, i)));
455
0
  }
456
0
  return addState(dfa, MStatePtr(new LoadVars(ds, makeDFAState(dfa, nps))));
457
0
}
458
459
0
MStatePtr makeASSwitch(const std::string& arrayVar, MDFA* dfa, const std::vector< std::pair<size_t, stateidx_t> >& lenjmps, stateidx_t defState) {
460
  // switch on array length, then load that many elements and continue
461
0
  std::string switchVar = arrayVar + ".0";
462
0
  SwitchVal::Jumps jmps;
463
0
  for (const auto& lj : lenjmps) {
464
0
    jmps.push_back(SwitchVal::Jump(PrimitivePtr(new Long(lj.first, dfa->rootLA)), lj.second));
465
0
  }
466
467
  // open an array view out of this value (for most types this should be a no-op)
468
  // load array length
469
  // and then perform the switch
470
0
  std::string oarrayVar = arrayVar + ".a";
471
472
0
  stateidx_t switchState = addState(dfa, makeSwitch(dfa, switchVar, jmps, defState));
473
0
  LoadVars::Defs ds;
474
0
  ds.push_back(LoadVars::Def(oarrayVar, openArray(dfa, arrayVar)));
475
0
  ds.push_back(LoadVars::Def(switchVar, arraySize(dfa, oarrayVar)));
476
477
0
  return MStatePtr(new LoadVars(ds, switchState));
478
0
}
479
480
0
MStatePtr makeArrayState(MDFA* dfa, const PatternRows& ps, size_t c) {
481
0
  return
482
0
    makeSplitState<
483
0
      MatchArray,
484
0
      size_t,
485
0
      &maSize,
486
0
      &makeASplitRow,
487
0
      &makeASAnyRow,
488
0
      &makeASSuccState,
489
0
      &makeASSwitch
490
0
    >
491
0
    (dfa, ps, c);
492
0
}
493
494
// split on string matching
495
0
size_t maxStringLen(const PatternRows& ps, size_t c) {
496
0
  size_t mlen = 0;
497
0
  for (const auto &p : ps) {
498
0
    if (const MatchArray* ma = is<MatchArray>(p.patterns[c])) {
499
0
      mlen = std::max<size_t>(ma->size(), mlen);
500
0
    }
501
0
  }
502
0
  return mlen;
503
0
}
504
505
0
size_t packedSValues(size_t cs) {
506
0
  assert(cs % 8 == 0);
507
0
  return cs / 8;
508
0
}
509
510
0
inline unsigned char spatChar(const MatchArray& ma, size_t i) {
511
0
  if (i >= ma.size()) {
512
0
    return 0;
513
0
  } else if (const MatchLiteral* ml = is<MatchLiteral>(ma.pattern(i))) {
514
0
    if (const Char* c = is<Char>(ml->equivConstant())) {
515
0
      return static_cast<unsigned char>(c->value());
516
0
    } else {
517
0
      throw annotated_error(*ml, "Internal error, can't unpack non-char as char");
518
0
    }
519
0
  } else {
520
0
    throw annotated_error(ma, "Internal error, can't unpack non-string as string");
521
0
  }
522
0
}
523
524
template <typename T>
525
0
  T translatep(const MatchArray& ma, size_t i) {
526
0
    T x = 0;
527
0
    for (size_t j = 0; j < sizeof(T); ++j) {
528
0
      x |= static_cast<T>(spatChar(ma, i + (sizeof(T) - 1 - j))) << (8 * j);
529
0
    }
530
0
    return x;
531
0
  }
532
533
0
Patterns sarrayPatterns(const std::string& svarName, size_t cs, const MatchArray& ma) {
534
0
  Patterns r;
535
0
  size_t i  = 0;
536
0
  while (cs >= 8) {
537
0
    PatternPtr qwp(new MatchLiteral(PrimitivePtr(new Long(translatep<unsigned long>(ma, i), ma.la())), ma.la()));
538
0
    qwp->name(svarName + ".l" + str::from(i));
539
0
    r.push_back(qwp);
540
541
0
    cs -= 8;
542
0
    i  += 8;
543
0
  }
544
0
  assert(cs == 0);
545
0
  return r;
546
0
}
547
548
0
void addSATableRow(size_t len, const PatternRow& r, size_t c, PatternRows* out) {
549
0
  copyRowWithoutColumn(out, r, c);
550
0
  if (const MatchArray* ma = is<MatchArray>(r.patterns[c])) {
551
0
    prependPatterns(&out->back(), sarrayPatterns(r.patterns[c]->name(), len, *ma));
552
0
  } else {
553
0
    assert(is<MatchAny>(r.patterns[c]));
554
0
    prependPatterns(&out->back(), arrayAnyMatches(packedSValues(len)));
555
0
  }
556
0
}
557
558
0
MStatePtr makeCharArrayState(MDFA* dfa, const PatternRows& ps, size_t c) {
559
0
  static MonoTypePtr longTy(Prim::make("long"));
560
561
0
  std::string arrayVar = ps[0].patterns[c]->name();
562
0
  auto      mlen     = align<size_t>(maxStringLen(ps, c) + 1, 8);
563
0
  size_t      cs       = mlen;
564
  
565
0
  LoadVars::Defs ds;
566
567
  // open this array (usually a no-op)
568
0
  std::string oarrayVar = arrayVar + ".a";
569
0
  ds.push_back(LoadVars::Def(oarrayVar, openArray(dfa, arrayVar)));
570
571
  // load string values
572
0
  size_t i = 0;
573
0
  while (cs >= 8) {
574
0
    ds.push_back(LoadVars::Def(arrayVar + ".l" + str::from(i), assume(charArrElement(dfa, "packCArrLong", oarrayVar, i), longTy, dfa->rootLA)));
575
0
    cs -= 8;
576
0
    i  += 8;
577
0
  }
578
0
  assert(cs == 0);
579
580
  // generate the successor table
581
0
  PatternRows nps;
582
0
  for (const auto &p : ps) {
583
0
    addSATableRow(mlen, p, c, &nps);
584
0
  }
585
586
  // and that's it!
587
0
  return MStatePtr(new LoadVars(ds, makeDFAState(dfa, nps)));
588
0
}
589
590
0
bool canMakeCharArrayState(const PatternRows& ps, size_t c) {
591
0
  bool seemsLegit = false;
592
0
  for (const auto &p : ps) {
593
0
    if (const MatchArray* ma = is<MatchArray>(p.patterns[c])) {
594
0
      for (size_t i = 0; i < ma->size(); ++i) {
595
0
        if (const MatchLiteral* ml = is<MatchLiteral>(ma->pattern(i))) {
596
0
          if (is<Char>(ml->equivConstant()) != nullptr) {
597
0
            seemsLegit = true;
598
0
          }
599
0
        } else {
600
0
          return false;
601
0
        }
602
0
      }
603
0
    } else if (is<MatchAny>(p.patterns[c]) == nullptr) {
604
0
      return false;
605
0
    }
606
0
  }
607
0
  return seemsLegit;
608
0
}
609
610
0
size_t canMakeCharArrStateAtColumn(MDFA* dfa, const PatternRows& ps) {
611
0
  if (dfa->c->buildColumnwiseMatches()) {
612
0
    return ps[0].patterns.size(); // don't bother packing strings if we're compiling columnwise
613
0
  }
614
615
0
  for (size_t c = 0; c < ps[0].patterns.size(); ++c) {
616
0
    if (canMakeCharArrayState(ps, c)) {
617
0
      return c;
618
0
    }
619
0
  }
620
0
  return ps[0].patterns.size();
621
0
}
622
623
// split on record load/matches
624
0
MStatePtr makeRecordState(MDFA* dfa, const PatternRows& ps, size_t c) {
625
  // get the fields to load
626
0
  LoadVars::Defs defs;
627
628
0
  const MatchRecord* r0 = is<MatchRecord>(ps[0].patterns[c]);
629
0
  if (r0 != nullptr) {
630
0
    for (size_t fi = 0; fi < r0->size(); ++fi) {
631
0
      const MatchRecord::Field& f = r0->pattern(fi);
632
0
      defs.push_back(LoadVars::Def(f.second->name(), field(dfa, r0->name(), f.first)));
633
0
    }
634
0
  } else {
635
0
    throw annotated_error(*ps[0].patterns[c], "Internal error, can't make record state from non-record pattern");
636
0
  }
637
638
  // eliminate this column and add new columns for field patterns
639
0
  PatternRows cdef;
640
641
0
  for (const auto &p : ps) {
642
0
    if (const MatchRecord* mr = is<MatchRecord>(p.patterns[c])) {
643
      // each row's field patterns become columns tested against the fields loaded for the
644
      // first row, so every record here has to have those fields, in that order
645
      // (validation pads and type-checks them to agree: this is a backstop, since rows
646
      //  of different widths would be read out of bounds from here on)
647
0
      bool sameFields = mr->size() == r0->size();
648
0
      for (size_t fi = 0; sameFields && fi < mr->size(); ++fi) {
649
0
        sameFields = mr->pattern(fi).first == r0->pattern(fi).first;
650
0
      }
651
0
      if (!sameFields) {
652
0
        throw annotated_error(*p.patterns[c], "Internal error, record patterns in one column have different fields");
653
0
      }
654
655
0
      copyRowWithoutColumn(&cdef, p, c);
656
0
      prependPatterns(&cdef.back(), recordFieldPatterns(*mr));
657
0
    } else if (is<MatchAny>(p.patterns[c]) != nullptr) {
658
0
      copyRowWithoutColumn(&cdef, p, c);
659
0
      prependPatterns(&cdef.back(), arrayAnyMatches(defs.size()));
660
0
    } else {
661
0
      throw annotated_error(*p.patterns[c], "Internal error, invalid pattern table received");
662
0
    }
663
0
  }
664
665
  // now just load and continue
666
0
  return MStatePtr(new LoadVars(defs, makeDFAState(dfa, cdef)));
667
0
}
668
669
// split on variant switch/matches
670
0
std::string varCtor(const MatchVariant& mv) { return mv.label(); }
671
672
0
void makeVariantSplitRow(const MatchVariant& mv, PatternRows* out, const PatternRow& r, size_t c) {
673
0
  copyRowWithoutColumn(out, r, c);
674
0
  out->back().patterns.insert(out->back().patterns.begin(), mv.value());
675
0
}
676
677
0
void makeVSAnyRow(std::string, PatternRows* out, const PatternRow& r, size_t c) {
678
0
  copyRowWithoutColumn(out, r, c);
679
0
  out->back().patterns.insert(out->back().patterns.begin(), r.patterns[c]);
680
0
}
681
682
0
stateidx_t makeVSSuccState(const std::string&, std::string, MDFA* dfa, const PatternRows& nps) {
683
0
  return makeDFAState(dfa, nps);
684
0
}
685
686
0
MStatePtr makeVSSwitch(const std::string& switchVar, MDFA*, const SwitchVariant::CtorJumps& jmps, stateidx_t defState) {
687
0
  return MStatePtr(new SwitchVariant(switchVar, jmps, defState));
688
0
}
689
690
0
MStatePtr makeVariantState(MDFA* dfa, const PatternRows& ps, size_t c) {
691
0
  return
692
0
    makeSplitState<
693
0
      MatchVariant,
694
0
      std::string,
695
0
      &varCtor,
696
0
      &makeVariantSplitRow,
697
0
      &makeVSAnyRow,
698
0
      &makeVSSuccState,
699
0
      &makeVSSwitch
700
0
    >
701
0
    (dfa, ps, c);
702
0
}
703
704
// split on regex switch/matches
705
// Regex columns are matched by one function per column rather than one per
706
// DFA state. A split on any other column hands each branch a subset of the
707
// rows, so as the table is deconstructed the same column is tested at many
708
// states, each with its own subset of the column's regexes -- and a function
709
// compiled for each subset would repeat the NFA/DFA construction, definition,
710
// type inference and machine code generation once per state. Since a state
711
// needs to know only which of *its* rows a string matches, the function
712
// compiled for every regex the column can test answers at every state: the
713
// result it returns is a set of matched column regexes, and the rows to
714
// follow are those of the state whose regex lies in that set.
715
//
716
// Measured on the test suite's 70x12 table (Matching/largeMatchTableCompileTime)
717
// this replaces 888 regex functions with six.
718
719
// gather every regex a column can test, walking nested patterns in the same
720
// order that deconstruction later assigns them names. Arrays of chars are
721
// counted too, since regexNormalize turns them into regexes wherever a column
722
// mixes them with real ones; those that cannot be so translated are left out
723
// here (the column will fail the same way it does now if it comes to one).
724
struct collectColumnRegexesF : public switchPattern<UnitV> {
725
  ColumnRegexTables* out;
726
0
  explicit collectColumnRegexesF(ColumnRegexTables* out) : out(out) { }
727
728
0
  static void add(ColumnRegexTables* out, const std::string& name, const RegexPtr& r) {
729
0
    ColumnRegexes& crs = (*out)[name];
730
0
    rejectOversizedRegex(r);
731
0
    const std::string k = regexKey(r);
732
0
    if (crs.index.find(k) == crs.index.end()) {
733
0
      crs.index[k] = crs.regexes.size();
734
0
      crs.regexes.push_back(r);
735
0
    }
736
0
  }
737
738
0
  UnitV with(const MatchAny*)     const override { return unitv; }
739
0
  UnitV with(const MatchLiteral*) const override { return unitv; }
740
0
  UnitV with(const MatchRegex* x) const override { add(this->out, x->name(), x->value()); return unitv; }
741
0
  UnitV with(const MatchArray* x) const override {
742
0
    try {
743
0
      PatternPtr rp = MatchRegex::toRegex(*x);
744
0
      add(this->out, x->name(), is<MatchRegex>(rp)->value());
745
0
    } catch (std::exception&) {
746
0
    }
747
0
    for (size_t i = 0; i < x->size(); ++i) {
748
0
      switchOf(x->pattern(i), *this);
749
0
    }
750
0
    return unitv;
751
0
  }
752
0
  UnitV with(const MatchRecord* x) const override {
753
0
    for (size_t i = 0; i < x->size(); ++i) {
754
0
      switchOf(x->pattern(i).second, *this);
755
0
    }
756
0
    return unitv;
757
0
  }
758
0
  UnitV with(const MatchVariant* x) const override {
759
0
    switchOf(x->value(), *this);
760
0
    return unitv;
761
0
  }
762
};
763
764
0
void collectColumnRegexes(ColumnRegexTables* out, const PatternRows& ps) {
765
0
  collectColumnRegexesF f(out);
766
0
  for (const auto& r : ps) {
767
0
    for (const auto& p : r.patterns) {
768
0
      switchOf(p, f);
769
0
    }
770
0
  }
771
0
}
772
773
// the regexes tested at a column, extended (it should not need to be, after
774
// collectColumnRegexes, but correctness only asks that every regex the state
775
// tests be among them) with any not already there
776
0
const ColumnRegexes& columnRegexesFor(MDFA* dfa, const std::string& colVar, const Regexes& rs) {
777
0
  ColumnRegexes& crs = dfa->columnRegexes[colVar];
778
0
  for (const auto& r : rs) {
779
0
    collectColumnRegexesF::add(&dfa->columnRegexes, colVar, r);
780
0
  }
781
0
  return crs;
782
0
}
783
784
0
MStatePtr makeRegexState(MDFA* dfa, const PatternRows& ps, size_t c) {
785
  // remember the match-any rows, and which column regex each other row tests
786
0
  std::set<size_t> matchAnyRows;
787
0
  Regexes          rowRegexes;
788
0
  for (size_t r = 0; r < ps.size(); ++r) {
789
0
    if (const MatchRegex* mr = is<MatchRegex>(ps[r].patterns[c])) {
790
0
      rowRegexes.push_back(mr->value());
791
0
    } else if (is<MatchAny>(ps[r].patterns[c]) != nullptr) {
792
0
      matchAnyRows.insert(r);
793
0
      rowRegexes.push_back(RegexPtr());
794
0
    } else {
795
0
      throw annotated_error(*ps[r].patterns[c], "Internal error, invalid pattern table received");
796
0
    }
797
0
  }
798
799
0
  std::string switchVar = ps[0].patterns[c]->name();
800
801
0
  Regexes testedRegexes;
802
0
  for (const auto& r : rowRegexes) {
803
0
    if (r) { testedRegexes.push_back(r); }
804
0
  }
805
0
  const ColumnRegexes& colRegexes = columnRegexesFor(dfa, switchVar, testedRegexes);
806
807
0
  std::vector<size_t> rowRegexIdx(ps.size(), 0);
808
0
  for (size_t r = 0; r < ps.size(); ++r) {
809
0
    if (rowRegexes[r]) {
810
0
      rowRegexIdx[r] = colRegexes.index.find(regexKey(rowRegexes[r]))->second;
811
0
    }
812
0
  }
813
814
  // make (or reuse) the function that matches every regex in this column
815
0
  CRegexes regexFn = makeRegexFn(dfa->c, colRegexes.regexes, dfa->rootLA);
816
817
  // open a char array on the match value (usually this will be a no-op)
818
  // then call the regex function to get the set of continuation rows to follow and a buffer for captured data
819
0
  std::string oarrayVar   = switchVar + ".a";
820
0
  std::string rcaptureVar = switchVar + ".rgxcapture";
821
0
  std::string rcheckVar   = switchVar + ".rgxcheck";
822
823
0
  LoadVars::Defs ds;
824
0
  ds.push_back(LoadVars::Def(oarrayVar, openArray(dfa, switchVar)));
825
0
  ds.push_back(LoadVars::Def(rcaptureVar, regexFn.captureBuffer));
826
0
  ds.push_back(LoadVars::Def(rcheckVar,
827
0
    fncall(
828
0
      var(regexFn.fname, dfa->rootLA), list(
829
0
        var(rcaptureVar, dfa->rootLA),
830
0
        var(oarrayVar, dfa->rootLA),
831
0
        constant(static_cast<long>(0), dfa->rootLA),
832
0
        fncall(var("size", dfa->rootLA), list(var(oarrayVar, dfa->rootLA)), dfa->rootLA),
833
0
        constant(static_cast<int>(0), dfa->rootLA)),
834
0
      dfa->rootLA
835
0
    )
836
0
  ));
837
838
  // each result of the column function selects the rows here whose regex it
839
  // matched; results that select the same rows lead to the same state, and a
840
  // result that selects none of them is the same as no match at all
841
0
  using MatchedRows = std::vector<size_t>;
842
0
  std::map<MatchedRows, std::vector<size_t>> resultsByRows;
843
0
  for (const auto& rstate : regexFn.rstates) {
844
0
    MatchedRows rows;
845
0
    for (size_t r = 0; r < ps.size(); ++r) {
846
0
      if (rowRegexes[r] && rstate.second.count(rowRegexIdx[r]) > 0) {
847
0
        rows.push_back(r);
848
0
      }
849
0
    }
850
0
    if (!rows.empty()) {
851
0
      resultsByRows[rows].push_back(rstate.first);
852
0
    }
853
0
  }
854
855
  // based on the match result, branch to a reduced table
856
0
  SwitchVal::Jumps sjmps;
857
0
  for (const auto& rr : resultsByRows) {
858
0
    PatternRows ktbl;
859
0
    auto anyr = matchAnyRows.begin();
860
861
    // the captured data to load: that of every regex matched here, in row order
862
0
    CVarDefs cvds;
863
0
    std::set<size_t> unpacked;
864
865
0
    for (const auto& r : rr.first) {
866
      // all match-any values prior to this row must take priority
867
0
      for (; anyr != matchAnyRows.end() && *anyr < r; ++anyr) {
868
0
        copyRowWithoutColumn(&ktbl, ps[*anyr], c);
869
0
      }
870
871
      // then we've matched this row at this column
872
0
      copyRowWithoutColumn(&ktbl, ps[r], c);
873
874
0
      if (unpacked.insert(rowRegexIdx[r]).second) {
875
0
        CVarDefs rcvds = unpackCaptureVars(switchVar, rcaptureVar, regexFn, rowRegexIdx[r], dfa->rootLA);
876
0
        cvds.insert(cvds.end(), rcvds.begin(), rcvds.end());
877
0
      }
878
0
    }
879
880
    // include all trailing match-any rows at the end of this reduced table
881
0
    for (; anyr != matchAnyRows.end(); ++anyr) {
882
0
      copyRowWithoutColumn(&ktbl, ps[*anyr], c);
883
0
    }
884
885
    // in this case, follow this continuation and load variables for it
886
0
    stateidx_t nextState = makeDFAState(dfa, ktbl);
887
0
    if (!cvds.empty()) {
888
0
      nextState = addState(dfa, MStatePtr(new LoadVars(cvds, nextState)));
889
0
    }
890
    // (the state was made with one reference; each further result that
891
    // jumps to it is another)
892
0
    for (size_t i = 0; i < rr.second.size(); ++i) {
893
0
      sjmps.push_back(SwitchVal::Jump(PrimitivePtr(new Int(static_cast<int>(rr.second[i]), dfa->rootLA)), nextState));
894
0
      if (i > 0) {
895
0
        addRef(dfa, nextState);
896
0
      }
897
0
    }
898
0
  }
899
900
  // otherwise if we didn't match anything, branch to a default table containing just the match-any states (if applicable)
901
0
  PatternRows def;
902
0
  for (auto r : matchAnyRows) {
903
0
    copyRowWithoutColumn(&def, ps[r], c);
904
0
  }
905
0
  stateidx_t defState = !def.empty() ? makeDFAState(dfa, def) : nullState;
906
907
  // and that's our state ... a load for the regex call and a branch on its result
908
0
  return MStatePtr(new LoadVars(ds, addState(dfa, makeLSSwitch(rcheckVar, dfa, sjmps, defState))));
909
0
}
910
911
// there are five ways that we can deconstruct a pattern table:
912
//   literal -- a switch on literal values branching to other states
913
//   array   -- a switch on array sizes, branching to other states (with corresponding element loads)
914
//              (in the case of char arrays, we do something a little different for fast compile times)
915
//   regex   -- a switch on regular expressions, branching to states where matched
916
//   record  -- load the fields of a record and branch to other states
917
//   variant -- switch on the constructors of a variant and branch to other states
918
struct makeSuccStateF : public switchPattern<MStatePtr> {
919
  MDFA* dfa;
920
  const PatternRows& ps;
921
  size_t c;
922
0
  makeSuccStateF(MDFA* dfa, const PatternRows& ps, size_t c) : dfa(dfa), ps(ps), c(c) { }
923
924
0
  [[noreturn]] MStatePtr with(const MatchAny* ma) const override {
925
0
    throw annotated_error(*ma, "Internal error, can't deconstruct wildcard columns in match expression");
926
0
  }
927
928
0
  MStatePtr with(const MatchLiteral*) const override { return makeLiteralState(dfa, ps, c); }
929
0
  MStatePtr with(const MatchRegex*)   const override { return makeRegexState(dfa, regexNormalize(ps, c), c); }
930
0
  MStatePtr with(const MatchRecord*)  const override { return makeRecordState(dfa, ps, c); }
931
0
  MStatePtr with(const MatchVariant*) const override { return makeVariantState(dfa, ps, c); }
932
933
  // if we have a 'match array' column but it's got a regex somewhere, then we actually
934
  // need to apply regex match logic (otherwise we can match as an array)
935
0
  MStatePtr with(const MatchArray*) const override {
936
0
    for (const auto &p : ps) {
937
0
      if (is<MatchRegex>(p.patterns[c]) != nullptr) {
938
0
        return makeRegexState(dfa, regexNormalize(ps, c), c);
939
0
      }
940
0
    }
941
0
    return makeArrayState(dfa, ps, c);
942
0
  }
943
944
  // normalize patterns in an entire column into regular expressions
945
  // (this allows mixing of literal matches and regex matches in a single column)
946
0
  static PatternRows regexNormalize(const PatternRows& ps, size_t c) {
947
0
    PatternRows nps = ps;
948
0
    for (auto &np : nps) {
949
0
      if (const MatchArray* ma = is<MatchArray>(np.patterns[c])) {
950
0
        np.patterns[c] = MatchRegex::toRegex(*ma);
951
0
      }
952
0
    }
953
0
    return nps;
954
0
  }
955
};
956
957
0
MStatePtr makeSuccState(MDFA* dfa, const PatternRows& ps, size_t c) {
958
0
  return switchOf(ps[0].patterns[c], makeSuccStateF(dfa, ps, c));
959
0
}
960
961
// choose which column to deconstruct
962
// the current scoring function just gives a rough measurement of how many matches are done in a given column
963
struct scorePatternF : public switchPattern<size_t> {
964
  // don't count the same primitive twice
965
  mutable PrimitiveSet recprims;
966
967
0
  size_t with(const MatchAny*) const override {
968
0
    return 0;
969
0
  }
970
971
0
  size_t with(const MatchLiteral* ml) const override {
972
0
    return this->recprims.insert(ml->equivConstant()).second ? 1 : 0;
973
0
  }
974
975
0
  size_t with(const MatchArray* ma) const override {
976
0
    size_t s = 1;
977
0
    for (size_t i = 0; i < ma->size(); ++i) {
978
0
      s += switchOf(ma->pattern(i), *this);
979
0
    }
980
0
    return s;
981
0
  }
982
983
0
  size_t with(const MatchRegex*) const override {
984
0
    return 1;
985
0
  }
986
987
0
  size_t with(const MatchRecord* mr) const override {
988
0
    size_t s = 0;
989
0
    for (size_t i = 0; i < mr->size(); ++i) {
990
0
      s += switchOf(mr->pattern(i).second, *this);
991
0
    }
992
0
    return s;
993
0
  }
994
995
0
  size_t with(const MatchVariant* mv) const override {
996
0
    return 1 + switchOf(mv->value(), *this);
997
0
  }
998
};
999
1000
0
size_t columnScore(const PatternRows& ps, size_t c) {
1001
0
  size_t s = 0;
1002
0
  scorePatternF matchCounter;
1003
0
  for (const auto& p : ps) {
1004
0
    s += switchOf(p.patterns[c], matchCounter);
1005
0
  }
1006
0
  return s;
1007
0
}
1008
1009
0
size_t choosePivotColumn(const PatternRows& ps) {
1010
0
  size_t chosenColumn = ps[0].patterns.size();
1011
0
  size_t currentScore = std::numeric_limits<size_t>::max();
1012
1013
0
  size_t bestArrayColumn = ps[0].patterns.size();
1014
0
  size_t bestArrayScore  = std::numeric_limits<size_t>::max();
1015
1016
0
  for (size_t c = 0; c < ps[0].patterns.size(); ++c) {
1017
0
    if (is<MatchAny>(ps[0].patterns[c]) == nullptr) {
1018
0
      size_t csc = 1 + columnScore(ps, c);
1019
0
      if (csc < currentScore) {
1020
0
        chosenColumn = c;
1021
0
        currentScore = csc;
1022
0
      }
1023
1024
0
      if ((is<MatchArray>(ps[0].patterns[c]) != nullptr) && csc < bestArrayScore) {
1025
0
        bestArrayColumn = c;
1026
0
        bestArrayScore  = csc;
1027
0
      }
1028
0
    }
1029
0
  }
1030
1031
  // prefer array selection (for GLM)
1032
0
  if (bestArrayColumn < ps[0].patterns.size()) {
1033
0
    return bestArrayColumn;
1034
0
  } else {
1035
0
    return chosenColumn;
1036
0
  }
1037
0
}
1038
1039
// is a pattern table just a set of primitive selection rules?
1040
0
bool isPrimSelection(bool alwaysLowerPrimMatchTables, const PatternRows& ps) {
1041
  // heuristically avoid prim selection derivation for "small tables"
1042
0
  if (!alwaysLowerPrimMatchTables && ps.size() < 500) {
1043
0
    return false;
1044
0
  }
1045
1046
  // there can't be any guards in a primitive selection
1047
0
  for (const auto &p : ps) {
1048
0
    if (p.guard) {
1049
0
      return false;
1050
0
    }
1051
0
  }
1052
1053
  // any match on a composite value (record, array, variant) doesn't count as primitive
1054
  // we also can't (currently) have convertible values in primitive tests
1055
0
  bool seemsLegit = false;
1056
1057
0
  for (size_t c = 0; c < ps[0].patterns.size(); ++c) {
1058
0
    for (const auto &p : ps) {
1059
0
      if (const MatchLiteral* ml = is<MatchLiteral>(p.patterns[c])) {
1060
0
        if (ml->expression()) {
1061
0
          return false;
1062
0
        } else {
1063
          // one constant is as good as all constants
1064
0
          seemsLegit = true;
1065
0
          break;
1066
0
        }
1067
0
      } else if (is<MatchAny>(p.patterns[c]) == nullptr) {
1068
0
        return false;
1069
0
      }
1070
0
    }
1071
0
  }
1072
1073
0
  return seemsLegit;
1074
0
}
1075
1076
// assuming that a pattern table represents a primitive selection, determine its argument sequence
1077
0
PrimFArgs makePrimFArgs(const PatternRows& ps) {
1078
0
  PrimFArgs args;
1079
0
  for (size_t c = 0; c < ps[0].patterns.size(); ++c) {
1080
0
    for (const auto & p : ps) {
1081
0
      if (const MatchLiteral* ml = is<MatchLiteral>(p.patterns[c])) {
1082
0
        args.push_back(PrimFArg(ml->name(), ml->equivConstant()->primType()));
1083
0
        break;
1084
0
      }
1085
0
    }
1086
0
  }
1087
0
  return args;
1088
0
}
1089
1090
// does it make sense and is it worthwhile to decompose this table column-wise?
1091
0
bool shouldDecomposeColumnwise(MDFA* dfa, const PatternRows& ps) {
1092
  // it only makes sense to decompose columnwise if the table has at least one row, at least two columns
1093
0
  if (ps.empty() || ps[0].patterns.size() <= 1) {
1094
0
    return false;
1095
0
  }
1096
1097
  // there's some overhead with this method, so only do it if the user asks for it
1098
0
  if (!dfa->c->buildColumnwiseMatches()) {
1099
0
    return false;
1100
0
  }
1101
1102
  // don't bother doing this for small tables
1103
0
  if (ps.size() * ps[0].patterns.size() < 100) {
1104
0
    return false;
1105
0
  }
1106
1107
  // the logic in makeColRowsetCalcExpr assumes column counts fit in a byte
1108
0
  if (ps[0].patterns.size() > 256) {
1109
0
    return false;
1110
0
  }
1111
1112
  // OK let's do it!
1113
0
  return true;
1114
0
}
1115
1116
// calculate a set of implied rows from a single column of a match table
1117
0
ExprPtr makeColRowsetCalcExpr(MDFA* dfa, const PatternRows& ps, size_t c, const std::string& rcVarName, std::vector<uint8_t>* skipCounts) {
1118
0
  bool isFinal = c == ps[0].patterns.size() - 1;
1119
1120
0
  PatternRows cps;
1121
0
  for (size_t r = 0; r < ps.size(); ++r) {
1122
0
    auto rcVar = fncall(var("saelem", dfa->rootLA), list(var(rcVarName, dfa->rootLA), constant(static_cast<size_t>(r), dfa->rootLA)), dfa->rootLA);
1123
1124
0
    if (!isFinal) {
1125
0
      if (refutable(ps[r].patterns[c])) {
1126
0
        auto markRowExpr = assign(rcVar, fncall(var("badd", dfa->rootLA), list(rcVar, constant(static_cast<uint8_t>(1), dfa->rootLA)), dfa->rootLA), dfa->rootLA);
1127
0
        cps.push_back(PatternRow(list(ps[r].patterns[c]), let("_", markRowExpr, constant(false, dfa->rootLA), dfa->rootLA), mktunit(dfa->rootLA)));
1128
0
      } else {
1129
0
        ++(*skipCounts)[r];
1130
0
      }
1131
0
    } else {
1132
0
      if (r < ps.size()-1) {
1133
0
        auto checkCount = fncall(var("beq", dfa->rootLA), list(rcVar, constant(static_cast<uint8_t>(ps[0].patterns.size()-(1+(*skipCounts)[r])), dfa->rootLA)), dfa->rootLA);
1134
0
        cps.push_back(PatternRow(list(ps[r].patterns[c]), ps[r].guard ? fncall(var("and",dfa->rootLA), list(checkCount, ps[r].guard), dfa->rootLA) : checkCount, ps[r].result));
1135
0
      } else {
1136
0
        if (ps[r].guard != ExprPtr()) {
1137
0
          throw annotated_error(*ps[r].guard, "Inexhaustive patterns in match expression after guard");
1138
0
        }
1139
0
        cps.push_back(PatternRow(list(ps[r].patterns[c]), ps[r].result));
1140
0
      }
1141
1142
      // always ref the row result (may leave unreachable rows undetected)
1143
0
      addState(dfa, MStatePtr(new FinishExpr(ps[r].result)));
1144
0
    }
1145
0
  }
1146
0
  if (!isFinal) {
1147
0
    cps.push_back(PatternRow(list(PatternPtr(new MatchAny("_", dfa->rootLA))), mktunit(dfa->rootLA)));
1148
0
  }
1149
1150
0
  return liftDFAExpr(dfa->c, cps, dfa->rootLA);
1151
0
}
1152
1153
// convert a pattern table to a DFA state by aggregating test results for each column
1154
0
stateidx_t makeColAggrDFAState(MDFA* dfa, const PatternRows& ps) {
1155
  // make an expr for each column to compute its implied rowset
1156
0
  LoadVars::Defs       sdefs;
1157
0
  std::string          rcname = ".rc." + freshName();
1158
0
  std::vector<uint8_t> skipCounts(ps.size(), 0);
1159
  
1160
0
  sdefs.push_back(LoadVars::Def(rcname, assume(fncall(var("newPrimZ", dfa->rootLA), list(mktunit(dfa->rootLA)), dfa->rootLA), arrayty(primty("byte"), ps.size()), dfa->rootLA)));
1161
0
  for (size_t c = 0; c < ps[0].patterns.size()-1; ++c) {
1162
0
    sdefs.push_back(LoadVars::Def("_", makeColRowsetCalcExpr(dfa, ps, c, rcname, &skipCounts)));
1163
0
  }
1164
1165
0
  return
1166
0
    addState(dfa, MStatePtr(
1167
0
      new LoadVars(
1168
0
        sdefs,
1169
0
        addState(dfa, MStatePtr(new FinishExpr(makeColRowsetCalcExpr(dfa, ps, ps[0].patterns.size()-1, rcname, &skipCounts))))
1170
0
      )
1171
0
    ));
1172
0
}
1173
1174
// convert a pattern table to a DFA state by picking a column to discriminate on, branching to subtables on that column value
1175
0
stateidx_t makeColPivotDFAState(MDFA* dfa, const PatternRows& ps) {
1176
0
  stateidx_t result = nullState;
1177
1178
  // choose a column to deconstruct
1179
  // if no column can be chosen, there is only one path -- the immediate return expression
1180
0
  size_t c = choosePivotColumn(ps);
1181
0
  if (c < ps[0].patterns.size()) {
1182
0
    if (dfa->inPrimSel || !isPrimSelection(dfa->c->alwaysLowerPrimMatchTables(), ps)) {
1183
0
      result = addState(dfa, makeSuccState(dfa, ps, c));
1184
0
    } else {
1185
0
      dfa->inPrimSel = true;
1186
0
      MStatePtr succState = makeSuccState(dfa, ps, c);
1187
0
      dfa->inPrimSel = false;
1188
1189
0
      succState->isPrimMatchRoot = true;
1190
0
      succState->primFArgs       = makePrimFArgs(ps);
1191
0
      result = addState(dfa, succState);
1192
0
    }
1193
0
  } else if (ps[0].guard) {
1194
0
    SwitchVal::Jumps jmps;
1195
0
    jmps.push_back(SwitchVal::Jump(PrimitivePtr(new Bool(true, dfa->rootLA)), addState(dfa, MStatePtr(new FinishExpr(ps[0].result)))));
1196
1197
0
    PatternRows tail;
1198
0
    tableTail(&tail, ps);
1199
0
    if (tail.empty()) {
1200
0
      throw annotated_error(*ps[0].guard, "Inexhaustive patterns in match expression after guard");
1201
0
    }
1202
1203
0
    size_t guardS = addState(dfa, MStatePtr(new SwitchVal(".guardcheck", jmps, makeDFAState(dfa, tail))));
1204
1205
0
    LoadVars::Defs ds;
1206
0
    ds.push_back(LoadVars::Def(".guardcheck", ps[0].guard));
1207
0
    result = addState(dfa, MStatePtr(new LoadVars(ds, guardS)));
1208
0
  } else {
1209
0
    result = addState(dfa, MStatePtr(new FinishExpr(ps[0].result)));
1210
0
  }
1211
1212
  // next time we come through, just use the state implied by the table config
1213
0
  dfa->tableCfgStates[ps] = result;
1214
1215
  // and that's it
1216
0
  return result;
1217
0
}
1218
1219
// Compiling a pattern-match table is worst-case exponential in general, and
1220
// this construction pays for it in two currencies at once. Splitting a column
1221
// hands every match-any row to every branch it did not name, so a table can
1222
// come out of a split barely smaller than it went in -- and each such state
1223
// holds a copy of its table, keyed by the whole table again in
1224
// tableCfgStates. Where the rows leave nothing to share, the recursion is a
1225
// straight chain, one state and one full table copy per row: 7,483 rows of
1226
// wildcard cost 4,000 states and 75M table cells before the process ran out
1227
// of memory at 2560MB (OSS-Fuzz 557561539, whose 90KB of input is ~7,500
1228
// repetitions of one row shape).
1229
//
1230
// So both currencies are budgeted. The margins are measured, not guessed.
1231
// Over 11,495 match tables compiled by the test suite the costliest holds
1232
// 236,011 cells and none recurses deeper than 22, while the report above is
1233
// past both by orders of magnitude -- a chain thousands of states deep and
1234
// tens of millions of cells.
1235
//
1236
// The cell budget is set by what a cell costs rather than by that ratio
1237
// alone. Measured on a match of N rows over three columns with wildcards
1238
// scattered through them -- the shape that keeps tables from shrinking as
1239
// they split -- the resident cost past a bare compiler's ~780MB runs 72MB at
1240
// 46,609 cells, 316MB at 333,190, 657MB at 1,081,804 and 1,415MB at
1241
// 2,515,309, converging on ~600 bytes a cell. A million cells is therefore
1242
// about 600MB on that shape, which leaves the whole read inside half of the
1243
// 2560MB the report was filed against.
1244
//
1245
// What is counted is every table this walk builds, not only the ones a new
1246
// state keeps: the count is taken above the memoisation check, so a table
1247
// that turns out to have been seen before is charged for too. That is
1248
// deliberate. By the time the check can say so, dropUnusedColumns has already
1249
// copied the whole table and the probe has hashed and compared it, so a
1250
// repeat costs the same transient memory and very nearly the same time as a
1251
// first sight -- and it is peak and time, not what survives, that took the
1252
// process out. It does make the budget conservative wherever a table shares
1253
// sub-tables, and measurably so: over the 13,391 matches the test suite
1254
// compiles, 9.7% of counted cells are repeats, and in the largest single
1255
// table (Matching/largeMatchTableCompileTime) it is 51%. Charged at that
1256
// worst rate a legitimate table still reaches only 236,011 of the million.
1257
//
1258
// Depth is held much looser, and deliberately, because the tables that cost
1259
// the most cells are not the ones that recurse deepest. A production match
1260
// big enough to be worth compiling columnwise (buildColumnwiseMatches -- the
1261
// only way a table of a few hundred rows compiles at all, the row-pivot path
1262
// below does not finish on one) recurses about 0.78 states per row while
1263
// holding almost no table at once: a 400-row, 13-column limit table measures
1264
// 312 deep and 5,213 cells, and a 200-row one 171 deep and 2,613. Rows are
1265
// in turn capped near 600 by the parser's nesting limit, so ~470 is about as
1266
// deep as a table of many flat rows can legitimately go, and a bound that
1267
// merely looked generous against the row-pivot suite maximum of 22 would sit
1268
// right on top of real code. For such tables depth is a backstop against
1269
// runaway recursion eating the C stack, not a second opinion on size: to
1270
// reach a chain deep enough to trip it the cells above are long since spent,
1271
// since a chain of D states starts from a table of D rows and sums ~D^2/2
1272
// cells.
1273
//
1274
// None of that holds for a row that tests many things, and such a row can
1275
// come from source text as well as from the C++ API (compileMatch takes
1276
// PatternRows as given). One level of depth is one test on the way to a row's
1277
// result: a literal compared, an array's length checked, a record, tuple or
1278
// variant taken apart. So a nested pattern costs one state per level of
1279
// nesting and only one cell for each, and rows of nested patterns reach depth
1280
// cheaply: k columns each nested P deep make a chain about k*P states deep
1281
// from about k^2*P/2 cells, which the cell budget allows up to ~22,000 states
1282
// deep at the pattern nesting bound (maxPatternNestingDepth in pattern.C).
1283
// For these the depth bound is the only one in the way, and it has to be set
1284
// by what the stack holds.
1285
//
1286
// Measured on a release x86-64 build, one state of that chain (makeDFAState
1287
// through makeColPivotDFAState and makeRecordState) takes ~760 bytes of
1288
// stack: a 512KB stack overflowed at ~670 states and a 1MB one at ~1,360, so
1289
// 8MB runs out near 11,000 and 4MB -- the headroom ClusterFuzz leaves -- near
1290
// 5,500. The bound this replaced, 10,000, was past the first and twice the
1291
// second. At that measured rate 1,000 states are ~760KB, which leaves room in
1292
// a few MB for the pattern walks each state makes on top of it (bounded
1293
// separately in pattern.C) and for frames several times larger in a sanitized
1294
// build. It does not fit a 512KB stack, and is not meant to.
1295
//
1296
// The price is that matches which used to compile are now turned away, ones
1297
// written as source text among them. Matching a tuple of N pairs against
1298
// ((1, _), (1, _), ...) with a fall-through row takes one state to open the
1299
// tuple, two for each pair (open it, compare the literal) and one for the
1300
// row's result, 2N+2 in all: 499 pairs are 1,000 states and compile, 500 are
1301
// 1,002 and do not (Matching/matchDFADepthBoundaryFromOneRow holds these
1302
// numbers to the code). Under the old bound 700 pairs, 1,402 states, compiled
1303
// and ran -- on an arm64 release build with an 8MB stack, which is all that
1304
// observation covers. A tuple of 500 [1]s is turned away the same way. That
1305
// is the shape of generated code more than of anything written by hand, and
1306
// the answer for it is to split the match (the error says so): a rejection
1307
// that names the limit, rather than a stack that may or may not hold.
1308
static const size_t maxMatchTableCells = 1000000;
1309
static const size_t maxMatchDFADepth   = 1000;
1310
1311
// count a state's recursion into the match being compiled, and back out again
1312
// however the state is left -- the budgets below are reported by throwing.
1313
struct MatchDepth {
1314
  MDFA* dfa;
1315
0
  explicit MatchDepth(MDFA* dfa) : dfa(dfa) { ++this->dfa->stateDepth; }
1316
0
  ~MatchDepth() { --this->dfa->stateDepth; }
1317
  MatchDepth(const MatchDepth&) = delete;
1318
  MatchDepth& operator=(const MatchDepth&) = delete;
1319
};
1320
1321
// make a state out of the input pattern table (recursively constructing sub-states as necessary)
1322
0
stateidx_t makeDFAState(MDFA* dfa, const PatternRows& xps) {
1323
0
  MatchDepth depth(dfa);
1324
0
  if (dfa->stateDepth > maxMatchDFADepth) {
1325
0
    throw annotated_error(dfa->rootLA, "match expression is too complex to compile (nests more than " + str::from(maxMatchDFADepth) + " states deep; match fewer values at once, or split it into several smaller matches)");
1326
0
  }
1327
1328
  // every row is indexed by the columns of the first from here on (starting with
1329
  // dropUnusedColumns), so a table that is not rectangular must not get any further
1330
0
  for (const auto& r : xps) {
1331
0
    if (r.patterns.size() != xps[0].patterns.size()) {
1332
0
      throw annotated_error(dfa->rootLA, "Internal error, pattern table rows have different numbers of columns");
1333
0
    }
1334
0
  }
1335
1336
0
  PatternRows ps;
1337
0
  dropUnusedColumns(&ps, xps);
1338
1339
0
  if (!ps.empty()) {
1340
    // charged against what is left of the budget, so the sum cannot wrap
1341
0
    const size_t cells = ps.size() * ps[0].patterns.size();
1342
0
    if (cells > maxMatchTableCells - dfa->tableCells) {
1343
0
      throw annotated_error(dfa->rootLA, "match expression is too complex to compile (needs more than " + str::from(maxMatchTableCells) + " pattern table cells)");
1344
0
    }
1345
0
    dfa->tableCells += cells;
1346
0
  }
1347
1348
  // if we can deconstruct strings here, do it before anything else
1349
  // (it has a potential runtime performance impact and should only be done to reduce compilation time for large schemas)
1350
0
  size_t strc = canMakeCharArrStateAtColumn(dfa, ps);
1351
0
  if (strc < ps[0].patterns.size()) {
1352
0
    return addState(dfa, makeCharArrayState(dfa, ps, strc));
1353
0
  }
1354
1355
  // did we already produce this state?  if so, just add to its ref-count and return it
1356
0
  auto tcfg = dfa->tableCfgStates.find(ps);
1357
0
  if (tcfg != dfa->tableCfgStates.end()) {
1358
0
    addRef(dfa, tcfg->second);
1359
0
    return tcfg->second;
1360
0
  }
1361
1362
  // for very large tables, we can avoid giant DFAs and long compile times by column-wise decomposition
1363
  // otherwise, create a branch point with sub-tables based on a chosen column
1364
0
  if (shouldDecomposeColumnwise(dfa, ps)) {
1365
0
    return makeColAggrDFAState(dfa, ps);
1366
0
  } else {
1367
0
    return makeColPivotDFAState(dfa, ps);
1368
0
  }
1369
0
}
1370
1371
// deconstruct the pattern match table to produce the equivalent DFA
1372
0
stateidx_t makeDFA(MDFA* dfa, const PatternRows& ps, const LexicalAnnotation& la) {
1373
0
  dfa->rootLA = la;
1374
1375
  // every regex column is matched by one function, over all of its regexes
1376
0
  collectColumnRegexes(&dfa->columnRegexes, ps);
1377
1378
  // start by adding 0-ref states and placeholder parameters for each final expression
1379
0
  std::vector<stateidx_t> finalStates;
1380
0
  for (const auto& pr : ps) {
1381
0
    stateidx_t fst = addState(dfa, MStatePtr(new FinishExpr(pr.result)), false);
1382
0
    finalStates.push_back(fst);
1383
0
    dfa->exprIdxs[pr.result.get()] = fst;
1384
0
  }
1385
1386
  // recursively add states for each step of deconstruction of the match table
1387
0
  stateidx_t rootS = makeDFAState(dfa, ps);
1388
1389
  // make sure that every provided final state is reachable
1390
0
  if (dfa->c->requireMatchReachability()) {
1391
0
    std::vector<size_t> unreachableRows;
1392
0
    for (size_t r = 0; r < ps.size(); ++r) {
1393
0
      size_t fs = finalStates[r];
1394
1395
0
      if (dfa->states[fs]->refs == 0) {
1396
0
        unreachableRows.push_back(r);
1397
0
      }
1398
0
    }
1399
1400
0
    if (!unreachableRows.empty()) {
1401
0
      std::ostringstream fss;
1402
0
      fss << "Unreachable row" << (unreachableRows.size() > 1 ? "s" : "") << " in match expression:\n";
1403
0
      for (size_t ur : unreachableRows) {
1404
0
        fss << "  " << show(ps[ur]) << std::endl;
1405
0
      }
1406
0
      if (dfa->c->ignoreUnreachableMatches()) {
1407
0
        dfa->c->gatherUnreachableMatches({.la = la, .lines = fss.str()});
1408
0
      } else {
1409
0
        throw annotated_error(la, fss.str());
1410
0
      }
1411
0
    }
1412
0
  }
1413
1414
0
  if (dfa->c->unreachableMatchRowsPtr) {
1415
0
    dfa->c->unreachableMatchRowsPtr->reserve(ps.size());
1416
0
    for (size_t r = 0; r < ps.size(); ++r) {
1417
0
      size_t fs = finalStates[r];
1418
1419
0
      if (dfa->states[fs]->refs == 0) {
1420
0
        dfa->c->unreachableMatchRowsPtr->emplace_back(r, ps[r]);
1421
0
      }
1422
0
    }
1423
0
  }
1424
1425
  // OK, this is a good DFA
1426
0
  return rootS;
1427
0
}
1428
1429
// translate a pattern match table to an equivalent low level matching expression
1430
ExprPtr liftDFAExpr(MDFA* dfa, stateidx_t state);
1431
1432
struct liftDFAExprF : public switchMState<ExprPtr> {
1433
  MDFA* dfa;
1434
0
  liftDFAExprF(MDFA* dfa) : dfa(dfa) { }
1435
1436
0
  ExprPtr with(const LoadVars* x) const override {
1437
0
    const LoadVars::Defs& ds = x->defs();
1438
0
    ExprPtr b = liftDFAExpr(this->dfa, x->nextState());
1439
1440
0
    for (auto d = ds.rbegin(); d != ds.rend(); ++d) {
1441
0
      b = let(d->first, d->second, b, dfa->rootLA);
1442
0
    }
1443
1444
0
    return b;
1445
0
  }
1446
1447
0
  ExprPtr with(const SwitchVal* x) const override {
1448
0
    ExprPtr def = x->defaultState() == nullState ? ExprPtr() : liftDFAExpr(this->dfa, x->defaultState());
1449
1450
0
    const SwitchVal::Jumps& jmps = x->jumps();
1451
0
    Switch::Bindings bs;
1452
0
    for (const auto& jmp : jmps) {
1453
0
      bs.push_back(Switch::Binding(jmp.first, liftDFAExpr(this->dfa, jmp.second)));
1454
0
    }
1455
1456
0
    return ExprPtr(new Switch(varName(this->dfa, x->switchVar()), bs, def, dfa->rootLA));
1457
0
  }
1458
1459
0
  ExprPtr with(const SwitchVariant* x) const override {
1460
0
    ExprPtr def = x->defaultState() == nullState ? ExprPtr() : liftDFAExpr(this->dfa, x->defaultState());
1461
1462
0
    const SwitchVariant::CtorJumps& jmps = x->jumps();
1463
0
    Case::Bindings bs;
1464
0
    for (const auto& jmp : jmps) {
1465
0
      bs.push_back(Case::Binding(jmp.first, x->switchVar() + ".1", liftDFAExpr(this->dfa, jmp.second)));
1466
0
    }
1467
1468
0
    return ExprPtr(new Case(varName(this->dfa, x->switchVar()), bs, def, dfa->rootLA));
1469
0
  }
1470
1471
0
  ExprPtr with(const FinishExpr* x) const override {
1472
0
    return x->expr();
1473
0
  }
1474
};
1475
1476
using ExprCheck = std::pair<ExprPtr, PrimitivePtr>;
1477
using ExprChecks = std::vector<ExprCheck>;
1478
1479
0
ExprPtr checkExpr(const ExprChecks& cs, const LexicalAnnotation& la) {
1480
0
  if (cs.empty()) {
1481
0
    throw annotated_error(la, "Internal error, can't produce empty check expression");
1482
0
  } else {
1483
0
    ExprPtr v = fncall(var("===", la), list(cs[0].first, std::dynamic_pointer_cast<Expr>(cs[0].second)), la);
1484
1485
0
    for (size_t i = 1; i < cs.size(); ++i) {
1486
0
      v = fncall(var("and", la), list(v, fncall(var("===", la), list(cs[i].first, std::dynamic_pointer_cast<Expr>(cs[i].second)), la)), la);
1487
0
    }
1488
1489
0
    return v;
1490
0
  }
1491
0
}
1492
1493
struct IfCheck {
1494
0
  IfCheck() : trueb(nullState), falseb(nullState) { }
1495
1496
  ExprChecks check;
1497
  stateidx_t trueb;
1498
  stateidx_t falseb;
1499
};
1500
1501
0
bool compressToIfCheck(MDFA* dfa, const SwitchVal& sv, IfCheck* out) {
1502
0
  if (sv.jumps().size() == 1) {
1503
0
    if (out->falseb == nullState || out->falseb == sv.defaultState()) {
1504
0
      out->check.push_back(ExprCheck(varName(dfa, sv.switchVar()), sv.jumps()[0].first));
1505
0
      out->trueb  = sv.jumps()[0].second;
1506
0
      out->falseb = sv.defaultState();
1507
1508
0
      if (const SwitchVal* nsv = is<SwitchVal>(dfa->states[out->trueb])) {
1509
0
        compressToIfCheck(dfa, *nsv, out);
1510
0
        return true;
1511
0
      } else {
1512
0
        return true;
1513
0
      }
1514
0
    } else {
1515
0
      return false;
1516
0
    }
1517
0
  } else {
1518
0
    return false;
1519
0
  }
1520
0
}
1521
1522
0
ExprPtr liftDFAExprWithSwitchCompression(MDFA* dfa, stateidx_t state) {
1523
0
  const MStatePtr& s = dfa->states[state];
1524
1525
0
  if (const SwitchVal* sv = is<SwitchVal>(s)) {
1526
0
    IfCheck ifc;
1527
0
    if (compressToIfCheck(dfa, *sv, &ifc)) {
1528
0
      return fncall(var("if", dfa->rootLA), list(checkExpr(ifc.check, dfa->rootLA), liftDFAExpr(dfa, ifc.trueb), liftDFAExpr(dfa, ifc.falseb)), dfa->rootLA);
1529
0
    }
1530
0
  }
1531
1532
0
  return switchOf(s, liftDFAExprF(dfa));
1533
0
}
1534
1535
// A state referenced once is written into the function that references it,
1536
// up to a bound on how many states one function may accumulate, past which
1537
// further states are folded into functions of their own. The bound keeps any
1538
// one function small enough for LLVM to compile in reasonable time (its
1539
// codegen has passes superlinear in function size). It is a bound per
1540
// function, not on how many states a match may inline in total: folding every
1541
// state past the first N into a function of its own -- which is what a total
1542
// bound amounts to -- leaves a large match as thousands of two-instruction
1543
// functions, and the JIT pays per function (symbol resolution, inlining them
1544
// back) far more than it pays per instruction.
1545
//
1546
// The default is from the test suite's 70x12 table (Matching/
1547
// largeMatchTableCompileTime, ~6,800 states) on a release build: a bound of
1548
// 2,000 compiles it in 34s, 500 in 19s, 200 in 18.4s, 100 in 17s, 50 in
1549
// 18.5s, and no bound at all in 51s. The curve is flat from 75 to 200, so a
1550
// smaller table is not hurt by picking the low end of it.
1551
//
1552
// HOBBES_DFA_INLINE_THRESHOLD sets the bound; 0 removes it.
1553
0
size_t dfaInlineThreshold() {
1554
0
  static const size_t inlineThreshold = [] {
1555
0
    const char* v = std::getenv("HOBBES_DFA_INLINE_THRESHOLD");
1556
0
    if (v == nullptr) {
1557
0
      return static_cast<size_t>(100);
1558
0
    }
1559
0
    const auto i = strtoul(v, nullptr, 10);
1560
0
    return i == 0 ? std::numeric_limits<size_t>::max() : static_cast<size_t>(i);
1561
0
  }();
1562
0
  return inlineThreshold;
1563
0
}
1564
1565
0
bool shouldInlineState(const MDFA* dfa, stateidx_t state) {
1566
0
  const MStatePtr& s = dfa->states[state];
1567
1568
0
  if (dfa->states[state]->isPrimMatchRoot) {
1569
0
    return false;
1570
0
  } else if (s->refs <= 1 && dfa->inlinedStates < dfaInlineThreshold()) {
1571
0
    return true;
1572
0
  } else if (const FinishExpr* fe = is<FinishExpr>(s)) {
1573
0
    return isConst(fe->expr()) || (is<Var>(fe->expr()) != nullptr);
1574
0
  } else {
1575
0
    return false;
1576
0
  }
1577
0
}
1578
1579
ExprPtr liftPrimMatchExpr(MDFA* dfa, stateidx_t state);
1580
1581
0
ExprPtr liftDFAExpr(MDFA* dfa, stateidx_t state) {
1582
0
  if (shouldInlineState(dfa, state)) {
1583
0
    ++dfa->inlinedStates;
1584
0
    return liftDFAExprWithSwitchCompression(dfa, state);
1585
0
  } else {
1586
0
    FoldedStateCalls::const_iterator fsc = dfa->foldedStateCalls.find(state);
1587
1588
0
    if (fsc != dfa->foldedStateCalls.end()) {
1589
0
      return fsc->second;
1590
0
    } else if (dfa->states[state]->isPrimMatchRoot) {
1591
0
      return liftPrimMatchExpr(dfa, state);
1592
0
    } else {
1593
      // a folded state starts a function of its own, with its own room to inline into
1594
0
      size_t   outerInlined = dfa->inlinedStates;
1595
0
      dfa->inlinedStates = 0;
1596
0
      ExprPtr  def   = liftDFAExprWithSwitchCompression(dfa, state);
1597
0
      dfa->inlinedStates = outerInlined;
1598
      // the state function takes the variables it uses as arguments, except
1599
      // those it can reach anyway: globals, and the state functions lifted
1600
      // before it. Asking the environment about each free variable is much
1601
      // cheaper than enumerating every global for every fold (boot alone
1602
      // folds over six hundred states against thousands of globals)
1603
0
      str::seq fvns;
1604
0
      for (const auto& fvn : freeVars(def)) {
1605
0
        if (dfa->liftedStateFns.count(fvn) == 0 && !dfa->c->typeEnv()->hasBinding(fvn)) {
1606
0
          fvns.push_back(fvn);
1607
0
        }
1608
0
      }
1609
1610
0
      std::string stateFn = ".patfs." + str::from(state);
1611
0
      ExprPtr callexp = fncall(varName(dfa, stateFn), vars(fvns, dfa->rootLA), dfa->rootLA);
1612
1613
0
      dfa->foldedStates.push_back(FoldedState(stateFn, ExprPtr(new Fn(fvns, def, dfa->rootLA))));
1614
0
      dfa->foldedStateCalls[state] = callexp;
1615
0
      dfa->liftedStateFns.insert(stateFn);
1616
1617
0
      return callexp;
1618
0
    }
1619
0
  }
1620
0
}
1621
1622
0
ExprPtr liftDFAExpr(cc* c, const PatternRows& ps, const LexicalAnnotation& rootLA) {
1623
0
  MDFA pdfa;
1624
0
  pdfa.c         = c;
1625
0
  pdfa.inPrimSel = false;
1626
1627
0
  stateidx_t initState = makeDFA(&pdfa, ps, rootLA);
1628
0
  ExprPtr    me        = liftDFAExpr(&pdfa, initState);
1629
1630
0
  if (pdfa.foldedStates.empty()) {
1631
0
    return me;
1632
0
  } else {
1633
0
    LetRec::Bindings bs;
1634
0
    for (const auto& fs : pdfa.foldedStates) {
1635
0
      bs.push_back(LetRec::Binding(fs.first, fs.second));
1636
0
    }
1637
0
    return ExprPtr(new LetRec(bs, me, rootLA));
1638
0
  }
1639
0
}
1640
1641
// determine the row/expr set reachable from a DFA state
1642
using RowResults = std::map<size_t, ExprPtr>;
1643
1644
struct reachableRowExprsF : public switchMState<UnitV> {
1645
  const MDFA* dfa;
1646
  RowResults* results;
1647
1648
0
  reachableRowExprsF(const MDFA* dfa, RowResults* results) : dfa(dfa), results(results) { }
1649
1650
0
  UnitV with(const SwitchVal* x) const override {
1651
0
    if (x->defaultState() != nullState) {
1652
0
      switchOf(this->dfa->states[x->defaultState()], *this);
1653
0
    }
1654
0
    for (const auto& jmp : x->jumps()) {
1655
0
      switchOf(this->dfa->states[jmp.second], *this);
1656
0
    }
1657
0
    return unitv;
1658
0
  }
1659
1660
0
  UnitV with(const FinishExpr* x) const override {
1661
0
    auto ei = this->dfa->exprIdxs.find(x->expr().get());
1662
0
    if (ei == this->dfa->exprIdxs.end()) {
1663
0
      throw std::runtime_error("Internal error, match DFA returns non-indexed expression");
1664
0
    } else {
1665
0
      (*this->results)[ei->second] = x->expr();
1666
0
    }
1667
0
    return unitv;
1668
0
  }
1669
  
1670
0
  UnitV with(const LoadVars* x) const override {
1671
0
    switchOf(this->dfa->states[x->nextState()], *this);
1672
0
    return unitv;
1673
0
  }
1674
1675
0
  UnitV with(const SwitchVariant* x) const override {
1676
0
    if (x->defaultState() != nullState) {
1677
0
      switchOf(this->dfa->states[x->defaultState()], *this);
1678
0
    }
1679
0
    for (const auto& jmp : x->jumps()) {
1680
0
      switchOf(this->dfa->states[jmp.second], *this);
1681
0
    }
1682
0
    return unitv;
1683
0
  }
1684
};
1685
1686
0
RowResults findRowResults(MDFA* dfa, stateidx_t s) {
1687
0
  RowResults result;
1688
0
  switchOf(dfa->states[s], reachableRowExprsF(dfa, &result));
1689
0
  return result;
1690
0
}
1691
1692
0
long asLongRep(long*  x) { return *x; }
1693
0
long asLongRep(double x) { return asLongRep(reinterpret_cast<long*>(&x)); }
1694
1695
// derive a primitive search function from a DFA (or sub-DFA) that contains _only_ primitive tests
1696
using Args = std::map<std::string, llvm::Value *>;
1697
using StateBranches = std::map<stateidx_t, llvm::BasicBlock *>;
1698
1699
struct makePrimDFASF : public switchMState<UnitV> {
1700
  const Args&    args;
1701
  StateBranches* branches;
1702
  MDFA*          dfa;
1703
1704
0
  makePrimDFASF(const Args& args, StateBranches* branches, MDFA* dfa) : args(args), branches(branches), dfa(dfa) {
1705
0
  }
1706
1707
0
  llvm::Value* arg(const std::string& an) const {
1708
0
    auto a = this->args.find(an);
1709
0
    if (a == this->args.end()) {
1710
0
      throw std::runtime_error("Internal error, reference to undefined variable in primitive match: " + an);
1711
0
    } else {
1712
0
      return a->second;
1713
0
    }
1714
0
  }
1715
1716
0
  UnitV with(const SwitchVal* x) const override {
1717
0
    if (x->defaultState() == nullState) {
1718
0
      if (x->jumps().empty()) {
1719
0
        throw std::runtime_error("Internal error, empty switch statement in primitive match compilation");
1720
0
      } else {
1721
0
        throw std::runtime_error("Internal error, switches without default states not supported for primitive match compilation (on switch for " + x->switchVar() + " :: " + show(x->jumps()[0].first->primType()) + " with " + str::from(x->jumps().size()) + " cases)");
1722
0
      }
1723
0
    }
1724
1725
0
    if (!x->jumps().empty() && (is<Double>(x->jumps().begin()->first) != nullptr)) {
1726
0
      llvm::SwitchInst* s = withContext([&](auto&) {
1727
0
        return this->dfa->c->builder()->CreateSwitch(this->dfa->c->builder()->CreateBitCast(arg(x->switchVar()), longType()), blockForState(x->defaultState()), x->jumps().size());
1728
0
      });
1729
0
      for (const auto& jmp : x->jumps()) {
1730
0
        if (const Double* d = is<Double>(jmp.first)) {
1731
0
          s->addCase(civalue(asLongRep(d->value())), blockForState(jmp.second));
1732
0
        }
1733
0
      }
1734
0
    } else {
1735
0
      llvm::SwitchInst* s = withContext([&](auto&) {
1736
0
        return this->dfa->c->builder()->CreateSwitch(arg(x->switchVar()), blockForState(x->defaultState()), x->jumps().size());
1737
0
      });
1738
0
      for (const auto& jmp : x->jumps()) {
1739
0
        s->addCase(toLLVMConstantInt(jmp.first), blockForState(jmp.second));
1740
0
      }
1741
0
    }
1742
0
    return unitv;
1743
0
  }
1744
1745
0
  UnitV with(const FinishExpr* x) const override {
1746
0
    auto ei = this->dfa->exprIdxs.find(x->expr().get());
1747
0
    if (ei == this->dfa->exprIdxs.end()) {
1748
0
      throw std::runtime_error("Internal error, primitive match DFA returns non-indexed expression");
1749
0
    } else {
1750
0
      withContext([&](auto&) { this->dfa->c->builder()->CreateRet(cvalue(static_cast<int>(ei->second))); });
1751
0
    }
1752
0
    return unitv;
1753
0
  }
1754
1755
0
  [[noreturn]] UnitV with(const LoadVars*) const override {
1756
0
    throw std::runtime_error("Internal error, not a primitive match table (load vars)");
1757
0
  }
1758
1759
0
  [[noreturn]] UnitV with(const SwitchVariant*) const override {
1760
0
    throw std::runtime_error("Internal error, not a primitive match table (switch variant)");
1761
0
  }
1762
1763
0
  llvm::BasicBlock* blockForState(stateidx_t s) const {
1764
0
    auto b = this->branches->find(s);
1765
0
    if (b != this->branches->end()) {
1766
0
      return b->second;
1767
0
    } else {
1768
0
      return withContext([&](llvm::LLVMContext& ctx) {
1769
0
        llvm::BasicBlock* obb = this->dfa->c->builder()->GetInsertBlock();
1770
0
        llvm::BasicBlock* bb = llvm::BasicBlock::Create(ctx, ".pmst" + freshName(), obb->getParent());
1771
0
        this->dfa->c->builder()->SetInsertPoint(bb);
1772
0
        switchOf(this->dfa->states[s], *this);
1773
0
        (*this->branches)[s] = bb;
1774
0
        this->dfa->c->builder()->SetInsertPoint(obb);
1775
0
        return bb;
1776
0
      });
1777
0
    }
1778
0
  }
1779
};
1780
1781
0
llvm::Function* makePrimMatchDFAFunc(const std::string& fname, MDFA* dfa, stateidx_t s, const PrimFArgs& args) {
1782
0
  Types atys;
1783
0
  for (const auto& arg : args) {
1784
0
    if (!isUnit(arg.second)) {
1785
0
      atys.push_back(toLLVM(arg.second, true));
1786
0
    }
1787
0
  }
1788
1789
0
  llvm::Function* result   = withContext([&](auto&) {
1790
0
    return llvm::Function::Create(llvm::FunctionType::get(intType(), atys, false),
1791
0
                                  llvm::Function::ExternalLinkage, fname, dfa->c->module());
1792
0
  });
1793
0
  llvm::BasicBlock* bb     = withContext([result](llvm::LLVMContext& ctx) { return llvm::BasicBlock::Create(ctx, "entry", result); });
1794
1795
0
  withContext([dfa, bb](auto&) { dfa->c->builder()->SetInsertPoint(bb); });
1796
1797
0
  Args fargs;
1798
0
  llvm::Function::arg_iterator a = result->arg_begin();
1799
0
  for (const auto &arg : args) {
1800
0
    if (isUnit(arg.second)) {
1801
0
      fargs[arg.first] = cvalue(true);
1802
0
    } else {
1803
0
      a->setName(arg.first);
1804
0
      fargs[arg.first] = &*a;
1805
0
      ++a;
1806
0
    }
1807
0
  }
1808
1809
0
  StateBranches sb;
1810
0
  switchOf(dfa->states[s], makePrimDFASF(fargs, &sb, dfa));
1811
1812
0
  return result;
1813
0
}
1814
1815
class primdfafunc : public op {
1816
public:
1817
0
  primdfafunc(llvm::Function* vfn, const PrimFArgs& args) : vfn(vfn) {
1818
0
    MonoTypes atys;
1819
0
    if (args.empty()) {
1820
0
      atys.push_back(MonoTypePtr(Prim::make("unit")));
1821
0
    } else {
1822
0
      for (const auto& arg : args) {
1823
0
        atys.push_back(arg.second);
1824
0
      }
1825
0
    }
1826
0
    this->ftype = polytype(functy(atys, primty("int")));
1827
0
  }
1828
1829
0
  llvm::Value* apply(jitcc* c, const MonoTypes&, const MonoTypePtr&, const Exprs& es) override {
1830
0
    return withContext([&](auto&) { return fncall(c->builder(), this->vfn, this->vfn->getFunctionType(), compileArgs(c, es)); });
1831
0
  }
1832
1833
0
  PolyTypePtr type(typedb&) const override {
1834
0
    return this->ftype;
1835
0
  }
1836
private:
1837
  llvm::Function* vfn;
1838
  PolyTypePtr     ftype;
1839
};
1840
1841
0
void makeCompiledPrimMatchFunction(const std::string& fname, MDFA* dfa, stateidx_t state) {
1842
0
  const MStatePtr& mstate = dfa->states[state];
1843
0
  dfa->c->bindLLFunc(fname, new primdfafunc(makePrimMatchDFAFunc(fname, dfa, state, mstate->primFArgs), mstate->primFArgs));
1844
0
}
1845
1846
// derive a primitive match DFA to run in an interpreted mode, to minimize compilation overhead
1847
using IDFATransition = variant<int, long>;
1848
using IDFATransitions = array<std::pair<long, IDFATransition>>;
1849
1850
struct IDFAState {
1851
  long             reads;
1852
  IDFATransitions* transitions;
1853
  IDFATransition   def;
1854
};
1855
1856
0
MonoTypePtr dfaStateType() {
1857
0
  Variant::Members tcns;
1858
0
  tcns.push_back(Variant::Member("done", MonoTypePtr(Prim::make("int")),  0));
1859
0
  tcns.push_back(Variant::Member("step", MonoTypePtr(Prim::make("long")), 1));
1860
0
  MonoTypePtr tty(Variant::make(tcns));
1861
1862
0
  Record::Members dtfns;
1863
0
  dtfns.push_back(Record::Member(".f0", MonoTypePtr(Prim::make("long"))));
1864
0
  dtfns.push_back(Record::Member(".f1", tty));
1865
0
  MonoTypePtr dtty(Record::make(dtfns));
1866
1867
0
  Record::Members dfafns;
1868
0
  dfafns.push_back(Record::Member("reads",       MonoTypePtr(Prim::make("long"))));
1869
0
  dfafns.push_back(Record::Member("transitions", arrayty(dtty)));
1870
0
  dfafns.push_back(Record::Member("def",         tty));
1871
0
  return arrayty(MonoTypePtr(Record::make(dfafns)));
1872
0
}
1873
1874
using ArgPos = std::unordered_map<std::string, size_t>;
1875
using GlobalToLocalState = std::unordered_map<size_t, size_t>;
1876
1877
0
void mapStatesFrom(MDFA* dfa, stateidx_t state, GlobalToLocalState* localstate) {
1878
0
  if (localstate->find(state) == localstate->end()) {
1879
0
    if (state > dfa->states.size()) {
1880
0
      throw std::runtime_error("Internal error, invalid state produced for primitive DFA interpretation");
1881
0
    } else if (const SwitchVal* sv = is<SwitchVal>(dfa->states[state])) {
1882
0
      size_t lc = localstate->size();
1883
0
      (*localstate)[state] = lc;
1884
0
      for (const auto& jmp : sv->jumps()) {
1885
0
        mapStatesFrom(dfa, jmp.second, localstate);
1886
0
      }
1887
1888
0
      if (sv->defaultState() == nullState) {
1889
0
        throw std::runtime_error("Internal error, primitive DFAs without default states not supported for interpretation");
1890
0
      }
1891
0
      mapStatesFrom(dfa, sv->defaultState(), localstate);
1892
0
    } else if (is<FinishExpr>(dfa->states[state]) == nullptr) {
1893
0
      throw std::runtime_error("Internal error, invalid primitive DFA for interpretation");
1894
0
    }
1895
0
  }
1896
0
}
1897
1898
0
size_t localState(const GlobalToLocalState& localstate, stateidx_t state) {
1899
0
  auto ls = localstate.find(state);
1900
0
  if (ls == localstate.end()) {
1901
0
    throw std::runtime_error("Internal error, incorrectly determined local state index");
1902
0
  } else {
1903
0
    return ls->second;
1904
0
  }
1905
0
}
1906
1907
0
size_t reads(const ArgPos& argpos, const std::string& a) {
1908
0
  auto ai = argpos.find(a);
1909
0
  if (ai == argpos.end()) {
1910
0
    throw std::runtime_error("Internal error, undefined argument: " + a);
1911
0
  } else {
1912
0
    return ai->second;
1913
0
  }
1914
0
}
1915
1916
IDFATransitions* transitions(const ArgPos&, MDFA*, const SwitchVal::Jumps&, const GlobalToLocalState&, std::set<stateidx_t>*, array<IDFAState>*);
1917
IDFATransition transitionDef(const ArgPos&, MDFA*, stateidx_t, const GlobalToLocalState&, std::set<stateidx_t>*, array<IDFAState>*);
1918
1919
0
void copyStateDef(const ArgPos& argpos, MDFA* dfa, stateidx_t state, const GlobalToLocalState& localstate, std::set<stateidx_t>* dones, array<IDFAState>* dfaStates) {
1920
  // don't copy the same state twice
1921
0
  if (dones->find(state) != dones->end()) {
1922
0
    return;
1923
0
  }
1924
0
  dones->insert(state);
1925
1926
  // expect a primitive switch state at a predetermined output index
1927
0
  const SwitchVal* sv     = is<SwitchVal>(dfa->states[state]);
1928
0
  size_t           statei = localState(localstate, state);
1929
1930
0
  if (sv == nullptr) {
1931
0
    throw std::runtime_error("Internal error, expected primitive switch for interpreted DFA");
1932
0
  }
1933
1934
  // encode this particular state structure
1935
0
  IDFAState& staterec = dfaStates->data[statei];
1936
1937
0
  staterec.reads       = reads(argpos, sv->switchVar());
1938
0
  staterec.transitions = transitions(argpos, dfa, sv->jumps(), localstate, dones, dfaStates);
1939
0
  staterec.def         = transitionDef(argpos, dfa, sv->defaultState(), localstate, dones, dfaStates);
1940
0
}
1941
1942
0
IDFATransitions* transitions(const ArgPos& argpos, MDFA* dfa, const SwitchVal::Jumps& jmps, const GlobalToLocalState& localstate, std::set<stateidx_t>* dones, array<IDFAState>* dfaStates) {
1943
0
  using SortedSVJumps = std::map<long, IDFATransition>;
1944
1945
0
  SortedSVJumps ssvj;
1946
0
  for (const auto& jmp : jmps) {
1947
0
    if (const Long* lv = is<Long>(jmp.first)) {
1948
0
      ssvj[lv->value()] = transitionDef(argpos, dfa, jmp.second, localstate, dones, dfaStates);
1949
0
    } else {
1950
0
      throw std::runtime_error("Internal error, expected long value in DFA transition data");
1951
0
    }
1952
0
  }
1953
1954
0
  size_t msz = offsetof(IDFATransitions, data) + (ssvj.size() * sizeof(std::pair<long, IDFATransition>));
1955
0
  auto* result = reinterpret_cast<IDFATransitions*>(malloc(msz));
1956
0
  memset(reinterpret_cast<void*>(result), 0, msz);
1957
0
  result->size = ssvj.size();
1958
0
  size_t i = 0;
1959
0
  for (const auto& svj : ssvj) {
1960
0
    new (&result->data[i]) std::pair<long, IDFATransition>();
1961
0
    result->data[i].first  = svj.first;
1962
0
    result->data[i].second = svj.second;
1963
0
    ++i;
1964
0
  }
1965
0
  return result;
1966
0
}
1967
1968
0
IDFATransition transitionDef(const ArgPos& argpos, MDFA* dfa, stateidx_t s, const GlobalToLocalState& localstate, std::set<stateidx_t>* dones, array<IDFAState>* dfaStates) {
1969
0
  if (const FinishExpr* fe = is<FinishExpr>(dfa->states[s])) {
1970
0
    auto ei = dfa->exprIdxs.find(fe->expr().get());
1971
0
    if (ei == dfa->exprIdxs.end()) {
1972
0
      throw std::runtime_error("Internal error, unexpected result expression");
1973
0
    }
1974
0
    return IDFATransition(static_cast<int>(ei->second));
1975
0
  } else {
1976
0
    long nextState = localState(localstate, s);
1977
0
    copyStateDef(argpos, dfa, s, localstate, dones, dfaStates);
1978
0
    return IDFATransition(static_cast<long>(nextState));
1979
0
  }
1980
0
}
1981
1982
0
void makeInterpretedPrimMatchFunction(const std::string& fname, MDFA* dfa, stateidx_t state) {
1983
0
  const MStatePtr& mstate = dfa->states[state];
1984
1985
  // figure out what our arguments are
1986
0
  str::seq vnames;
1987
0
  Exprs    vargs;
1988
0
  ArgPos   argpos;
1989
0
  for (const auto& arg : mstate->primFArgs) {
1990
0
    argpos[arg.first] = vargs.size();
1991
0
    vnames.push_back(arg.first);
1992
0
    vargs.push_back(varName(dfa, arg.first));
1993
0
  }
1994
1995
  // map global states to local positions
1996
0
  GlobalToLocalState localstate;
1997
0
  mapStatesFrom(dfa, state, &localstate);
1998
1999
  // construct the DFA description in a consumable format
2000
0
  size_t msz = offsetof(array<IDFAState>, data) + (localstate.size() * sizeof(IDFAState));
2001
0
  auto* dfaStates = reinterpret_cast<array<IDFAState>*>(malloc(msz));
2002
0
  memset(reinterpret_cast<void*>(dfaStates), 0, msz);
2003
0
  dfaStates->size = localstate.size();
2004
2005
0
  std::set<stateidx_t> dones;
2006
0
  copyStateDef(argpos, dfa, state, localstate, &dones, dfaStates);
2007
2008
  // bind this DFA def to the global data set for this evaluator
2009
0
  std::string dfavar = fname + "_data";
2010
0
  dfa->c->bind(polytype(dfaStateType()), dfavar, dfaStates);
2011
2012
  // then we can interpret this DFA by filling in a fresh argument vector and then running our generic DFA evaluation function over the definition
2013
0
  ExprPtr runDFADef =
2014
0
    ExprPtr(
2015
0
      new Fn(
2016
0
        vnames,
2017
0
        fncall(varName(dfa, "runLongDFA"), list(var(dfavar, dfa->rootLA), ExprPtr(new Long(0, dfa->rootLA)), ExprPtr(new MkArray(vargs, dfa->rootLA))), dfa->rootLA),
2018
0
        dfa->rootLA
2019
0
      )
2020
0
    );
2021
2022
0
  dfa->foldedStates.push_back(FoldedState(fname, runDFADef));
2023
0
}
2024
2025
0
bool canMakeInterpretedPrimMatchFunction(MDFA* dfa, stateidx_t state) {
2026
0
  const MStatePtr& mstate = dfa->states[state];
2027
0
  for (const auto& arg : mstate->primFArgs) {
2028
0
    if (const Prim* pty = is<Prim>(arg.second)) {
2029
0
      if (pty->name() != "long") {
2030
0
        return false;
2031
0
      }
2032
0
    } else {
2033
0
      return false;
2034
0
    }
2035
0
  }
2036
0
  return true;
2037
0
}
2038
2039
// given that we want to compile a primitive DFA, decide how best to do it
2040
0
ExprPtr liftPrimMatchExpr(MDFA* dfa, stateidx_t state) {
2041
0
  static size_t    c      = 0;
2042
0
  std::string      fname  = ".pm.gen." + str::from(c++);
2043
0
  const MStatePtr& mstate = dfa->states[state];
2044
2045
0
  if (dfa->c->buildInterpretedMatches() && canMakeInterpretedPrimMatchFunction(dfa, state)) {
2046
0
    makeInterpretedPrimMatchFunction(fname, dfa, state);
2047
0
  } else {
2048
0
    makeCompiledPrimMatchFunction(fname, dfa, state);
2049
0
  }
2050
2051
0
  Exprs findEndStateArgs;
2052
0
  for (const auto& arg : mstate->primFArgs) {
2053
0
    findEndStateArgs.push_back(varName(dfa, arg.first));
2054
0
  }
2055
2056
  // defer to the primitive match, switch on the determined row
2057
0
  Switch::Bindings bs;
2058
0
  for (const auto& r : findRowResults(dfa, state)) {
2059
0
    bs.push_back(Switch::Binding(PrimitivePtr(new Int(static_cast<int>(r.first), dfa->rootLA)), r.second));
2060
0
  }
2061
0
  return ExprPtr(new Switch(fncall(var(fname, dfa->rootLA), findEndStateArgs, dfa->rootLA), bs, bs[0].exp, dfa->rootLA));
2062
0
}
2063
2064
}
2065