Coverage Report

Created: 2025-08-25 07:03

/src/testdir/tests/capi/luaL_loadbuffer_proto/serializer.cc
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * SPDX-License-Identifier: BSD-2-Clause
3
 *
4
 * Copyright 2022, Tarantool AUTHORS, please see AUTHORS file.
5
 */
6
#include "serializer.h"
7
8
#include <stack>
9
#include <string>
10
11
/**
12
* If control flow reaches the point of the unreachable(), the program is
13
* undefined. It is useful in situations where the compiler cannot deduce
14
* the unreachability of the code.
15
*/
16
#if __has_builtin(__builtin_unreachable) || defined(__GNUC__)
17
0
#  define unreachable() (assert(0), __builtin_unreachable())
18
#else
19
#  define unreachable() (assert(0))
20
#endif
21
22
using namespace lua_grammar;
23
24
extern char preamble_lua[];
25
26
#define PROTO_TOSTRING(TYPE, VAR_NAME) \
27
  std::string TYPE##ToString(const TYPE & (VAR_NAME))
28
29
/* PROTO_TOSTRING version for nested (depth=2) protobuf messages. */
30
#define NESTED_PROTO_TOSTRING(TYPE, VAR_NAME, PARENT_MESSAGE) \
31
  std::string TYPE##ToString \
32
  (const PARENT_MESSAGE::TYPE & (VAR_NAME))
