aboutsummaryrefslogtreecommitdiff
path: root/gcc/rust/ast/rust-fmt.h
blob: e59bed3e9d29a17e4eebce45aca434f192e98ded (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Copyright (C) 2023-2025 Free Software Foundation, Inc.

// This file is part of GCC.

// GCC is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 3, or (at your option) any later
// version.

// GCC is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
// for more details.

// You should have received a copy of the GNU General Public License
// along with GCC; see the file COPYING3.  If not see
// <http://www.gnu.org/licenses/>.

#ifndef RUST_FMT_H
#define RUST_FMT_H

#include "rust-system.h"
#include "optional.h"

namespace Rust {
namespace Fmt {

namespace ffi {

extern "C" {

unsigned char *rust_ffi_alloc (size_t count, size_t elem_size, size_t align);

void rust_ffi_dealloc (unsigned char *data, size_t count, size_t elem_size,
		       size_t align);

} // extern "C"

template <typename T> class FFIVec
{
  T *data;
  size_t len;
  size_t cap;

public:
  FFIVec () : data ((T *) alignof (T)), len (0), cap (0) {}

  FFIVec (const FFIVec &) = delete;
  FFIVec &operator= (const FFIVec &) = delete;

  FFIVec (FFIVec &&other) : data (other.data), len (other.len), cap (other.cap)
  {
    other.data = (T *) alignof (T);
    other.len = 0;
    other.cap = 0;
  }

  FFIVec &operator= (FFIVec &&other)
  {
    this->~FFIVec ();
    new (this) FFIVec (std::move (other));
    return *this;
  }

  ~FFIVec ()
  {
    // T can't be zero-sized
    if (cap)
      rust_ffi_dealloc ((unsigned char *) data, cap, sizeof (T), alignof (T));
  }

  size_t size () const { return len; }

  const T &operator[] (size_t idx) const
  {
    rust_assert (idx <= len);
    return data[idx];
  }

  T *begin () { return data; }
  const T *begin () const { return data; }
  T *end () { return data + len; }
  const T *end () const { return data + len; }
};

// https://github.com/rust-lang/rfcs/blob/master/text/2195-really-tagged-unions.md
template <typename T,
	  typename =
	    typename std::enable_if<std::is_standard_layout<T>::value>::type>
class FFIOpt
{
public:
  template <typename U>
  FFIOpt (U &&val) : some{Some::KIND, std::forward<U> (val)}
  {}

  FFIOpt () : none{None::KIND} {}

  FFIOpt (const FFIOpt &other)
  {
    if (other.has_value ())
      new (&some) Some{Some::KIND, other.some.val};
    else
      new (&none) None{None::KIND};
  }

  FFIOpt (FFIOpt &&other)
  {
    if (other.has_value ())
      new (&some) Some{Some::KIND, std::move (other.some.val)};
    else
      new (&none) None{None::KIND};
  }

  ~FFIOpt ()
  {
    if (has_value ())
      some.~Some ();
    else
      none.~None ();
  }

  FFIOpt &operator= (const FFIOpt &other)
  {
    this->~FFIOpt ();
    new (this) FFIOpt (other);
    return *this;
  }

  FFIOpt &operator= (FFIOpt &&other)
  {
    this->~FFIOpt ();
    new (this) FFIOpt (std::move (other));
    return *this;
  }

  tl::optional<std::reference_wrapper<T>> get_opt ()
  {
    if (has_value ())
      return std::ref (some.val);
    else
      return tl::nullopt;
  }

  tl::optional<std::reference_wrapper<const T>> get_opt () const
  {
    if (has_value ())
      return std::ref (some.val);
    else
      return tl::nullopt;
  }

  bool has_value () const { return some.kind == Some::KIND; }

  operator bool () const { return has_value (); }

private:
  struct Some
  {
    static constexpr uint8_t KIND = 0;
    uint8_t kind;
    T val;
  };

  struct None
  {
    static constexpr uint8_t KIND = 1;
    uint8_t kind;
  };

  union
  {
    Some some;
    None none;
  };
};

struct RustHamster
{
  const char *ptr;
  size_t len;

  std::string to_string () const;

  explicit RustHamster (const std::string &str)
    : ptr (str.data ()), len (str.size ())
  {}
};

/// Enum of alignments which are supported.
enum class Alignment
{
  /// The value will be aligned to the left.
  AlignLeft,
  /// The value will be aligned to the right.
  AlignRight,
  /// The value will be aligned in the center.
  AlignCenter,
  /// The value will take on a default alignment.
  AlignUnknown,
};

/// Enum for the debug hex flags.
enum class DebugHex
{
  /// The `x` flag in `{:x?}`.
  Lower,
  /// The `X` flag in `{:X?}`.
  Upper,
};

/// Enum for the sign flags.
enum class Sign
{
  /// The `+` flag.
  Plus,
  /// The `-` flag.
  Minus,
};

/// Enum describing where an argument for a format can be located.
struct Position
{
  enum class Tag
  {
    /// The argument is implied to be located at an index
    ArgumentImplicitlyIs,
    /// The argument is located at a specific index given in the format,
    ArgumentIs,
    /// The argument has a name.
    ArgumentNamed,
  };

  struct ArgumentImplicitlyIs_Body
  {
    size_t _0;
  };

  struct ArgumentIs_Body
  {
    size_t _0;
  };

  struct ArgumentNamed_Body
  {
    RustHamster _0;
  };

  Tag tag;
  union
  {
    ArgumentImplicitlyIs_Body argument_implicitly_is;
    ArgumentIs_Body argument_is;
    ArgumentNamed_Body argument_named;
  };
};

/// Range inside of a `Span` used for diagnostics when we only have access to
/// relative positions.
struct InnerSpan
{
  size_t start;
  size_t end;
};

/// A count is used for the precision and width parameters of an integer, and
/// can reference either an argument or a literal integer.
struct Count
{
  enum class Tag
  {
    /// The count is specified explicitly.
    CountIs,
    /// The count is specified by the argument with the given name.
    CountIsName,
    /// The count is specified by the argument at the given index.
    CountIsParam,
    /// The count is specified by a star (like in `{:.*}`) that refers to the
    /// argument at the given index.
    CountIsStar,
    /// The count is implied and cannot be explicitly specified.
    CountImplied,
  };

  struct CountIs_Body
  {
    size_t _0;
  };

  struct CountIsName_Body
  {
    RustHamster _0;
    InnerSpan _1;
  };

  struct CountIsParam_Body
  {
    size_t _0;
  };

  struct CountIsStar_Body
  {
    size_t _0;
  };

  Tag tag;
  union
  {
    CountIs_Body count_is;
    CountIsName_Body count_is_name;
    CountIsParam_Body count_is_param;
    CountIsStar_Body count_is_star;
  };
};

/// Specification for the formatting of an argument in the format string.
struct FormatSpec
{
  /// Optionally specified character to fill alignment with.
  FFIOpt<uint32_t> fill;
  /// Span of the optionally specified fill character.
  FFIOpt<InnerSpan> fill_span;
  /// Optionally specified alignment.
  Alignment align;
  /// The `+` or `-` flag.
  FFIOpt<Sign> sign;
  /// The `#` flag.
  bool alternate;
  /// The `0` flag.
  bool zero_pad;
  /// The `x` or `X` flag. (Only for `Debug`.)
  FFIOpt<DebugHex> debug_hex;
  /// The integer precision to use.
  Count precision;
  /// The span of the precision formatting flag (for diagnostics).
  FFIOpt<InnerSpan> precision_span;
  /// The string width requested for the resulting format.
  Count width;
  /// The span of the width formatting flag (for diagnostics).
  FFIOpt<InnerSpan> width_span;
  /// The descriptor string representing the name of the format desired for
  /// this argument, this can be empty or any number of characters, although
  /// it is required to be one word.
  RustHamster ty;
  /// The span of the descriptor string (for diagnostics).
  FFIOpt<InnerSpan> ty_span;
};

/// Representation of an argument specification.
struct Argument
{
  /// Where to find this argument
  Position position;
  /// The span of the position indicator. Includes any whitespace in implicit
  /// positions (`{  }`).
  InnerSpan position_span;
  /// How to format the argument
  FormatSpec format;
};

/// A piece is a portion of the format string which represents the next part
/// to emit. These are emitted as a stream by the `Parser` class.
struct Piece
{
  enum class Tag
  {
    /// A literal string which should directly be emitted
    String,
    /// This describes that formatting should process the next argument (as
    /// specified inside) for emission.
    NextArgument,
  };

  struct String_Body
  {
    RustHamster _0;
  };

  struct NextArgument_Body
  {
    Argument _0;
  };

  Tag tag;
  union
  {
    String_Body string;
    NextArgument_Body next_argument;
  };
};

enum ParseMode
{
  Format = 0,
  InlineAsm,
};

extern "C" {

FFIVec<Piece> collect_pieces (RustHamster input, bool append_newline,
			      ParseMode parse_mode);

FFIVec<Piece> clone_pieces (const FFIVec<Piece> &);

} // extern "C"

} // namespace ffi

struct Pieces
{
  static Pieces collect (const std::string &to_parse, bool append_newline,
			 ffi::ParseMode parse_mode);

  const ffi::FFIVec<ffi::Piece> &get_pieces () const { return data->second; }

private:
  Pieces (std::string str, ffi::FFIVec<ffi::Piece> pieces)
    : data (
      std::make_shared<decltype (data)::element_type> (std::move (str),
						       std::move (pieces)))
  {}

  // makes copying simpler
  // also, we'd need to keep the parsed string in a shared_ptr anyways
  // since we store pointers into the parsed string
  std::shared_ptr<std::pair<std::string, ffi::FFIVec<ffi::Piece>>> data;
};

} // namespace Fmt
} // namespace Rust

#endif // !RUST_FMT_H