Coverage Report

Created: 2026-12-01 07:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hobbes/lib/hobbes/read/parser.C
Line
Count
Source
1
2
#include <cstdio>
3
#include <exception>
4
#include <fstream>
5
#include <hobbes/lang/expr.H>
6
#include <hobbes/lang/module.H>
7
#include <hobbes/lang/pat/pattern.H>
8
#include <hobbes/parse/grammar.H>
9
#include <hobbes/read/parser.H>
10
#include <hobbes/read/pgen/hexpr.parse.H>
11
#include <hobbes/util/autorelease.H>
12
#include <iostream>
13
#include <mutex>
14
#include <stack>
15
#include <stdexcept>
16
#include <string>
17
18
// protect access to lexer/parser globals (blech)
19
static std::recursive_mutex parse_mutex;
20
struct parse_mutex_lock {
21
20.1k
   parse_mutex_lock() { parse_mutex.lock(); }
22
20.1k
  ~parse_mutex_lock() { parse_mutex.unlock(); }
23
};
24
20.1k
#define LOCK_PARSER parse_mutex_lock parse_lock
25
26
////////////////////////////////////////////////////////
27
// bison parser defs
28
extern hobbes::cc*     yyParseCC;
29
extern std::string     yyVexpLexError;
30
extern hobbes::Module* yyParsedModule;
31
extern std::string     yyParsedVar;
32
extern hobbes::Expr*   yyParsedExpr;
33
extern std::exception_ptr yyParseThrown;
34
extern std::string     yyMatchDiagram;
35
extern int             yyInitToken;
36
extern std::string     yyModulePath;
37
extern int             yylineno;
38
extern int             yycolumn;
39
extern YYLTYPE         yyErrPos;
40
41
extern int yyparse();
42
extern void pushLexerParseState();
43
extern void popLexerParseState();
44
0
#define YY_BUF_SIZE 16384
45
struct yy_buffer_state;
46
using YY_BUFFER_STATE = yy_buffer_state *;
47
extern YY_BUFFER_STATE yy_scan_string(const char*);
48
extern YY_BUFFER_STATE yy_create_buffer(FILE*, int);
49
extern void yy_switch_to_buffer(YY_BUFFER_STATE);
50
extern void yy_delete_buffer(YY_BUFFER_STATE);
51
////////////////////////////////////////////////////////
52
53
namespace hobbes {
54
55
0
[[noreturn]] void throwFileError(const std::string& fname, const YYLTYPE& errPos, const std::string& emsg) {
56
0
  throw annotated_error::fileError(fname, Pos(errPos.first_line, errPos.first_column), Pos(errPos.last_line, errPos.last_column), emsg);
57
0
}
58
59
10.3k
[[noreturn]] void throwBufferError(const char* buffer, const YYLTYPE& errPos, const std::string& emsg) {
60
10.3k
  throw annotated_error::bufferError(buffer, Pos(errPos.first_line, errPos.first_column), Pos(errPos.last_line, errPos.last_column), emsg);
61
10.3k
}
62
63
// (parser may call itself recursively when importing scripts)
64
std::stack<YY_BUFFER_STATE> activeParseBuffers;
65
66
20.1k
void freeParserData() {
67
20.1k
  if (activeParseBuffers.empty()) {
68
20.1k
    AutoreleaseSet::reset();
69
20.1k
  }
70
20.1k
}
71
72
0
size_t openParseCount() {
73
0
  return activeParseBuffers.size();
74
0
}
75
76
template <typename T>
77
7.70k
  const T& checkReturn(const T& x) {
78
7.70k
    if (!x) {
79
0
      throw std::runtime_error("Internal error: parser failed to produce a value");
80
7.70k
    } else {
81
7.70k
      return x;
82
7.70k
    }
83
7.70k
  }
std::shared_ptr<hobbes::Module> const& hobbes::checkReturn<std::shared_ptr<hobbes::Module> >(std::shared_ptr<hobbes::Module> const&)
Line
Count
Source
77
599
  const T& checkReturn(const T& x) {
78
599
    if (!x) {
79
0
      throw std::runtime_error("Internal error: parser failed to produce a value");
80
599
    } else {
81
599
      return x;
82
599
    }
83
599
  }
std::shared_ptr<hobbes::Expr> const& hobbes::checkReturn<std::shared_ptr<hobbes::Expr> >(std::shared_ptr<hobbes::Expr> const&)
Line
Count
Source
77
7.10k
  const T& checkReturn(const T& x) {
78
7.10k
    if (!x) {
79
0
      throw std::runtime_error("Internal error: parser failed to produce a value");
80
7.10k
    } else {
81
7.10k
      return x;
82
7.10k
    }
83
7.10k
  }
84
85
// WHAT A FAILED PARSE FREES
86
//
87
// Grammar actions build tree nodes with a bare `new`, and the action that
88
// consumes a node takes ownership of it. A parse that fails leaves nodes that
89
// no action consumed, and each of the ways it can leave them has its own
90
// cleanup:
91
//
92
//  * values still on bison's stack at a syntax error are deleted by the
93
//    %destructor that hexpr.y declares for their types;
94
//  * strings, lists and the like are registered with the AutoreleaseSet as
95
//    they are made, and released between parses (see ParseScope, below);
96
//  * the finished tree, handed over by the start rule in a parse that then
97
//    fails, is deleted by the parse itself (see Parsed and ParseScope, below).
98
//
99
// The first of those only happens on the parser's own ways out, so an
100
// exception -- from the lexer (a literal out of range) or from an action (a
101
// match or a `parse` block that doesn't compile) -- is not allowed to unwind
102
// through yyparse: it is caught, the parse is stopped the parser's way, and
103
// runParserOnBuffer rethrows it afterwards (see yyParseThrown in hexpr.y).
104
//
105
// What is still stranded is the right-hand side of the one rule whose action
106
// threw, where that action hadn't yet taken ownership of it: bison leaves
107
// those symbols alone, since it can't tell which ones the action took.
108
109
// Every expression the parser returns is bounded in how deeply it nests
110
// (checkNestingDepth, and the reasoning behind it, in lang/expr.H): the parser
111
// builds a tree as deep as its input describes, and everything that walks the
112
// tree afterwards recurs through its levels. The check throws with the tree
113
// still referenced from here, which is safe: expression teardown is iterative
114
// whoever lets go of the tree, so unwinding past it costs one frame, not one
115
// per level.
116
//
117
// The same bound is applied a second time, earlier, by the compilers that
118
// grammar actions run mid-parse on sub-expressions (compileMatch for `\`,
119
// `match`, `let` with a pattern and comprehensions; makeParser for `parse`
120
// blocks) -- those walk what they are given before the parse is over and the
121
// check here can see it (OSS-Fuzz 556791547).
122
123
// One parse, from the scanner's point of view: the buffer it reads from, the
124
// lexer state it starts with, and the undoing of both when it is over.
125
//
126
// The undoing is what matters, and it is in a destructor so that it happens
127
// however the parse ends. yyparse can return -- on success, or on a syntax
128
// error it has recovered from -- or it can throw, when a grammar action does
129
// (a regex literal over its term limit, a numeric literal too large for its
130
// type). Teardown used to follow yyparse as plain statements, so the throwing
131
// path skipped it: the buffer was never closed, the count of open parses never
132
// came back down, and since that count is how the parser decides it is
133
// between parses and may release what the last one autoreleased, nothing was
134
// released again for the rest of the process (the OSS-Fuzz parse-expr harness
135
// grew by about 44KB per rejected input that way).
136
//
137
// The lexer state is the other half. The scanner keeps the start condition
138
// and the off-side-rule bookkeeping between tokens, and a parse that ends
139
// early leaves them wherever the failure found them; see pushLexerParseState
140
// in hexpr.l for what that did to the next parse. Saved on the way in and put
141
// back on the way out, every parse starts as a fresh process would, and the
142
// parse of an imported script -- which runs nested inside its importer's --
143
// hands the importer's state back when it is done.
144
//
145
// It also owns what the parse makes. The grammar's start rule hands the
146
// finished tree over through yyParsedModule and yyParsedExpr, and its action
147
// can run in a parse that fails: where a state has one thing it can do, bison
148
// does it without looking at the next token, so an expression followed by
149
// something that can't follow it is reduced all the way to the start rule --
150
// its tree handed over -- before the token is read and reported ("unexpected
151
// intV, expecting end of file"). Each reader used to take the tree after the
152
// parser returned, in a statement that the error was thrown past, and since
153
// the pointer is cleared for the next parse, nothing ever freed it: a string
154
// literal of 1MB with a digit after its closing quote is a million character
155
// constants, and each read of it left 145MB behind (OSS-Fuzz 587020633, where
156
// a fuzzer that keeps reading the same input in one process ran out of
157
// memory).
158
//
159
// So the hand-over belongs to the scope of the parse rather than to whoever
160
// asked for it: cleared on the way in, taken by runParserOnBuffer if the parse
161
// gets that far (take), and deleted on the way out if not. A reader has
162
// nothing to remember, and a new one can't forget. What an enclosing parse had
163
// been handed is kept aside and put back, so that this holds without relying
164
// on the start rule being the last thing a parse does.
165
struct Parsed {
166
  ModulePtr   module;
167
  ExprPtr     expr;
168
  std::string var; // the name defined, when a definition was read
169
};
170
171
class ParseScope {
172
public:
173
20.1k
  ParseScope(cc* c, int initTok, YY_BUFFER_STATE bs) : bs(bs), outerModule(yyParsedModule), outerExpr(yyParsedExpr), outerVar(yyParsedVar) {
174
20.1k
    yyParsedModule = nullptr;
175
20.1k
    yyParsedExpr   = nullptr;
176
20.1k
    yyParsedVar    = "";
177
20.1k
    yyParseCC      = c;
178
20.1k
    yyInitToken    = initTok;
179
20.1k
    yylineno       = 1;
180
20.1k
    yycolumn       = 1;
181
20.1k
    yyVexpLexError = ""; // a lexer error left by a parse that threw is not this one's
182
20.1k
    yyParseThrown  = nullptr;
183
20.1k
    yyErrPos       = YYLTYPE(); // nor is the position of one (see parseErrorPos)
184
20.1k
    yylloc         = YYLTYPE{1, 1, 1, 1}; // the lexer sets this per token, and an empty parse has none: its
185
                                          // end-of-file error would otherwise sit where the previous parse's last token was
186
20.1k
    pushLexerParseState();
187
20.1k
    yy_switch_to_buffer(bs);
188
20.1k
    activeParseBuffers.push(bs);
189
20.1k
  }
190
191
  // what the parse made, which is the caller's from here on
192
20.1k
  Parsed take() {
193
    // (out of the globals first: making a shared_ptr deletes what it was given
194
    //  if it can't allocate, and the destructor must not then delete it again)
195
20.1k
    Module* m = yyParsedModule;
196
20.1k
    Expr*   e = yyParsedExpr;
197
20.1k
    yyParsedModule = nullptr;
198
20.1k
    yyParsedExpr   = nullptr;
199
200
20.1k
    Parsed r;
201
20.1k
    r.var = yyParsedVar;
202
20.1k
    try {
203
20.1k
      r.module = ModulePtr(m);
204
20.1k
    } catch (...) {
205
0
      delete e;
206
0
      throw;
207
0
    }
208
20.1k
    r.expr = ExprPtr(e);
209
20.1k
    return r;
210
20.1k
  }
211
212
20.1k
  ~ParseScope() {
213
20.1k
    delete yyParsedModule;
214
20.1k
    delete yyParsedExpr;
215
20.1k
    yyParsedModule = this->outerModule;
216
20.1k
    yyParsedExpr   = this->outerExpr;
217
20.1k
    yyParsedVar    = this->outerVar;
218
219
20.1k
    activeParseBuffers.pop();
220
20.1k
    freeParserData();
221
20.1k
    yy_delete_buffer(this->bs);
222
20.1k
    if (!activeParseBuffers.empty()) { yy_switch_to_buffer(activeParseBuffers.top()); }
223
20.1k
    popLexerParseState();
224
20.1k
  }
225
226
  ParseScope(const ParseScope&) = delete;
227
  ParseScope& operator=(const ParseScope&) = delete;
228
private:
229
  YY_BUFFER_STATE bs;
230
  Module*         outerModule;
231
  Expr*           outerExpr;
232
  std::string     outerVar;
233
};
234
235
// where an error in the parse just run was found. yyerror records the
236
// position of a syntax error, but an error thrown from a lexer or grammar
237
// action (an unsupported literal, a duplicate field name) goes past yyerror,
238
// and until ParseScope cleared it the position reported for one of those was
239
// whatever the last syntax error in the process left behind. With it cleared,
240
// such an error is reported at the token the parser was on when it was thrown.
241
10.3k
YYLTYPE parseErrorPos() {
242
10.3k
  return yyErrPos.first_line != 0 ? yyErrPos : yylloc;
243
10.3k
}
244
245
20.1k
Parsed runParserOnBuffer(cc* c, int initTok, YY_BUFFER_STATE bs) {
246
20.1k
  Parsed parsed;
247
20.1k
  {
248
20.1k
    ParseScope scope(c, initTok, bs);
249
20.1k
    yyparse();
250
20.1k
    parsed = scope.take();
251
20.1k
  }
252
253
  // what the lexer or a grammar action threw, carried around the parser rather
254
  // than through it (see yyParseThrown in hexpr.y)
255
20.1k
  if (yyParseThrown) {
256
3.83k
    std::exception_ptr thrown;
257
3.83k
    std::swap(thrown, yyParseThrown);
258
3.83k
    yyVexpLexError = "";
259
3.83k
    std::rethrow_exception(thrown);
260
3.83k
  }
261
262
16.3k
  if (!yyVexpLexError.empty()) {
263
8.63k
    std::string msg = yyVexpLexError;
264
8.63k
    yyVexpLexError = "";
265
8.63k
    throw std::runtime_error(msg);
266
8.63k
  }
267
7.70k
  return parsed;
268
16.3k
}
269
270
0
Parsed runParserOnFile(cc* c, int initTok, const std::string& fname) {
271
0
  FILE* f = fopen(fname.c_str(), "r");
272
0
  if (f == nullptr) {
273
0
    throw std::runtime_error("Failed to open file for reading, '" + fname + "'");
274
0
  }
275
0
  try {
276
0
    LexicallyAnnotated::pushFileContext(fname);
277
0
    Parsed parsed = runParserOnBuffer(c, initTok, yy_create_buffer(f, YY_BUF_SIZE));
278
0
    fclose(f);
279
0
    LexicallyAnnotated::popContext();
280
0
    return parsed;
281
0
  } catch (annotated_error&) {
282
0
    fclose(f);
283
0
    LexicallyAnnotated::popContext();
284
0
    throw;
285
0
  } catch (std::exception& ex) {
286
0
    fclose(f);
287
0
    LexicallyAnnotated::popContext();
288
0
    throwFileError(fname, parseErrorPos(), ex.what());
289
0
  }
290
0
}
291
292
20.1k
Parsed runParserOnString(cc* c, int initTok, const char* s) {
293
20.1k
  try {
294
20.1k
    LexicallyAnnotated::pushLiteralContext(s);
295
20.1k
    Parsed parsed = runParserOnBuffer(c, initTok, yy_scan_string(s));
296
20.1k
    LexicallyAnnotated::popContext();
297
20.1k
    return parsed;
298
20.1k
  } catch (annotated_error&) {
299
2.11k
    LexicallyAnnotated::popContext();
300
2.11k
    throw;
301
10.3k
  } catch (std::exception& ex) {
302
10.3k
    LexicallyAnnotated::popContext();
303
10.3k
    throwBufferError(s, parseErrorPos(), ex.what());
304
10.3k
  }
305
20.1k
}
306
307
// a module's expressions get the same nesting bound as an expression read on
308
// its own (see defReadExpr below): a definition's body, and the body of each
309
// member of an instance, are the places a module holds an expression
310
599
static void checkNestingDepth(const ModulePtr& m) {
311
31.7k
  for (const auto& md : m->definitions()) {
312
31.7k
    if (const MVarDef* vd = is<MVarDef>(md)) {
313
6.30k
      checkNestingDepth(vd->varExpr());
314
25.4k
    } else if (const InstanceDef* id = is<InstanceDef>(md)) {
315
16.3k
      for (const auto& mvd : id->members()) {
316
16.3k
        checkNestingDepth(mvd->varExpr());
317
16.3k
      }
318
13.6k
    }
319
31.7k
  }
320
599
}
321
322
// yyModulePath is parser-global state copied into every MImport node.  Scope
323
// it to one read so a syntax/open failure cannot make a later in-memory module
324
// search the failed file's directory (and potentially load a library there).
325
class ModulePathScope {
326
public:
327
20.1k
  explicit ModulePathScope(const std::string& path) : previous(yyModulePath) {
328
20.1k
    yyModulePath = path;
329
20.1k
  }
330
20.1k
  ~ModulePathScope() noexcept { yyModulePath.swap(this->previous); }
331
332
  ModulePathScope(const ModulePathScope&) = delete;
333
  ModulePathScope& operator=(const ModulePathScope&) = delete;
334
335
private:
336
  std::string previous;
337
};
338
339
0
ModulePtr defReadModuleFile(cc* c, const std::string& file) {
340
0
  LOCK_PARSER;
341
342
0
  ModulePathScope modulePath(str::rsplit(file, "/").first);
343
0
  ModulePtr m = checkReturn(runParserOnFile(c, TPARSEMODULE, file).module);
344
0
  checkNestingDepth(m);
345
0
  return m;
346
0
}
347
348
599
ModulePtr defReadModule(cc* c, const char* text) {
349
599
  LOCK_PARSER;
350
351
599
  ModulePathScope modulePath("");
352
599
  ModulePtr m = checkReturn(runParserOnString(c, TPARSEMODULE, text).module);
353
599
  checkNestingDepth(m);
354
599
  return m;
355
599
}
356
357
599
ModulePtr defReadModule(cc* c, const std::string& text) {
358
599
  return defReadModule(c, text.c_str());
359
599
}
360
361
0
ExprDefn defReadExprDefn(cc* c, const std::string& expr) {
362
0
  LOCK_PARSER;
363
364
0
  ModulePathScope modulePath("");
365
0
  Parsed parsed = runParserOnString(c, TPARSEDEFN, expr.c_str());
366
367
0
  ExprPtr e = checkReturn(parsed.expr);
368
0
  checkNestingDepth(e);
369
0
  return ExprDefn(parsed.var, e);
370
0
}
371
372
19.5k
ExprPtr defReadExpr(cc* c, const std::string& expr) {
373
19.5k
  LOCK_PARSER;
374
375
19.5k
  ModulePathScope modulePath("");
376
19.5k
  ExprPtr e = checkReturn(runParserOnString(c, TPARSEEXPR, expr.c_str()).expr);
377
19.5k
  checkNestingDepth(e);
378
19.5k
  return e;
379
19.5k
}
380
381
// allow variable and pattern variable overloading
382
// (these bare `new`s are not autoreleased: the consuming grammar action wraps
383
// them, and a syntax error that discards them mid-parse runs the %destructor
384
// hexpr.y declares for their types. What still leaks them is an action that
385
// throws, since the exception unwinds past bison's cleanup -- see
386
// runParserOnBuffer above for what that path does and does not put back)
387
489k
Expr* defVarCtor(const std::string& vn, const LexicalAnnotation& la) { return new Var(vn, la); }
388
VarCtorFn varCtorFn = &defVarCtor;
389
0
void overrideVarCtor(VarCtorFn f) { varCtorFn = f; }
390
391
584k
Pattern* defPatVarCtor(const std::string& vn, const LexicalAnnotation& la) { return new MatchAny(vn, la); }
392
PatVarCtorFn patVarCtorFn = &defPatVarCtor;
393
0
void overridePatVarCtor(PatVarCtorFn f) { patVarCtorFn = f; }
394
395
}
396