33
34
namespace luajit_fuzzer {
35
namespace {
36
37
/*
38
 * The following keywords are reserved and cannot be used as names,
39
 * see Lua 5.1 Reference Manual, 2.1 – Lexical Conventions.
40
 */
41
const std::set<std::string> KReservedLuaKeywords {
42
  "and",
43
  "break",
44
  "do",
45
  "else",
46
  "elseif",
47
  "end",
48
  "false",
49
  "for",
50
  "function",
51
  "if",
52
  "in",
53
  "local",
54
  "nil",
55
  "not",
56
  "or",
57
  "repeat",
58
  "return",
59
  "then",
60
  "true",
61
  "until",
62
  "while",
63
};
64
65
const std::string kCounterNamePrefix = "counter_";
66
const std::string kNumberWrapperName = "always_number";
67
const std::string kBinOpWrapperName = "only_numbers_cmp";
68
const std::string kNotNaNAndNilWrapperName = "not_nan_and_nil";
69
70
PROTO_TOSTRING(Block, block);
71
PROTO_TOSTRING(Chunk, chunk);
72
73
PROTO_TOSTRING(Statement, stat);
74
75
/** LastStatement and nested types. */
76
PROTO_TOSTRING(LastStatement, laststat);
77
NESTED_PROTO_TOSTRING(ReturnOptionalExpressionList, explist, LastStatement);
78
79
/**
80
 * Statement options.
81
 */
82
83
/** AssignmentList and nested types. */
84
PROTO_TOSTRING(AssignmentList, assignmentlist);
85
NESTED_PROTO_TOSTRING(VariableList, varlist, AssignmentList);
86
87
/** FunctionCall and nested types. */
88
PROTO_TOSTRING(FunctionCall, call);
89
NESTED_PROTO_TOSTRING(Args, args, FunctionCall);
90
NESTED_PROTO_TOSTRING(PrefixArgs, prefixargs, FunctionCall);
91
NESTED_PROTO_TOSTRING(PrefixNamedArgs, prefixnamedargs, FunctionCall);
92
93
/** DoBlock, WhileCycle and RepeatCycle clauses. */
94
PROTO_TOSTRING(DoBlock, block);
95
PROTO_TOSTRING(WhileCycle, whilecycle);
96
PROTO_TOSTRING(RepeatCycle, repeatcycle);
97
98
/** IfStatement and nested types. */
99
PROTO_TOSTRING(IfStatement, statement);
100
NESTED_PROTO_TOSTRING(ElseIfBlock, elseifblock, IfStatement);
101
102
/** ForCycleName and ForCycleList clauses. */
103
PROTO_TOSTRING(ForCycleName, forcyclename);
104
PROTO_TOSTRING(ForCycleList, forcyclelist);
105
106
/** Function and nested types. */
107
PROTO_TOSTRING(Function, func);
108
NESTED_PROTO_TOSTRING(FuncName, funcname, Function);
109
110
PROTO_TOSTRING(NameList, namelist);
111
NESTED_PROTO_TOSTRING(NameListWithEllipsis, namelist, FuncBody);
112
NESTED_PROTO_TOSTRING(ParList, parlist, FuncBody);
113
114
/** LocalFunc and LocalNames clauses. */
115
PROTO_TOSTRING(LocalFunc, localfunc);
116
PROTO_TOSTRING(LocalNames, localnames);
117
118
/**
119
 * Expressions and variables.
120
 */
121
122
/** Expressions clauses. */
123
PROTO_TOSTRING(ExpressionList, explist);
124
PROTO_TOSTRING(OptionalExpressionList, explist);
125
PROTO_TOSTRING(PrefixExpression, prefExpr);
126
127
/* Variable and nested types. */
128
PROTO_TOSTRING(Variable, var);
129
NESTED_PROTO_TOSTRING(IndexWithExpression, indexexpr, Variable);
130
NESTED_PROTO_TOSTRING(IndexWithName, indexname, Variable);
131
132
/** Expression and nested types. */
133
PROTO_TOSTRING(Expression, expr);
134
NESTED_PROTO_TOSTRING(AnonFunc, function, Expression);
135
NESTED_PROTO_TOSTRING(ExpBinaryOpExp, binary, Expression);
136
NESTED_PROTO_TOSTRING(UnaryOpExp, unary, Expression);
137
138
/**
139
 * Tables and fields.
140
 */
141
PROTO_TOSTRING(TableConstructor, table);
142
PROTO_TOSTRING(FieldList, fieldlist);
143
NESTED_PROTO_TOSTRING(FieldWithFieldSep, field, FieldList);
144
145
/** Field and nested types. */
146
PROTO_TOSTRING(Field, field);
147
NESTED_PROTO_TOSTRING(ExpressionAssignment, assignment, Field);
148
NESTED_PROTO_TOSTRING(NameAssignment, assignment, Field);
149
PROTO_TOSTRING(FieldSep, sep);
150
151
/** Operators. */
152
PROTO_TOSTRING(BinaryOperator, op);
153
PROTO_TOSTRING(UnaryOperator, op);
154
155
/** Identifier (Name). */
156
PROTO_TOSTRING(Name, name);
157
158
std::string
159
NumberWrappedExpressionToString(const Expression &expr)
160
21.4k
{
161
21.4k
  std::string retval;
162
21.4k
  retval += kNumberWrapperName;
163
21.4k
  retval += "(";
164
21.4k
  retval += ExpressionToString(expr);
165
21.4k
  retval += ")";
166
167
21.4k
  return retval;
168
21.4k
}
169
170
std::string
171
AllowedIndexExpressionToString(const Expression &expr)
172
6.44k
{
173
6.44k
  std::string retval;
174
6.44k
  retval += kNotNaNAndNilWrapperName;
175
6.44k
  retval += "(";
176
6.44k
  retval += ExpressionToString(expr);
177
6.44k
  retval += ")";
178
6.44k
  return retval;
179
6.44k
}
180
181
/**
182
 * Class that controls id creation for counters. Basically, a
183
 * variable wrapper that guarantees variable to be incremented.
184
 */
185
class CounterIdProvider {
186
public:
187
  /** Returns number of id provided. */
188
  std::size_t count()
189
183k
  {
190
183k
    return id_;
191
183k
  }
192
193
  /** Returns a new id that was not used after last clean(). */
194
  std::size_t next()
195
165k
  {
196
165k
    return id_++;
197
165k
  }
198
199
  /**
200
   * Cleans history. Should be used to make fuzzer starts
201
   * independent.
202
   */
203
  void clean()
204
18.6k
  {
205
18.6k
    id_ = 0;
206
18.6k
  }
207
208
private:
209
  std::size_t id_ = 0;
210
};
211
212
/** A singleton for counter id provider. */
213
CounterIdProvider&
214
GetCounterIdProvider()
215
367k
{
216
367k
  static CounterIdProvider provider;
217
367k
  return provider;
218
367k
}
219
220
std::string
221
GetCounterName(std::size_t id)
222
330k
{
223
330k
  return kCounterNamePrefix + std::to_string(id);
224
330k
}
225
226
/** Returns `<counter_name> = <counter_name> + 1`. */
227
std::string
228
GetCounterIncrement(const std::string &counter_name)
229
165k
{
230
165k
  std::string retval = counter_name;
231
165k
  retval += " = ";
232
165k
  retval += counter_name;
233
165k
  retval += " + 1;\n";
234
165k
  return retval;
235
165k
}
236
237
/**
238
 * Returns `if <counter_name> > kMaxCounterValue then
239
 * <then_block> end`.
240
 */
241
std::string
242
GetCondition(const std::string &counter_name, const std::string &then_block)
243
165k
{
244
165k
  std::string retval = "if ";
245
165k
  retval += counter_name;
246
165k
  retval += " > ";
247
165k
  retval += std::to_string(kMaxCounterValue);
248
165k
  retval += " then ";
249
165k
  retval += then_block;
250
165k
  retval += " end\n";
251
165k
  return retval;
252
165k
}
253
254
/**
255
 * Class that registers and provides context during code
256
 * generation.
257
 * Used to generate correct Lua code.
258
 */
259
class Context {
260
public:
261
  enum class BlockType {
262
    kReturnable,
263
    kBreakable,
264
    kReturnableWithVararg,
265
  };
266
267
  void step_in(BlockType type)
268
165k
  {
269
165k
    block_stack_.push(type);
270
165k
    if (block_type_is_returnable_(type)) {
271
47.9k
      returnable_stack_.push(type);
272
47.9k
    }
273
165k
  }
274
275
  void step_out()
276
165k
  {
277
165k
    assert(!block_stack_.empty());
278
165k
    if (block_type_is_returnable_(block_stack_.top())) {
279
47.9k
      assert(!returnable_stack_.empty());
280
47.9k
      returnable_stack_.pop();
281
47.9k
    }
282
165k
    block_stack_.pop();
283
165k
  }
284
285
  std::string get_next_block_setup()
286
165k
  {
287
165k
    std::size_t id = GetCounterIdProvider().next();
288
165k
    std::string counter_name = GetCounterName(id);
289
290
165k
    return GetCondition(counter_name, get_exit_statement_()) +
291
165k
           GetCounterIncrement(counter_name);
292
165k
  }
293
294
  bool break_is_possible()
295
5.07k
  {
296
5.07k
    return !block_stack_.empty() &&
297
5.07k
           block_stack_.top() == BlockType::kBreakable;
298
5.07k
  }
299
300
  bool return_is_possible()
301
18.5k
  {
302
18.5k
    return !returnable_stack_.empty();
303
18.5k
  }
304
305
  bool vararg_is_possible()
306
8.30k
  {
307
8.30k
    return (returnable_stack_.empty() ||
308
8.30k
      (!returnable_stack_.empty() &&
309
1.88k
       returnable_stack_.top() ==
310
1.88k
        BlockType::kReturnableWithVararg));
311
8.30k
  }
312
313
private:
314
315
  bool block_type_is_returnable_(BlockType type)
316
330k
  {
317
330k
    switch (type) {
318
234k
    case BlockType::kBreakable:
319
234k
      return false;
320
89.4k
    case BlockType::kReturnable:
321
95.9k
    case BlockType::kReturnableWithVararg:
322
95.9k
      return true;
323
330k
    }
324
0
    unreachable();
325
0
  }
326
327
  std::string get_exit_statement_()
328
165k
  {
329
165k
    assert(!block_stack_.empty());
330
165k
    switch (block_stack_.top()) {
331
117k
    case BlockType::kBreakable:
332
117k
      return "break";
333
44.7k
    case BlockType::kReturnable:
334
47.9k
    case BlockType::kReturnableWithVararg:
335
47.9k
      return "return";
336
165k
    }
337
0
    unreachable();
338
0
  }
339
340
  std::stack<BlockType> block_stack_;
341
  /*
342
   * The returnable block can be exited with return from
343
   * the breakable block within it, but the breakable block
344
   * cannot be exited with break from the returnable block within
345
   * it.
346
   * Valid code:
347
   * `function foo() while true do return end end`
348
   * Erroneous code:
349
   * `while true do function foo() break end end`
350
   * This stack is used to check if `return` is possible.
351
   */
352
  std::stack<BlockType> returnable_stack_;
353
};
354
355
Context&
356
GetContext()
357
527k
{
358
527k
  static Context context;
359
527k
  return context;
360
527k
}
361
362
/**
363
 * Block may be placed not only in a cycle, so specially for cycles
364
 * there is a function that will add a break condition and a
365
 * counter increment.
366
 */
367
std::string
368
BlockToStringCycleProtected(const Block &block)
369
117k
{
370
117k
  std::string retval = GetContext().get_next_block_setup();
371
117k
  retval += ChunkToString(block.chunk());
372
117k
  return retval;
373
117k
}
374
375
/**
376
 * DoBlock may be placed not only in a cycle, so specially for
377
 * cycles there is a function that will call
378
 * BlockToStringCycleProtected().
379
 */
380
std::string
381
DoBlockToStringCycleProtected(const DoBlock &block)
382
45.1k
{
383
45.1k
  std::string retval = "do\n";
384
45.1k
  retval += BlockToStringCycleProtected(block.block());
385
45.1k
  retval += "end\n";
386
45.1k
  return retval;
387
45.1k
}
388
389
/**
390
 * FuncBody may contain recursive calls, so for all function bodies,
391
 * there is a function that adds a return condition and a counter
392
 * increment.
393
 */
394
std::string
395
FuncBodyToStringReqProtected(const FuncBody &body)
396
47.9k
{
397
47.9k
  std::string body_str = "( ";
398
47.9k
  if (body.has_parlist()) {
399
11.8k
    body_str += ParListToString(body.parlist());
400
11.8k
  }
401
47.9k
  body_str += " )\n\t";
402
403
47.9k
  body_str += GetContext().get_next_block_setup();
404
405
47.9k
  body_str += BlockToString(body.block());
406
47.9k
  body_str += "end\n";
407
47.9k
  return body_str;
408
47.9k
}
409
410
bool
411
FuncBodyHasVararg(const FuncBody &body)
412
47.9k
{
413
47.9k
  if (!body.has_parlist()) {
414
36.1k
    return false;
415
36.1k
  }
416
11.8k
  const FuncBody::ParList &parlist = body.parlist();
417
11.8k
  switch (parlist.parlist_oneof_case()) {
418
2.15k
  case FuncBody::ParList::ParlistOneofCase::kNamelist:
419
2.15k
    return parlist.namelist().has_ellipsis();
420
1.90k
  case FuncBody::ParList::ParlistOneofCase::kEllipsis:
421
1.90k
    return true;
422
7.77k
  default:
423
7.77k
    return parlist.namelist().has_ellipsis();
424
11.8k
  }
425
11.8k
}
426
427
Context::BlockType
428
GetFuncBodyType(const FuncBody &body)
429
47.9k
{
430
47.9k
  return FuncBodyHasVararg(body) ?
431
3.26k
    Context::BlockType::kReturnableWithVararg :
432
47.9k
    Context::BlockType::kReturnable;
433
47.9k
}
434
435
std::string
436
ClearIdentifier(const std::string &identifier)
437
427k
{
438
427k
  std::string cleared;
439
440
427k
  bool has_first_not_digit = false;
441
427k
  for (char c : identifier) {
442
285k
    if (has_first_not_digit && (std::iswalnum(c) || c == '_')) {
443
163k
      cleared += c;
444
163k
    } else if (std::isalpha(c) || c == '_') {
445
27.5k
      has_first_not_digit = true;
446
27.5k
      cleared += c;
447
93.9k
    } else {
448
93.9k
      cleared += '_';
449
93.9k
    }
450
285k
  }
451
427k
  return cleared;
452
427k
}
453
454
inline std::string
455
clamp(std::string s, size_t maxSize = kMaxStrLength)
456
752k
{
457
752k
  if (s.size() > maxSize)
458
17.7k
    s.resize(maxSize);
459
752k
  return s;
460
752k
}
461
462
inline double
463
clamp(double number, double upper, double lower)
464
32.6k
{
465
32.6k
  return number <= lower ? lower :
466
32.6k
         number >= upper ? upper : number;
467
32.6k
}
468
469
inline std::string
470
ConvertToStringDefault(const std::string &s, bool sanitize = false)
471
752k
{
472
752k
  std::string ident = clamp(s);
473
752k
  if (sanitize)
474
427k
    ident = ClearIdentifier(ident);
475
752k
  if (ident.empty())
476
668k
    ident = std::string(kDefaultIdent);
477
752k
  return ident;
478
752k
}
479
480
PROTO_TOSTRING(Block, block)
481
88.9k
{
482
88.9k
  return ChunkToString(block.chunk());
483
88.9k
}
484
485
PROTO_TOSTRING(Chunk, chunk)
486
206k
{
487
206k
  std::string chunk_str;
488
538k
  for (int i = 0; i < chunk.stat_size(); ++i)
489
332k
    chunk_str += StatementToString(chunk.stat(i)) + "\n";
490
491
206k
  if (chunk.has_laststat())
492
23.6k
    chunk_str += LastStatementToString(chunk.laststat()) + "\n";
493
494
206k
  return chunk_str;
495
206k
}
496
497
/**
498
 * LastStatement and nested types.
499
 */
500
PROTO_TOSTRING(LastStatement, laststat)
501
23.6k
{
502
23.6k
  std::string laststat_str;
503
23.6k
  using LastStatType = LastStatement::LastOneofCase;
504
23.6k
  switch (laststat.last_oneof_case()) {
505
7.40k
  case LastStatType::kExplist:
506
7.40k
    laststat_str = ReturnOptionalExpressionListToString(
507
7.40k
      laststat.explist());
508
7.40k
    break;
509
5.07k
  case LastStatType::kBreak:
510
5.07k
    if (GetContext().break_is_possible()) {
511
2.34k
      laststat_str = "break";
512
2.34k
    }
513
5.07k
    break;
514
11.1k
  default:
515
    /* Chosen as default in order to decrease number of 'break's. */
516
11.1k
    laststat_str = ReturnOptionalExpressionListToString(
517
11.1k
      laststat.explist());
518
11.1k
    break;
519
23.6k
  }
520
521
  /*
522
   * Add a semicolon when last statement is not empty
523
   * to avoid errors like:
524
   *
525
   * <preamble.lua>
526
   * (nil):Name0()
527
   * (nil)() -- ambiguous syntax (function call x new statement) near '('
528
   */
529
23.6k
  if (!laststat_str.empty())
530
10.5k
    laststat_str += "; ";
531
532
23.6k
  return laststat_str;
533
23.6k
}
534
535
NESTED_PROTO_TOSTRING(ReturnOptionalExpressionList, explist, LastStatement)
536
18.5k
{
537
18.5k
  if (!GetContext().return_is_possible()) {
538
10.3k
    return "";
539
10.3k
  }
540
541
8.22k
  std::string explist_str = "return";
542
8.22k
  if (explist.has_explist()) {
543
4.90k
    explist_str += " " + ExpressionListToString(explist.explist());
544
4.90k
    explist_str += " ";
545
4.90k
  }
546
8.22k
  return explist_str;
547
18.5k
}
548
549
/**
550
 * Statement and statement options.
551
 */
552
PROTO_TOSTRING(Statement, stat)
553
332k
{
554
332k
  std::string stat_str;
555
332k
  using StatType = Statement::StatOneofCase;
556
332k
  switch (stat.stat_oneof_case()) {
557
34.0k
  case StatType::kList:
558
34.0k
    stat_str = AssignmentListToString(stat.list());
559
34.0k
    break;
560
74.8k
  case StatType::kCall:
561
74.8k
    stat_str = FunctionCallToString(stat.call());
562
74.8k
    break;
563
3.96k
  case StatType::kBlock:
564
3.96k
    stat_str = DoBlockToString(stat.block());
565
3.96k
    break;
566
14.9k
  case StatType::kWhilecycle:
567
14.9k
    stat_str = WhileCycleToString(stat.whilecycle());
568
14.9k
    break;
569
71.9k
  case StatType::kRepeatcycle:
570
71.9k
    stat_str = RepeatCycleToString(stat.repeatcycle());
571
71.9k
    break;
572
10.4k
  case StatType::kIfstat:
573
10.4k
    stat_str = IfStatementToString(stat.ifstat());
574
10.4k
    break;
575
8.46k
  case StatType::kForcyclename:
576
8.46k
    stat_str = ForCycleNameToString(stat.forcyclename());
577
8.46k
    break;
578
21.7k
  case StatType::kForcyclelist:
579
21.7k
    stat_str = ForCycleListToString(stat.forcyclelist());
580
21.7k
    break;
581
7.16k
  case StatType::kFunc:
582
7.16k
    stat_str = FunctionToString(stat.func());
583
7.16k
    break;
584
14.1k
  case StatType::kLocalfunc:
585
14.1k
    stat_str = LocalFuncToString(stat.localfunc());
586
14.1k
    break;
587
6.52k
  case StatType::kLocalnames:
588
6.52k
    stat_str = LocalNamesToString(stat.localnames());
589
6.52k
    break;
590
64.3k
  default:
591
    /**
592
     * Chosen arbitrarily more for simplicity.
593
     * TODO: Choose "more interesting" defaults.
594
     */
595
64.3k
    stat_str = AssignmentListToString(stat.list());
596
64.3k
    break;
597
332k
  }
598
599
  /*
600
   * Always add a semicolon regardless of grammar
601
   * to avoid errors like:
602
   *
603
   * <preamble.lua>
604
   * (nil):Name0()
605
   * (nil)() -- ambiguous syntax (function call x new statement) near '('
606
   */
607
332k
  stat_str += "; ";
608
609
332k
  return stat_str;
610
332k
}
611
612
/**
613
 * AssignmentList and nested types.
614
 */
615
PROTO_TOSTRING(AssignmentList, assignmentlist)
616
98.4k
{
617
98.4k
  std::string list_str = VariableListToString(assignmentlist.varlist());
618
98.4k
  list_str += " = " + ExpressionListToString(assignmentlist.explist());
619
98.4k
  return list_str;
620
98.4k
}
621
622
NESTED_PROTO_TOSTRING(VariableList, varlist, AssignmentList)
623
98.4k
{
624
98.4k
  std::string varlist_str = VariableToString(varlist.var());
625
125k
  for (int i = 0; i < varlist.vars_size(); ++i) {
626
26.7k
    varlist_str += ", " + VariableToString(varlist.vars(i));
627
26.7k
    varlist_str += " ";
628
26.7k
  }
629
98.4k
  return varlist_str;
630
98.4k
}
631
632
/**
633
 * FunctionCall and nested types.
634
 */
635
PROTO_TOSTRING(FunctionCall, call)
636
93.8k
{
637
93.8k
  using FuncCallType = FunctionCall::CallOneofCase;
638
93.8k
  switch (call.call_oneof_case()) {
639
19.3k
  case FuncCallType::kPrefArgs:
640
19.3k
    return PrefixArgsToString(call.prefargs());
641
7.91k
  case FuncCallType::kNamedArgs:
642
7.91k
    return PrefixNamedArgsToString(call.namedargs());
643
66.5k
  default:
644
    /* Chosen for more variability of generated programs. */
645
66.5k
    return PrefixNamedArgsToString(call.namedargs());
646
93.8k
  }
647
93.8k
}
648
649
NESTED_PROTO_TOSTRING(Args, args, FunctionCall)
650
93.8k
{
651
93.8k
  using ArgsType = FunctionCall::Args::ArgsOneofCase;
652
93.8k
  switch (args.args_oneof_case()) {
653
8.76k
  case ArgsType::kExplist:
654
8.76k
    return "(" + OptionalExpressionListToString(args.explist()) +
655
8.76k
           ")";
656
1.84k
  case ArgsType::kTableconstructor:
657
1.84k
    return TableConstructorToString(args.tableconstructor());
658
7.52k
  case ArgsType::kStr:
659
7.52k
    return "'" + ConvertToStringDefault(args.str()) + "'";
660
75.6k
  default:
661
    /* For more variability. */
662
75.6k
    return TableConstructorToString(args.tableconstructor());
663
93.8k
  }
664
93.8k
}
665
666
NESTED_PROTO_TOSTRING(PrefixArgs, prefixargs, FunctionCall)
667
19.3k
{
668
19.3k
  std::string prefixargs_str = PrefixExpressionToString(
669
19.3k
    prefixargs.prefixexp());
670
19.3k
  prefixargs_str += " " + ArgsToString(prefixargs.args());
671
19.3k
  return prefixargs_str;
672
19.3k
}
673
674
NESTED_PROTO_TOSTRING(PrefixNamedArgs, prefixnamedargs, FunctionCall)
675
74.4k
{
676
74.4k
  std::string predixnamedargs_str = PrefixExpressionToString(
677
74.4k
    prefixnamedargs.prefixexp());
678
74.4k
  predixnamedargs_str += ":" + NameToString(prefixnamedargs.name());
679
74.4k
  predixnamedargs_str += " " + ArgsToString(prefixnamedargs.args());
680
74.4k
  return predixnamedargs_str;
681
74.4k
}
682
683
/**
684
 * DoBlock clause.
685
 */
686
PROTO_TOSTRING(DoBlock, block)
687
3.96k
{
688
3.96k
  return "do\n" + BlockToString(block.block()) + "end\n";
689
3.96k
}
690
691
/**
692
 * WhileCycle clause.
693
 */
694
PROTO_TOSTRING(WhileCycle, whilecycle)
695
14.9k
{
696
14.9k
  GetContext().step_in(Context::BlockType::kBreakable);
697
698
14.9k
  std::string whilecycle_str = "while ";
699
14.9k
  whilecycle_str += ExpressionToString(whilecycle.condition());
700
14.9k
  whilecycle_str += " ";
701
14.9k
  whilecycle_str += DoBlockToStringCycleProtected(whilecycle.doblock());
702
703
14.9k
  GetContext().step_out();
704
14.9k
  return whilecycle_str;
705
14.9k
}
706
707
/**
708
 * RepeatCycle clause.
709
 */
710
PROTO_TOSTRING(RepeatCycle, repeatcycle)
711
71.9k
{
712
71.9k
  GetContext().step_in(Context::BlockType::kBreakable);
713
714
71.9k
  std::string repeatcycle_str = "repeat\n";
715
71.9k
  repeatcycle_str += BlockToStringCycleProtected(repeatcycle.block());
716
71.9k
  repeatcycle_str += "until ";
717
71.9k
  repeatcycle_str += ExpressionToString(repeatcycle.condition());
718
719
71.9k
  GetContext().step_out();
720
71.9k
  return repeatcycle_str;
721
71.9k
}
722
723
/**
724
 * IfStatement and nested types.
725
 */
726
PROTO_TOSTRING(IfStatement, statement)
727
10.4k
{
728
10.4k
  std::string statement_str = "if " +
729
10.4k
    ExpressionToString(statement.condition());
730
10.4k
  statement_str += " then\n\t" + BlockToString(statement.first());
731
732
14.8k
  for (int i = 0; i < statement.clauses_size(); ++i)
733
4.44k
    statement_str += ElseIfBlockToString(statement.clauses(i));
734
735
10.4k
  if (statement.has_last())
736
3.46k
    statement_str += "else\n\t" + BlockToString(statement.last());
737
738
10.4k
  statement_str += "end\n";
739
10.4k
  return statement_str;
740
10.4k
}
741
742
NESTED_PROTO_TOSTRING(ElseIfBlock, elseifblock, IfStatement)
743
4.44k
{
744
4.44k
  std::string elseifblock_str = "elseif ";
745
4.44k
  elseifblock_str += ExpressionToString(elseifblock.condition());
746
4.44k
  elseifblock_str += " then\n\t";
747
4.44k
  elseifblock_str += BlockToString(elseifblock.block());
748
4.44k
  return elseifblock_str;
749
4.44k
}
750
751
/**
752
 * ForCycleName clause.
753
 * TODO: In 'for i = start, stop, step' construction start, stop, step
754
 * should be numbers. So results of the corresponding expressions
755
 * should be number.
756
 */
757
PROTO_TOSTRING(ForCycleName, forcyclename)
758
8.46k
{
759
8.46k
  GetContext().step_in(Context::BlockType::kBreakable);
760
761
8.46k
  std::string forcyclename_str = "for ";
762
8.46k
  forcyclename_str += NameToString(forcyclename.name());
763
8.46k
  forcyclename_str += " = ";
764
8.46k
  forcyclename_str += NumberWrappedExpressionToString(
765
8.46k
    forcyclename.startexp());
766
8.46k
  forcyclename_str += ", ";
767
8.46k
  forcyclename_str += NumberWrappedExpressionToString(
768
8.46k
    forcyclename.stopexp());
769
770
8.46k
  if (forcyclename.has_stepexp())
771
4.51k
    forcyclename_str += ", " + NumberWrappedExpressionToString(
772
4.51k
      forcyclename.stepexp());
773
774
8.46k
  forcyclename_str += " ";
775
8.46k
  forcyclename_str += DoBlockToStringCycleProtected(
776
8.46k
    forcyclename.doblock());
777
778
8.46k
  GetContext().step_out();
779
8.46k
  return forcyclename_str;
780
8.46k
}
781
782
/**
783
 * ForCycleList clause.
784
 */
785
PROTO_TOSTRING(ForCycleList, forcyclelist)
786
21.7k
{
787
21.7k
  GetContext().step_in(Context::BlockType::kBreakable);
788
789
21.7k
  std::string forcyclelist_str = "for ";
790
21.7k
  forcyclelist_str += NameListToString(forcyclelist.names());
791
21.7k
  forcyclelist_str += " in ";
792
21.7k
  forcyclelist_str += ExpressionListToString(forcyclelist.expressions());
793
21.7k
  forcyclelist_str += " ";
794
21.7k
  forcyclelist_str += DoBlockToStringCycleProtected(
795
21.7k
    forcyclelist.doblock());
796
797
21.7k
  GetContext().step_out();
798
21.7k
  return forcyclelist_str;
799
21.7k
}
800
801
/**
802
 * Function and nested types.
803
 */
804
PROTO_TOSTRING(Function, func)
805
7.16k
{
806
7.16k
  GetContext().step_in(GetFuncBodyType(func.body()));
807
808
7.16k
  std::string func_str = "function ";
809
7.16k
  func_str += FuncNameToString(func.name());
810
7.16k
  func_str += FuncBodyToStringReqProtected(func.body());
811
812
7.16k
  GetContext().step_out();
813
7.16k
  return func_str;
814
7.16k
}
815
816
NESTED_PROTO_TOSTRING(FuncName, funcname, Function)
817
7.16k
{
818
7.16k
  std::string funcname_str = NameToString(funcname.firstname());
819
820
8.68k
  for (int i = 0; i < funcname.names_size(); ++i)
821
1.52k
    funcname_str += "." + NameToString(funcname.names(i));
822
823
7.16k
  if (funcname.has_lastname())
824
803
    funcname_str += ":" + NameToString(funcname.lastname());
825
826
7.16k
  return funcname_str;
827
7.16k
}
828
829
PROTO_TOSTRING(NameList, namelist)
830
38.2k
{
831
38.2k
  std::string namelist_str = NameToString(namelist.firstname());
832
58.6k
  for (int i = 0; i < namelist.names_size(); ++i)
833
20.4k
    namelist_str += ", " + NameToString(namelist.names(i));
834
38.2k
  return namelist_str;
835
38.2k
}
836
837
NESTED_PROTO_TOSTRING(NameListWithEllipsis, namelist, FuncBody)
838
9.92k
{
839
9.92k
  std::string namelist_str = NameListToString(namelist.namelist());
840
9.92k
  if (namelist.has_ellipsis())
841
1.36k
    namelist_str += ", ...";
842
9.92k
  return namelist_str;
843
9.92k
}
844
845
NESTED_PROTO_TOSTRING(ParList, parlist, FuncBody)
846
11.8k
{
847
11.8k
  using ParListType = FuncBody::ParList::ParlistOneofCase;
848
11.8k
  switch (parlist.parlist_oneof_case()) {
849
2.15k
  case ParListType::kNamelist:
850
2.15k
    return NameListWithEllipsisToString(parlist.namelist());
851
1.90k
  case ParListType::kEllipsis:
852
1.90k
    return "...";
853
7.77k
  default:
854
    /* Chosen as default in order to decrease number of ellipses. */
855
7.77k
    return NameListWithEllipsisToString(parlist.namelist());
856
11.8k
  }
857
11.8k
}
858
859
/**
860
 * LocalFunc clause.
861
 */
862
PROTO_TOSTRING(LocalFunc, localfunc)
863
14.1k
{
864
14.1k
  GetContext().step_in(GetFuncBodyType(localfunc.funcbody()));
865
866
14.1k
  std::string localfunc_str = "local function ";
867
14.1k
  localfunc_str += NameToString(localfunc.name());
868
14.1k
  localfunc_str += " ";
869
14.1k
  localfunc_str += FuncBodyToStringReqProtected(localfunc.funcbody());
870
871
14.1k
  GetContext().step_out();
872
14.1k
  return localfunc_str;
873
14.1k
}
874
875
/**
876
 * LocalNames clause.
877
 */
878
PROTO_TOSTRING(LocalNames, localnames)
879
6.52k
{
880
6.52k
  std::string localnames_str = "local ";
881
6.52k
  localnames_str += NameListToString(localnames.namelist());
882
883
6.52k
  if (localnames.has_explist())
884
3.02k
    localnames_str += " = " + ExpressionListToString(
885
3.02k
      localnames.explist());
886
6.52k
  return localnames_str;
887
6.52k
}
888
889
/**
890
 * Expressions and variables.
891
 */
892
893
/**
894
 * Expressions clauses.
895
 */
896
PROTO_TOSTRING(ExpressionList, explist)
897
136k
{
898
136k
  std::string explist_str;
899
206k
  for (int i = 0; i < explist.expressions_size(); ++i)
900
70.6k
    explist_str += ExpressionToString(explist.expressions(i)) +
901
70.6k
        ", ";
902
136k
  explist_str += ExpressionToString(explist.explast()) + " ";
903
136k
  return explist_str;
904
136k
}
905
906
PROTO_TOSTRING(OptionalExpressionList, explist)
907
8.76k
{
908
8.76k
  if (explist.has_explist())
909
8.09k
    return ExpressionListToString(explist.explist());
910
674
  return "";
911
8.76k
}
912
913
PROTO_TOSTRING(PrefixExpression, prefixexp)
914
161k
{
915
161k
  using PrefExprType = PrefixExpression::PrefixOneofCase;
916
161k
  switch (prefixexp.prefix_oneof_case()) {
917
18.1k
  case PrefExprType::kVar:
918
18.1k
    return VariableToString(prefixexp.var());
919
18.9k
  case PrefExprType::kFunctioncall:
920
18.9k
    return FunctionCallToString(prefixexp.functioncall());
921
10.4k
  case PrefExprType::kExp:
922
10.4k
    return "(" + ExpressionToString(prefixexp.exp()) + ")";
923
114k
  default:
924
    /*
925
     * Can be generated too nested expressions with other options,
926
     * though they can be enabled for more variable fuzzing.
927
     */
928
114k
    return VariableToString(prefixexp.var());
929
161k
  }
930
161k
}
931
932
/**
933
 * Variable and nested types.
934
 */
935
PROTO_TOSTRING(Variable, var)
936
257k
{
937
257k
  using VarType = Variable::VarOneofCase;
938
257k
  switch (var.var_oneof_case()) {
939
19.2k
  case VarType::kName:
940
19.2k
    return NameToString(var.name());
941
9.08k
  case VarType::kIndexexpr:
942
9.08k
    return IndexWithExpressionToString(var.indexexpr());
943
6.35k
  case VarType::kIndexname:
944
6.35k
    return IndexWithNameToString(var.indexname());
945
222k
  default:
946
    /*
947
     * Can be generated too nested expressions with other options,
948
     * though they can be enabled for more variable fuzzing.
949
     */
950
222k
    return NameToString(var.name());
951
257k
  }
952
257k
}
953
954
NESTED_PROTO_TOSTRING(IndexWithExpression, indexexpr, Variable)
955
9.08k
{
956
9.08k
  std::string indexexpr_str = PrefixExpressionToString(
957
9.08k
    indexexpr.prefixexp());
958
9.08k
  indexexpr_str += "[" + ExpressionToString(indexexpr.exp()) + "]";
959
9.08k
  return indexexpr_str;
960
9.08k
}
961
962
NESTED_PROTO_TOSTRING(IndexWithName, indexname, Variable)
963
6.35k
{
964
6.35k
  std::string indexname_str = PrefixExpressionToString(
965
6.35k
    indexname.prefixexp());
966
6.35k
  std::string idx_str = ConvertToStringDefault(indexname.name(), true);
967
  /* Prevent using reserved keywords as indices. */
968
6.35k
  if (KReservedLuaKeywords.find(idx_str) != KReservedLuaKeywords.end()) {
969
56
    idx_str += "_1";
970
56
  }
971
6.35k
  indexname_str += "." + idx_str;
972
6.35k
  return indexname_str;
973
6.35k
}
974
975
/**
976
 * Expression and nested types.
977
 */
978
PROTO_TOSTRING(Expression, expr)
979
602k
{
980
602k
  using ExprType = Expression::ExprOneofCase;
981
602k
  switch (expr.expr_oneof_case()) {
982
15.7k
  case ExprType::kNil:
983
15.7k
    return "nil";
984
8.24k
  case ExprType::kFalse:
985
8.24k
    return "false";
986
8.08k
  case ExprType::kTrue:
987
8.08k
    return "true";
988
32.6k
  case ExprType::kNumber: {
989
    /* Clamp number between given boundaries. */
990
32.6k
    double number = clamp(expr.number(), kMaxNumber, kMinNumber);
991
32.6k
    return std::to_string(number);
992
0
  }
993
41.0k
  case ExprType::kStr:
994
41.0k
    return "'" + ConvertToStringDefault(expr.str()) + "'";
995
8.30k
  case ExprType::kEllipsis:
996
8.30k
    if (GetContext().vararg_is_possible()) {
997
7.25k
      return " ... ";
998
7.25k
    } else {
999
1.04k
      return " nil";
1000
1.04k
    }
1001
26.6k
  case ExprType::kFunction:
1002
26.6k
    return AnonFuncToString(expr.function());
1003
52.5k
  case ExprType::kPrefixexp:
1004
52.5k
    return PrefixExpressionToString(expr.prefixexp());
1005
16.9k
  case ExprType::kTableconstructor:
1006
16.9k
    return TableConstructorToString(expr.tableconstructor());
1007
102k
  case ExprType::kBinary:
1008
102k
    return ExpBinaryOpExpToString(expr.binary());
1009
13.0k
  case ExprType::kUnary:
1010
13.0k
    return UnaryOpExpToString(expr.unary());
1011
276k
  default:
1012
    /**
1013
     * Arbitrary choice.
1014
     * TODO: Choose "more interesting" defaults.
1015
     */
1016
276k
    return "'" + ConvertToStringDefault(expr.str()) + "'";
1017
602k
  }
1018
602k
}
1019
1020
NESTED_PROTO_TOSTRING(AnonFunc, func, Expression)
1021
26.6k
{
1022
26.6k
  GetContext().step_in(GetFuncBodyType(func.body()));
1023
1024
26.6k
  std::string retval = "function ";
1025
26.6k
  retval += FuncBodyToStringReqProtected(func.body());
1026
1027
26.6k
  GetContext().step_out();
1028
26.6k
  return retval;
1029
26.6k
}
1030
1031
NESTED_PROTO_TOSTRING(ExpBinaryOpExp, binary, Expression)
1032
102k
{
1033
102k
  std::string leftexp_str = ExpressionToString(binary.leftexp());
1034
102k
  std::string binop_str = BinaryOperatorToString(binary.binop());
1035
102k
  std::string rightexp_str = ExpressionToString(binary.rightexp());
1036
1037
102k
  std::string binary_str;
1038
102k
  if (binop_str == "<" ||
1039
102k
      binop_str == ">" ||
1040
102k
      binop_str == "<=" ||
1041
102k
      binop_str == ">=") {
1042
3.62k
    binary_str = kBinOpWrapperName;
1043
3.62k
    binary_str += "(" + leftexp_str;
1044
3.62k
    binary_str += ", '" + binop_str + "', ";
1045
3.62k
    binary_str += rightexp_str + ")";
1046
3.62k
    return binary_str;
1047
3.62k
  }
1048
1049
98.9k
  binary_str = leftexp_str;
1050
98.9k
  binary_str += " " + binop_str + " ";
1051
98.9k
  binary_str += rightexp_str;
1052
1053
98.9k
  return binary_str;
1054
102k
}
1055
1056
NESTED_PROTO_TOSTRING(UnaryOpExp, unary, Expression)
1057
13.0k
{
1058
13.0k
  std::string unary_str = UnaryOperatorToString(unary.unop());
1059
  /*
1060
   * Add a whitespace before an expression with unary minus,
1061
   * otherwise double hyphen comments the following code
1062
   * and it breaks generated programs syntactically.
1063
   */
1064
13.0k
  unary_str += " " + ExpressionToString(unary.exp());
1065
13.0k
  return unary_str;
1066
13.0k
}
1067
1068
/**
1069
 * Tables and fields.
1070
 */
1071
PROTO_TOSTRING(TableConstructor, table)
1072
94.4k
{
1073
94.4k
  std::string table_str = " (setmetatable({ ";
1074
94.4k
  if (table.has_fieldlist())
1075
11.9k
    table_str += FieldListToString(table.fieldlist());
1076
94.4k
  table_str += " }, table_mt))()";
1077
94.4k
  return table_str;
1078
94.4k
}
1079
1080
PROTO_TOSTRING(FieldList, fieldlist)
1081
11.9k
{
1082
11.9k
  std::string fieldlist_str = FieldToString(fieldlist.firstfield());
1083
28.0k
  for (int i = 0; i < fieldlist.fields_size(); ++i)
1084
16.1k
    fieldlist_str += FieldWithFieldSepToString(fieldlist.fields(i));
1085
11.9k
  if (fieldlist.has_lastsep())
1086
3.19k
    fieldlist_str += FieldSepToString(fieldlist.lastsep());
1087
11.9k
  return fieldlist_str;
1088
11.9k
}
1089
1090
NESTED_PROTO_TOSTRING(FieldWithFieldSep, field, FieldList)
1091
16.1k
{
1092
16.1k
  std::string field_str = FieldSepToString(field.sep());
1093
16.1k
  field_str += " " + FieldToString(field.field());
1094
16.1k
  return field_str;
1095
16.1k
}
1096
1097
/**
1098
 * Field and nested types.
1099
 */
1100
PROTO_TOSTRING(Field, field)
1101
28.0k
{
1102
28.0k
  using FieldType = Field::FieldOneofCase;
1103
28.0k
  switch (field.field_oneof_case()) {
1104
6.44k
  case FieldType::kExprassign:
1105
6.44k
    return ExpressionAssignmentToString(field.exprassign());
1106
1.30k
  case FieldType::kNamedassign:
1107
1.30k
    return NameAssignmentToString(field.namedassign());
1108
7.44k
  case FieldType::kExpression:
1109
7.44k
    return ExpressionToString(field.expression());
1110
12.8k
  default:
1111
    /* More common case of using fields. */
1112
12.8k
    return NameAssignmentToString(field.namedassign());
1113
28.0k
  }
1114
28.0k
}
1115
1116
NESTED_PROTO_TOSTRING(ExpressionAssignment, assignment, Field)
1117
6.44k
{
1118
  /* Prevent error 'table index is nil' and 'table index is NaN'. */
1119
6.44k
  std::string assignment_str = "[ " +
1120
6.44k
    AllowedIndexExpressionToString(assignment.key()) + " ]";
1121
6.44k
  assignment_str += " = " + ExpressionToString(assignment.value());
1122
6.44k
  return assignment_str;
1123
6.44k
}
1124
1125
NESTED_PROTO_TOSTRING(NameAssignment, assignment, Field)
1126
14.1k
{
1127
14.1k
  std::string assignment_str = NameToString(assignment.name());
1128
14.1k
  assignment_str += " = " + ExpressionToString(assignment.value());
1129
14.1k
  return assignment_str;
1130
14.1k
}
1131
1132
PROTO_TOSTRING(FieldSep, sep)
1133
19.3k
{
1134
19.3k
  using FieldSepType = FieldSep::SepOneofCase;
1135
19.3k
  switch (sep.sep_oneof_case()) {
1136
5.46k
  case FieldSepType::kComma:
1137
5.46k
    return ",";
1138
2.54k
  case FieldSepType::kSemicolon:
1139
2.54k
    return ";";
1140
11.3k
  default:
1141
11.3k
    return ",";
1142
19.3k
  }
1143
19.3k
}
1144
1145
/**
1146
 * Operators.
1147
 */
1148
PROTO_TOSTRING(BinaryOperator, op)
1149
102k
{
1150
102k
  using BinopType = BinaryOperator::BinaryOneofCase;
1151
102k
  switch (op.binary_oneof_case()) {
1152
7.35k
  case BinopType::kAdd:
1153
7.35k
    return "+";
1154
2.59k
  case BinopType::kSub:
1155
2.59k
    return "-";
1156
13.3k
  case BinopType::kMult:
1157
13.3k
    return "*";
1158
4.73k
  case BinopType::kDiv:
1159
4.73k
    return "/";
1160
#if LUA_VERSION_NUM >= 503
1161
  case BinopType::kIDiv:
1162
    return "//";
1163
#endif
1164
2.52k
  case BinopType::kExp:
1165
2.52k
    return "^";
1166
3.20k
  case BinopType::kMod:
1167
3.20k
    return "%";
1168
1169
35.4k
  case BinopType::kConcat:
1170
35.4k
    return "..";
1171
1172
1.51k
  case BinopType::kLess:
1173
1.51k
    return "<";
1174
690
  case BinopType::kLessEqual:
1175
690
    return "<=";
1176
833
  case BinopType::kGreater:
1177
833
    return ">";
1178
589
  case BinopType::kGreaterEqual:
1179
589
    return ">=";
1180
679
  case BinopType::kEqual:
1181
679
    return "==";
1182
680
  case BinopType::kNotEqual:
1183
680
    return "~=";
1184
1.18k
  case BinopType::kAnd:
1185
1.18k
    return "and";
1186
5.03k
  case BinopType::kOr:
1187
5.03k
    return "or";
1188
1189
#if LUA_VERSION_NUM >= 503
1190
  case BinopType::kBAnd:
1191
    return "&";
1192
  case BinopType::kBOr:
1193
    return "|";
1194
  case BinopType::kBXor:
1195
    return "~";
1196
  case BinopType::kBShl:
1197
    return "<<";
1198
  case BinopType::kBShr:
1199
    return ">>";
1200
#endif
1201
22.2k
  default:
1202
    /* Works in most cases. */
1203
22.2k
    return "==";
1204
102k
  }
1205
102k
}
1206
1207
PROTO_TOSTRING(UnaryOperator, op)
1208
13.0k
{
1209
13.0k
  using UnaryopType = UnaryOperator::UnaryOneofCase;
1210
13.0k
  switch (op.unary_oneof_case()) {
1211
3.45k
  case UnaryopType::kNegate:
1212
3.45k
    return "-";
1213
1.04k
  case UnaryopType::kNot:
1214
1.04k
    return "not ";
1215
2.63k
  case UnaryopType::kLength:
1216
2.63k
    return "#";
1217
#if LUA_VERSION_NUM >= 503
1218
  case UnaryopType::kBNot:
1219
    return "~";
1220
#endif
1221
5.95k
  default:
1222
    /* Works in most cases. */
1223
5.95k
    return "not ";
1224
13.0k
  }
1225
13.0k
}
1226
1227
/**
1228
 * Identifier (Name).
1229
 */
1230
PROTO_TOSTRING(Name, name)
1231
421k
{
1232
421k
  std::string ident = ConvertToStringDefault(name.name(), true);
1233
  /* Prevent using reserved keywords as identifiers. */
1234
421k
  if (KReservedLuaKeywords.find(ident) != KReservedLuaKeywords.end()) {
1235
240
    ident += "_1";
1236
240
  }
1237
  /* Identifier has default name, add an index. */
1238
421k
  if (!ident.compare(kDefaultIdent)) {
1239
384k
    ident += std::to_string(name.num() % kMaxIdentifiers);
1240
384k
  }
1241
421k
  return ident;
1242
421k
}
1243
1244
} /* namespace */
1245
1246
std::string
1247
MainBlockToString(const Block &block)
1248
18.6k
{
1249
18.6k
  GetCounterIdProvider().clean();
1250
1251
18.6k
  std::string block_str = BlockToString(block);
1252
18.6k
  std::string retval = preamble_lua;
1253
1254
183k
  for (size_t i = 0; i < GetCounterIdProvider().count(); ++i) {
1255
165k
    retval += GetCounterName(i);
1256
165k
    retval += " = 0\n";
1257
165k
  }
1258
18.6k
  retval += block_str;
1259
1260
18.6k
  return retval;
1261
18.6k
}
1262
1263
} /* namespace luajit_fuzzer */