File: signature_checker.h

package info (click to toggle)
android-platform-tools 34.0.5-12
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 150,900 kB
  • sloc: cpp: 805,786; java: 293,500; ansic: 128,288; xml: 127,491; python: 41,481; sh: 14,245; javascript: 9,665; cs: 3,846; asm: 2,049; makefile: 1,917; yacc: 440; awk: 368; ruby: 183; sql: 140; perl: 88; lex: 67
file content (1441 lines) | stat: -rw-r--r-- 50,257 bytes parent folder | download | duplicates (2)
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/*
 * WARNING: Do not include and use these directly. Use jni_macros.h instead!
 * The "detail" namespace should be a strong hint not to depend on the internals,
 * which could change at any time.
 *
 * This implements the underlying mechanism for compile-time JNI signature/ctype checking
 * and inference.
 *
 * This file provides the constexpr basic blocks such as strings, arrays, vectors
 * as well as the JNI-specific parsing functionality.
 *
 * Everything is implemented via generic-style (templates without metaprogramming)
 * wherever possible. Traditional template metaprogramming is used sparingly.
 *
 * Everything in this file except ostream<< is constexpr.
 */

#pragma once

#include <iostream>     // std::ostream
#include <jni.h>        // jni typedefs, JniNativeMethod.
#include <type_traits>  // std::common_type, std::remove_cv

namespace nativehelper {
namespace detail {

// If CHECK evaluates to false then X_ASSERT will halt compilation.
//
// Asserts meant to be used only within constexpr context.
#if defined(JNI_SIGNATURE_CHECKER_DISABLE_ASSERTS)
# define X_ASSERT(CHECK) do { if ((false)) { (CHECK) ? void(0) : void(0); } } while (false)
#else
# define X_ASSERT(CHECK) \
    ( (CHECK) ? void(0) : jni_assertion_failure(#CHECK) )
#endif

// The runtime 'jni_assert' will never get called from a constexpr context;
// instead compilation will abort with a stack trace.
//
// Inspect the frame above this one to see the exact nature of the failure.
inline void jni_assertion_failure(const char* /*msg*/) __attribute__((noreturn));
inline void jni_assertion_failure(const char* /*msg*/) {
  std::terminate();
}

// An immutable constexpr string view, similar to std::string_view but for C++14.
// For a mutable string see instead ConstexprVector<char>.
//
// As it is a read-only view into a string, it is not guaranteed to be zero-terminated.
struct ConstexprStringView {
  // Implicit conversion from string literal:
  //     ConstexprStringView str = "hello_world";
  template<size_t N>
  constexpr ConstexprStringView(const char (& lit)[N])  // NOLINT: explicit.
      : _array(lit), _size(N - 1) {
    // Using an array of characters is not allowed because the inferred size would be wrong.
    // Use the other constructor instead for that.
    X_ASSERT(lit[N - 1] == '\0');
  }

  constexpr ConstexprStringView(const char* ptr, size_t size)
      : _array(ptr), _size(size) {
    // See the below constructor instead.
    X_ASSERT(ptr != nullptr);
  }

  // No-arg constructor: Create empty view.
  constexpr ConstexprStringView() : _array(""), _size(0u) {}

  constexpr size_t size() const {
    return _size;
  }

  constexpr bool empty() const {
    return size() == 0u;
  }

  constexpr char operator[](size_t i) const {
    X_ASSERT(i <= size());
    return _array[i];
  }

  // Create substring from this[start..start+len).
  constexpr ConstexprStringView substr(size_t start, size_t len) const {
    X_ASSERT(start <= size());
    X_ASSERT(len <= size() - start);

    return ConstexprStringView(&_array[start], len);
  }

  // Create maximum length substring that begins at 'start'.
  constexpr ConstexprStringView substr(size_t start) const {
    X_ASSERT(start <= size());
    return substr(start, size() - start);
  }

  using const_iterator = const char*;

  constexpr const_iterator begin() const {
    return &_array[0];
  }

  constexpr const_iterator end() const {
    return &_array[size()];
  }

 private:
  const char* _array;  // Never-null for simplicity.
  size_t _size;
};

constexpr bool
operator==(const ConstexprStringView& lhs, const ConstexprStringView& rhs) {
  if (lhs.size() != rhs.size()) {
    return false;
  }
  for (size_t i = 0; i < lhs.size(); ++i) {
    if (lhs[i] != rhs[i]) {
      return false;
    }
  }
  return true;
}

constexpr bool
operator!=(const ConstexprStringView& lhs, const ConstexprStringView& rhs) {
  return !(lhs == rhs);
}

inline std::ostream& operator<<(std::ostream& os, const ConstexprStringView& str) {
  for (char c : str) {
    os << c;
  }
  return os;
}

constexpr bool IsValidJniDescriptorStart(char shorty) {
  constexpr char kValidJniStarts[] =
      {'V', 'Z', 'B', 'C', 'S', 'I', 'J', 'F', 'D', 'L', '[', '(', ')'};

  for (char c : kValidJniStarts) {
    if (c == shorty) {
      return true;
    }
  }

  return false;
}

// A constexpr "vector" that supports storing a variable amount of Ts
// in an array-like interface.
//
// An up-front kMaxSize must be given since constexpr does not support
// dynamic allocations.
template<typename T, size_t kMaxSize>
struct ConstexprVector {
 public:
  constexpr explicit ConstexprVector() : _size(0u), _array{} {
  }

 private:
  // Custom iterator to support ptr-one-past-end into the union array without
  // undefined behavior.
  template<typename Elem>
  struct VectorIterator {
    Elem* ptr;

    constexpr VectorIterator& operator++() {
      ++ptr;
      return *this;
    }

    constexpr VectorIterator operator++(int) const {
      VectorIterator tmp(*this);
      ++tmp;
      return tmp;
    }

    constexpr /*T&*/ auto& operator*() {
      // Use 'auto' here since using 'T' is incorrect with const_iterator.
      return ptr->_value;
    }

    constexpr const /*T&*/ auto& operator*() const {
      // Use 'auto' here for consistency with above.
      return ptr->_value;
    }

    constexpr bool operator==(const VectorIterator& other) const {
      return ptr == other.ptr;
    }

    constexpr bool operator!=(const VectorIterator& other) const {
      return !(*this == other);
    }
  };

  // Do not require that T is default-constructible by using a union.
  struct MaybeElement {
    union {
      T _value;
    };
  };

 public:
  using iterator = VectorIterator<MaybeElement>;
  using const_iterator = VectorIterator<const MaybeElement>;

  constexpr iterator begin() {
    return {&_array[0]};
  }

  constexpr iterator end() {
    return {&_array[size()]};
  }

  constexpr const_iterator begin() const {
    return {&_array[0]};
  }

  constexpr const_iterator end() const {
    return {&_array[size()]};
  }

  constexpr void push_back(const T& value) {
    X_ASSERT(_size + 1 <= kMaxSize);

    _array[_size]._value = value;
    _size++;
  }

  // A pop operation could also be added since constexpr T's
  // have default destructors, it would just be _size--.
  // We do not need a pop() here though.

  constexpr const T& operator[](size_t i) const {
    return _array[i]._value;
  }

  constexpr T& operator[](size_t i) {
    return _array[i]._value;
  }

  constexpr size_t size() const {
    return _size;
  }
 private:

  size_t _size;
  MaybeElement _array[kMaxSize];
};

// Parsed and validated "long" form of a single JNI descriptor.
// e.g. one of "J", "Ljava/lang/Object;" etc.
struct JniDescriptorNode {
  ConstexprStringView longy;

  constexpr JniDescriptorNode(ConstexprStringView longy) : longy(longy) {  // NOLINT(google-explicit-constructor)
    X_ASSERT(!longy.empty());
  }
  constexpr JniDescriptorNode() : longy() {}

  constexpr char shorty() {
    // Must be initialized with the non-default constructor.
    X_ASSERT(!longy.empty());
    return longy[0];
  }
};

inline std::ostream& operator<<(std::ostream& os, const JniDescriptorNode& node) {
  os << node.longy;
  return os;
}

// Equivalent of C++17 std::optional.
//
// An optional is essentially a type safe
//    union {
//      void Nothing,
//      T    Some;
//    };
//
template<typename T>
struct ConstexprOptional {
  // Create a default optional with no value.
  constexpr ConstexprOptional() : _has_value(false), _nothing() {
  }

  // Create an optional with a value.
  constexpr ConstexprOptional(const T& value)  // NOLINT(google-explicit-constructor)
      : _has_value(true), _value(value) {
  }

  constexpr explicit operator bool() const {
    return _has_value;
  }

  constexpr bool has_value() const {
    return _has_value;
  }

  constexpr const T& value() const {
    X_ASSERT(has_value());
    return _value;
  }

  constexpr const T* operator->() const {
    return &(value());
  }

  constexpr const T& operator*() const {
    return value();
  }

 private:
  bool _has_value;
  // The "Nothing" is likely unnecessary but improves readability.
  struct Nothing {};
  union {
    Nothing _nothing;
    T _value;
  };
};

template<typename T>
constexpr bool
operator==(const ConstexprOptional<T>& lhs, const ConstexprOptional<T>& rhs) {
  if (lhs && rhs) {
    return lhs.value() == rhs.value();
  }
  return lhs.has_value() == rhs.has_value();
}

template<typename T>
constexpr bool
operator!=(const ConstexprOptional<T>& lhs, const ConstexprOptional<T>& rhs) {
  return !(lhs == rhs);
}

template<typename T>
inline std::ostream& operator<<(std::ostream& os, const ConstexprOptional<T>& val) {
  if (val) {
    os << val.value();
  }
  return os;
}

// Equivalent of std::nullopt
// Allows implicit conversion to any empty ConstexprOptional<T>.
// Mostly useful for macros that need to return an empty constexpr optional.
struct NullConstexprOptional {
  template<typename T>
  constexpr operator ConstexprOptional<T>() const {  // NOLINT(google-explicit-constructor)
    return ConstexprOptional<T>();
  }
};

inline std::ostream& operator<<(std::ostream& os, NullConstexprOptional) {
  return os;
}

#if !defined(PARSE_FAILURES_NONFATAL)
// Unfortunately we cannot have custom messages here, as it just prints a stack trace with the
// macros expanded. This is at least more flexible than static_assert which requires a string
// literal.
// NOTE: The message string literal must be on same line as the macro to be seen during a
// compilation error.
#define PARSE_FAILURE(msg) X_ASSERT(! #msg)
#define PARSE_ASSERT_MSG(cond, msg) X_ASSERT(#msg && (cond))
#define PARSE_ASSERT(cond) X_ASSERT(cond)
#else
#define PARSE_FAILURE(msg) return NullConstexprOptional{};
#define PARSE_ASSERT_MSG(cond, msg) if (!(cond)) { PARSE_FAILURE(msg); }
#define PARSE_ASSERT(cond) if (!(cond)) { PARSE_FAILURE(""); }
#endif

// This is a placeholder function and should not be called directly.
constexpr void ParseFailure(const char* msg) {
  (void) msg;  // intentionally no-op.
}

// Temporary parse data when parsing a function descriptor.
struct ParseTypeDescriptorResult {
  // A single argument descriptor, e.g. "V" or "Ljava/lang/Object;"
  ConstexprStringView token;
  // The remainder of the function descriptor yet to be parsed.
  ConstexprStringView remainder;

  constexpr bool has_token() const {
    return token.size() > 0u;
  }

  constexpr bool has_remainder() const {
    return remainder.size() > 0u;
  }

  constexpr JniDescriptorNode as_node() const {
    X_ASSERT(has_token());
    return {token};
  }
};

// Parse a single type descriptor out of a function type descriptor substring,
// and return the token and the remainder string.
//
// If parsing fails (i.e. illegal syntax), then:
//    parses are fatal -> assertion is triggered (default behavior),
//    parses are nonfatal -> returns nullopt (test behavior).
constexpr ConstexprOptional<ParseTypeDescriptorResult>
ParseSingleTypeDescriptor(ConstexprStringView single_type,
                          bool allow_void = false) {
  constexpr NullConstexprOptional kUnreachable = {};

  // Nothing else left.
  if (single_type.size() == 0) {
    return ParseTypeDescriptorResult{};
  }

  ConstexprStringView token;
  ConstexprStringView remainder = single_type.substr(/*start*/1u);

  char c = single_type[0];
  PARSE_ASSERT(IsValidJniDescriptorStart(c));

  enum State {
    kSingleCharacter,
    kArray,
    kObject
  };

  State state = kSingleCharacter;

  // Parse the first character to figure out if we should parse the rest.
  switch (c) {
    case '!': {
      constexpr bool fast_jni_is_deprecated = false;
      PARSE_ASSERT(fast_jni_is_deprecated);
      break;
    }
    case 'V':
      if (!allow_void) {
        constexpr bool void_type_descriptor_only_allowed_in_return_type = false;
        PARSE_ASSERT(void_type_descriptor_only_allowed_in_return_type);
      }
      [[clang::fallthrough]];
    case 'Z':
    case 'B':
    case 'C':
    case 'S':
    case 'I':
    case 'J':
    case 'F':
    case 'D':
      token = single_type.substr(/*start*/0u, /*len*/1u);
      break;
    case 'L':
      state = kObject;
      break;
    case '[':
      state = kArray;
      break;
    default: {
      // See JNI Chapter 3: Type Signatures.
      PARSE_FAILURE("Expected a valid type descriptor character.");
      return kUnreachable;
    }
  }

  // Possibly parse an arbitary-long remainder substring.
  switch (state) {
    case kSingleCharacter:
      return {{token, remainder}};
    case kArray: {
      // Recursively parse the array component, as it's just any non-void type descriptor.
      ConstexprOptional<ParseTypeDescriptorResult>
          maybe_res = ParseSingleTypeDescriptor(remainder, /*allow_void*/false);
      PARSE_ASSERT(maybe_res);  // Downstream parsing has asserted, bail out.

      ParseTypeDescriptorResult res = maybe_res.value();

      // Reject illegal array type descriptors such as "]".
      PARSE_ASSERT_MSG(res.has_token(), "All array types must follow by their component type (e.g. ']I', ']]Z', etc. ");

      token = single_type.substr(/*start*/0u, res.token.size() + 1u);

      return {{token, res.remainder}};
    }
    case kObject: {
      // Parse the fully qualified class, e.g. Lfoo/bar/baz;
      // Note checking that each part of the class name is a valid class identifier
      // is too complicated (JLS 3.8).
      // This simple check simply scans until the next ';'.
      bool found_semicolon = false;
      size_t semicolon_len = 0;
      for (size_t i = 0; i < single_type.size(); ++i) {
        switch (single_type[i]) {
          case ')':
          case '(':
          case '[':
            PARSE_FAILURE("Object identifiers cannot have ()[ in them.");
            break;
        }
        if (single_type[i] == ';') {
          semicolon_len = i + 1;
          found_semicolon = true;
          break;
        }
      }

      PARSE_ASSERT(found_semicolon);

      token = single_type.substr(/*start*/0u, semicolon_len);
      remainder = single_type.substr(/*start*/semicolon_len);

      bool class_name_is_empty = token.size() <= 2u;  // e.g. "L;"
      PARSE_ASSERT(!class_name_is_empty);

      return {{token, remainder}};
    }
    default:
      X_ASSERT(false);
  }

  X_ASSERT(false);
  return kUnreachable;
}

// Abstract data type to represent container for Ret(Args,...).
template<typename T, size_t kMaxSize>
struct FunctionSignatureDescriptor {
  ConstexprVector<T, kMaxSize> args;
  T ret;

  static constexpr size_t max_size = kMaxSize;
};


template<typename T, size_t kMaxSize>
inline std::ostream& operator<<(
    std::ostream& os,
    const FunctionSignatureDescriptor<T, kMaxSize>& signature) {
  size_t count = 0;
  os << "args={";
  for (auto& arg : signature.args) {
    os << arg;

    if (count != signature.args.size() - 1) {
      os << ",";
    }

    ++count;
  }
  os << "}, ret=";
  os << signature.ret;
  return os;
}

// Ret(Args...) of JniDescriptorNode.
template<size_t kMaxSize>
using JniSignatureDescriptor = FunctionSignatureDescriptor<JniDescriptorNode,
                                                           kMaxSize>;

// Parse a JNI function signature descriptor into a JniSignatureDescriptor.
//
// If parsing fails (i.e. illegal syntax), then:
//    parses are fatal -> assertion is triggered (default behavior),
//    parses are nonfatal -> returns nullopt (test behavior).
template<size_t kMaxSize>
constexpr ConstexprOptional<JniSignatureDescriptor<kMaxSize>>
ParseSignatureAsList(ConstexprStringView signature) {
  // The list of JNI descriptors cannot possibly exceed the number of characters
  // in the JNI string literal. We leverage this to give an upper bound of the strlen.
  // This is a bit wasteful but in constexpr there *must* be a fixed upper size for data structures.
  ConstexprVector<JniDescriptorNode, kMaxSize> jni_desc_node_list;
  JniDescriptorNode return_jni_desc;

  enum State {
    kInitial = 0,
    kParsingParameters = 1,
    kParsingReturnType = 2,
    kCompleted = 3,
  };

  State state = kInitial;

  while (!signature.empty()) {
    switch (state) {
      case kInitial: {
        char c = signature[0];
        PARSE_ASSERT_MSG(c == '(',
                         "First character of a JNI signature must be a '('");
        state = kParsingParameters;
        signature = signature.substr(/*start*/1u);
        break;
      }
      case kParsingParameters: {
        char c = signature[0];
        if (c == ')') {
          state = kParsingReturnType;
          signature = signature.substr(/*start*/1u);
          break;
        }

        ConstexprOptional<ParseTypeDescriptorResult>
            res = ParseSingleTypeDescriptor(signature, /*allow_void*/false);
        PARSE_ASSERT(res);

        jni_desc_node_list.push_back(res->as_node());

        signature = res->remainder;
        break;
      }
      case kParsingReturnType: {
        ConstexprOptional<ParseTypeDescriptorResult>
            res = ParseSingleTypeDescriptor(signature, /*allow_void*/true);
        PARSE_ASSERT(res);

        return_jni_desc = res->as_node();
        signature = res->remainder;
        state = kCompleted;
        break;
      }
      default: {
        // e.g. "()VI" is illegal because the V terminates the signature.
        PARSE_FAILURE("Signature had left over tokens after parsing return type");
        break;
      }
    }
  }

  switch (state) {
    case kCompleted:
      // Everything is ok.
      break;
    case kParsingParameters:
      PARSE_FAILURE("Signature was missing ')'");
      break;
    case kParsingReturnType:
      PARSE_FAILURE("Missing return type");
    case kInitial:
      PARSE_FAILURE("Cannot have an empty signature");
    default:
      X_ASSERT(false);
  }

  return {{jni_desc_node_list, return_jni_desc}};
}

// What kind of JNI does this type belong to?
enum NativeKind {
  kNotJni,        // Illegal parameter used inside of a function type.
  kNormalJniCallingConventionParameter,
  kNormalNative,
  kFastNative,      // Also valid in normal.
  kCriticalNative,  // Also valid in fast/normal.
};

// Is this type final, i.e. it cannot be subtyped?
enum TypeFinal {
  kNotFinal,
  kFinal         // e.g. any primitive or any "final" class such as String.
};

// What position is the JNI type allowed to be in?
// Ignored when in a CriticalNative context.
enum NativePositionAllowed {
  kNotAnyPosition,
  kReturnPosition,
  kZerothPosition,
  kFirstOrLaterPosition,
  kSecondOrLaterPosition,
};

constexpr NativePositionAllowed ConvertPositionToAllowed(size_t position) {
  switch (position) {
    case 0:
      return kZerothPosition;
    case 1:
      return kFirstOrLaterPosition;
    default:
      return kSecondOrLaterPosition;
  }
}

// Type traits for a JNI parameter type. See below for specializations.
template<typename T>
struct jni_type_trait {
  static constexpr NativeKind native_kind = kNotJni;
  static constexpr const char type_descriptor[] = "(illegal)";
  static constexpr NativePositionAllowed position_allowed = kNotAnyPosition;
  static constexpr TypeFinal type_finality = kNotFinal;
  static constexpr const char type_name[] = "(illegal)";
};

// Access the jni_type_trait<T> from a non-templated constexpr function.
// Identical non-static fields to jni_type_trait, see Reify().
struct ReifiedJniTypeTrait {
  NativeKind native_kind;
  ConstexprStringView type_descriptor;
  NativePositionAllowed position_allowed;
  TypeFinal type_finality;
  ConstexprStringView type_name;

  template<typename T>
  static constexpr ReifiedJniTypeTrait Reify() {
    // This should perhaps be called 'Type Erasure' except we don't use virtuals,
    // so it's not quite the same idiom.
    using TR = jni_type_trait<T>;
    return {TR::native_kind,
            TR::type_descriptor,
            TR::position_allowed,
            TR::type_finality,
            TR::type_name};
  }

  // Find the most similar ReifiedJniTypeTrait corresponding to the type descriptor.
  //
  // Any type can be found by using the exact canonical type descriptor as listed
  // in the jni type traits definitions.
  //
  // Non-final JNI types have limited support for inexact similarity:
  //   [[* | [L* -> jobjectArray
  //   L* -> jobject
  //
  // Otherwise return a nullopt.
  static constexpr ConstexprOptional<ReifiedJniTypeTrait>
  MostSimilarTypeDescriptor(ConstexprStringView type_descriptor);
};

constexpr bool
operator==(const ReifiedJniTypeTrait& lhs, const ReifiedJniTypeTrait& rhs) {
  return lhs.native_kind == rhs.native_kind
      && rhs.type_descriptor == lhs.type_descriptor &&
      lhs.position_allowed == rhs.position_allowed
      && rhs.type_finality == lhs.type_finality &&
      lhs.type_name == rhs.type_name;
}

inline std::ostream& operator<<(std::ostream& os, const ReifiedJniTypeTrait& rjtt) {
  // os << "ReifiedJniTypeTrait<" << rjft.type_name << ">";
  os << rjtt.type_name;
  return os;
}

// Template specialization for any JNI typedefs.
#define JNI_TYPE_TRAIT(jtype, the_type_descriptor, the_native_kind, the_type_finality, the_position) \
template <>                                                                    \
struct jni_type_trait< jtype > {                                               \
  static constexpr NativeKind native_kind = the_native_kind;                   \
  static constexpr const char type_descriptor[] = the_type_descriptor;         \
  static constexpr NativePositionAllowed position_allowed = the_position;      \
  static constexpr TypeFinal type_finality = the_type_finality;                \
  static constexpr const char type_name[] = #jtype;                            \
};

#define DEFINE_JNI_TYPE_TRAIT(TYPE_TRAIT_FN)                                                                  \
TYPE_TRAIT_FN(jboolean,          "Z",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jbyte,             "B",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jchar,             "C",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jshort,            "S",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jint,              "I",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jlong,             "J",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jfloat,            "F",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jdouble,           "D",                      kCriticalNative,   kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jobject,           "Ljava/lang/Object;",     kFastNative,    kNotFinal, kFirstOrLaterPosition)  \
TYPE_TRAIT_FN(jclass,            "Ljava/lang/Class;",      kFastNative,       kFinal, kFirstOrLaterPosition)  \
TYPE_TRAIT_FN(jstring,           "Ljava/lang/String;",     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jarray,            "Ljava/lang/Object;",     kFastNative,    kNotFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jobjectArray,      "[Ljava/lang/Object;",    kFastNative,    kNotFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jbooleanArray,     "[Z",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jbyteArray,        "[B",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jcharArray,        "[C",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jshortArray,       "[S",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jintArray,         "[I",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jlongArray,        "[J",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jfloatArray,       "[F",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jdoubleArray,      "[D",                     kFastNative,       kFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(jthrowable,        "Ljava/lang/Throwable;",  kFastNative,    kNotFinal, kSecondOrLaterPosition) \
TYPE_TRAIT_FN(JNIEnv*,           "",                       kNormalJniCallingConventionParameter, kFinal, kZerothPosition) \
TYPE_TRAIT_FN(void,              "V",                      kCriticalNative,   kFinal, kReturnPosition)        \

DEFINE_JNI_TYPE_TRAIT(JNI_TYPE_TRAIT)

// See ReifiedJniTypeTrait for documentation.
constexpr ConstexprOptional<ReifiedJniTypeTrait>
ReifiedJniTypeTrait::MostSimilarTypeDescriptor(ConstexprStringView type_descriptor) {
#define MATCH_EXACT_TYPE_DESCRIPTOR_FN(type, type_desc, native_kind, ...)                      \
    if (type_descriptor == type_desc && native_kind >= kNormalNative) {                        \
      return { Reify<type>() };                                                                \
    }

  // Attempt to look up by the precise type match first.
  DEFINE_JNI_TYPE_TRAIT(MATCH_EXACT_TYPE_DESCRIPTOR_FN);

  // Otherwise, we need to do an imprecise match:
  char shorty = type_descriptor.size() >= 1 ? type_descriptor[0] : '\0';
  if (shorty == 'L') {
    // Something more specific like Ljava/lang/Throwable, string, etc
    // is already matched by the macro-expanded conditions above.
    return {Reify<jobject>()};
  } else if (type_descriptor.size() >= 2) {
    auto shorty_shorty = type_descriptor.substr(/*start*/0, /*size*/2u);
    if (shorty_shorty == "[[" || shorty_shorty == "[L") {
      // JNI arrays are covariant, so any type T[] (T!=primitive) is castable to Object[].
      return {Reify<jobjectArray>()};
    }
  }

  // To handle completely invalid values.
  return NullConstexprOptional{};
}

// Is this actual JNI position consistent with the expected position?
constexpr bool IsValidJniParameterPosition(NativeKind native_kind,
                                           NativePositionAllowed position,
                                           NativePositionAllowed expected_position) {
  X_ASSERT(expected_position != kNotAnyPosition);

  if (native_kind == kCriticalNative) {
    // CriticalNatives ignore positions since the first 2 special
    // parameters are stripped.
    return true;
  }

  // Is this a return-only position?
  if (expected_position == kReturnPosition) {
    if (position != kReturnPosition) {
      // void can only be in the return position.
      return false;
    }
    // Don't do the other non-return position checks for a return-only position.
    return true;
  }

  // JNIEnv* can only be in the first spot.
  if (position == kZerothPosition && expected_position != kZerothPosition) {
    return false;
    // jobject, jclass can be 1st or anywhere afterwards.
  } else if (position == kFirstOrLaterPosition && expected_position != kFirstOrLaterPosition) {
    return false;
    // All other parameters must be in 2nd+ spot, or in the return type.
  } else if (position == kSecondOrLaterPosition || position == kReturnPosition) {
    if (expected_position != kFirstOrLaterPosition && expected_position != kSecondOrLaterPosition) {
      return false;
    }
  }

  return true;
}

// Check if a jni parameter type is valid given its position and native_kind.
template <typename T>
constexpr bool IsValidJniParameter(NativeKind native_kind, NativePositionAllowed position) {
  // const,volatile does not affect JNI compatibility since it does not change ABI.
  using expected_trait = jni_type_trait<typename std::remove_cv<T>::type>;
  NativeKind expected_native_kind = expected_trait::native_kind;

  // Most types 'T' are not valid for JNI.
  if (expected_native_kind == NativeKind::kNotJni) {
    return false;
  }

  // The rest of the types might be valid, but it depends on the context (native_kind)
  // and also on their position within the parameters.

  // Position-check first.
  NativePositionAllowed expected_position = expected_trait::position_allowed;
  if (!IsValidJniParameterPosition(native_kind, position, expected_position)) {
    return false;
  }

  // Ensure the type appropriate is for the native kind.
  if (expected_native_kind == kNormalJniCallingConventionParameter) {
    // It's always wrong to use a JNIEnv* anywhere but the 0th spot.
    if (native_kind == kCriticalNative) {
      // CriticalNative does not allow using a JNIEnv*.
      return false;
    }

    return true;  // OK: JniEnv* used in 0th position.
  } else if (expected_native_kind == kCriticalNative) {
    // CriticalNative arguments are always valid JNI types anywhere used.
    return true;
  } else if (native_kind == kCriticalNative) {
    // The expected_native_kind was non-critical but we are in a critical context.
    // Illegal type.
    return false;
  }

  // Everything else is fine, e.g. fast/normal native + fast/normal native parameters.
  return true;
}

// Is there sufficient number of parameters given the kind of JNI that it is?
constexpr bool IsJniParameterCountValid(NativeKind native_kind, size_t count) {
  if (native_kind == kNormalNative || native_kind == kFastNative) {
    return count >= 2u;
  } else if (native_kind == kCriticalNative) {
    return true;
  }

  constexpr bool invalid_parameter = false;
  X_ASSERT(invalid_parameter);
  return false;
}

// Basic template interface. See below for partial specializations.
//
// Each instantiation will have a 'value' field that determines whether or not
// all of the Args are valid JNI arguments given their native_kind.
template<NativeKind native_kind, size_t position, typename ... Args>
struct is_valid_jni_argument_type {
  // static constexpr bool value = ?;
};

template<NativeKind native_kind, size_t position>
struct is_valid_jni_argument_type<native_kind, position> {
  static constexpr bool value = true;
};

template<NativeKind native_kind, size_t position, typename T>
struct is_valid_jni_argument_type<native_kind, position, T> {
  static constexpr bool value =
      IsValidJniParameter<T>(native_kind, ConvertPositionToAllowed(position));
};

template<NativeKind native_kind, size_t position, typename T, typename ... Args>
struct is_valid_jni_argument_type<native_kind, position, T, Args...> {
  static constexpr bool value =
      IsValidJniParameter<T>(native_kind, ConvertPositionToAllowed(position))
          && is_valid_jni_argument_type<native_kind,
                                        position + 1,
                                        Args...>::value;
};

// This helper is required to decompose the function type into a list of arg types.
template<NativeKind native_kind, typename T, T* fn>
struct is_valid_jni_function_type_helper;

template<NativeKind native_kind, typename R, typename ... Args, R (*fn)(Args...)>
struct is_valid_jni_function_type_helper<native_kind, R(Args...), fn> {
  static constexpr bool value =
      IsJniParameterCountValid(native_kind, sizeof...(Args))
          && IsValidJniParameter<R>(native_kind, kReturnPosition)
          && is_valid_jni_argument_type<native_kind, /*position*/
                                        0,
                                        Args...>::value;
};

// Is this function type 'T' a valid C++ function type given the native_kind?
template<NativeKind native_kind, typename T, T* fn>
constexpr bool IsValidJniFunctionType() {
  return is_valid_jni_function_type_helper<native_kind, T, fn>::value;
  // TODO: we could replace template metaprogramming with constexpr by
  // using FunctionTypeMetafunction.
}

// Many parts of std::array is not constexpr until C++17.
template<typename T, size_t N>
struct ConstexprArray {
  // Intentionally public to conform to std::array.
  // This means all constructors are implicit.
  // *NOT* meant to be used directly, use the below functions instead.
  //
  // The reason std::array has it is to support direct-list-initialization,
  // e.g. "ConstexprArray<T, sz>{T{...}, T{...}, T{...}, ...};"
  //
  // Note that otherwise this would need a very complicated variadic
  // argument constructor to only support list of Ts.
  T _array[N];

  constexpr size_t size() const {
    return N;
  }

  using iterator = T*;
  using const_iterator = const T*;

  constexpr iterator begin() {
    return &_array[0];
  }

  constexpr iterator end() {
    return &_array[N];
  }

  constexpr const_iterator begin() const {
    return &_array[0];
  }

  constexpr const_iterator end() const {
    return &_array[N];
  }

  constexpr T& operator[](size_t i) {
    return _array[i];
  }

  constexpr const T& operator[](size_t i) const {
    return _array[i];
  }
};

// Why do we need this?
// auto x = {1,2,3} creates an initializer_list,
//   but they can't be returned because it contains pointers to temporaries.
// auto x[] = {1,2,3} doesn't even work because auto for arrays is not supported.
//
// an alternative would be to pull up std::common_t directly into the call site
//   std::common_type_t<Args...> array[] = {1,2,3}
// but that's even more cludgier.
//
// As the other "stdlib-wannabe" functions, it's weaker than the library
// fundamentals std::make_array but good enough for our use.
template<typename... Args>
constexpr auto MakeArray(Args&& ... args) {
  return ConstexprArray<typename std::common_type<Args...>::type,
                        sizeof...(Args)>{args...};
}

// See below.
template<typename T, T* fn>
struct FunctionTypeMetafunction {
};

// Enables the "map" operation over the function component types.
template<typename R, typename ... Args, R (*fn)(Args...)>
struct FunctionTypeMetafunction<R(Args...), fn> {
  // Count how many arguments there are, and add 1 for the return type.
  static constexpr size_t
      count = sizeof...(Args) + 1u;  // args and return type.

  // Return an array where the metafunction 'Func' has been applied
  // to every argument type. The metafunction must be returning a common type.
  template<template<typename Arg> class Func>
  static constexpr auto map_args() {
    return map_args_impl<Func>(holder < Args > {}...);
  }

  // Apply the metafunction 'Func' over the return type.
  template<template<typename Ret> class Func>
  static constexpr auto map_return() {
    return Func<R>{}();
  }

 private:
  template<typename T>
  struct holder {
  };

  template<template<typename Arg> class Func, typename Arg0, typename... ArgsRest>
  static constexpr auto map_args_impl(holder<Arg0>, holder<ArgsRest>...) {
    // One does not simply call MakeArray with 0 template arguments...
    auto array = MakeArray(
        Func<Args>{}()...
    );

    return array;
  }

  template<template<typename Arg> class Func>
  static constexpr auto map_args_impl() {
    // This overload provides support for MakeArray() with 0 arguments.
    using ComponentType = decltype(Func<void>{}());

    return ConstexprArray<ComponentType, /*size*/0u>{};
  }
};

// Apply ReifiedJniTypeTrait::Reify<T> for every function component type.
template<typename T>
struct ReifyJniTypeMetafunction {
  constexpr ReifiedJniTypeTrait operator()() const {
    auto res = ReifiedJniTypeTrait::Reify<T>();
    X_ASSERT(res.native_kind != kNotJni);
    return res;
  }
};

// Ret(Args...) where every component is a ReifiedJniTypeTrait.
template<size_t kMaxSize>
using ReifiedJniSignature = FunctionSignatureDescriptor<ReifiedJniTypeTrait,
                                                        kMaxSize>;

// Attempts to convert the function type T into a list of ReifiedJniTypeTraits
// that correspond to the function components.
//
// If conversion fails (i.e. non-jni compatible types), then:
//    parses are fatal -> assertion is triggered (default behavior),
//    parses are nonfatal -> returns nullopt (test behavior).
template <NativeKind native_kind,
          typename T,
          T* fn,
          size_t kMaxSize = FunctionTypeMetafunction<T, fn>::count>
constexpr ConstexprOptional<ReifiedJniSignature<kMaxSize>>
MaybeMakeReifiedJniSignature() {
  if (!IsValidJniFunctionType<native_kind, T, fn>()) {
    PARSE_FAILURE("The function signature has one or more types incompatible with JNI.");
  }

  ReifiedJniTypeTrait return_jni_trait =
      FunctionTypeMetafunction<T,
                         fn>::template map_return<ReifyJniTypeMetafunction>();

  constexpr size_t
      kSkipArgumentPrefix = (native_kind != kCriticalNative) ? 2u : 0u;
  ConstexprVector<ReifiedJniTypeTrait, kMaxSize> args;
  auto args_list =
      FunctionTypeMetafunction<T, fn>::template map_args<ReifyJniTypeMetafunction>();
  size_t args_index = 0;
  for (auto& arg : args_list) {
    // Ignore the 'JNIEnv*, jobject' / 'JNIEnv*, jclass' prefix,
    // as its not part of the function descriptor string.
    if (args_index >= kSkipArgumentPrefix) {
      args.push_back(arg);
    }

    ++args_index;
  }

  return {{args, return_jni_trait}};
}

#define COMPARE_DESCRIPTOR_CHECK(expr) if (!(expr)) return false
#define COMPARE_DESCRIPTOR_FAILURE_MSG(msg) if ((true)) return false

// Compares a user-defined JNI descriptor (of a single argument or return value)
// to a reified jni type trait that was derived from the C++ function type.
//
// If comparison fails (i.e. non-jni compatible types), then:
//    parses are fatal -> assertion is triggered (default behavior),
//    parses are nonfatal -> returns false (test behavior).
constexpr bool
CompareJniDescriptorNodeErased(JniDescriptorNode user_defined_descriptor,
                               ReifiedJniTypeTrait derived) {

  ConstexprOptional<ReifiedJniTypeTrait> user_reified_opt =
      ReifiedJniTypeTrait::MostSimilarTypeDescriptor(user_defined_descriptor.longy);

  if (!user_reified_opt.has_value()) {
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "Could not find any JNI C++ type corresponding to the type descriptor");
  }

  char user_shorty = user_defined_descriptor.longy.size() > 0 ?
                     user_defined_descriptor.longy[0] :
                     '\0';

  ReifiedJniTypeTrait user = user_reified_opt.value();
  if (user == derived) {
    // If we had a similar match, immediately return success.
    return true;
  } else if (derived.type_name == "jthrowable") {
    if (user_shorty == 'L') {
      // Weakly allow any objects to correspond to a jthrowable.
      // We do not know the managed type system so we have to be permissive here.
      return true;
    } else {
      COMPARE_DESCRIPTOR_FAILURE_MSG(
          "jthrowable must correspond to an object type descriptor");
    }
  } else if (derived.type_name == "jarray") {
    if (user_shorty == '[') {
      // a jarray is the base type for all other array types. Allow.
      return true;
    } else {
      // Ljava/lang/Object; is the root for all array types.
      // Already handled above in 'if user == derived'.
      COMPARE_DESCRIPTOR_FAILURE_MSG(
          "jarray must correspond to array type descriptor");
    }
  }
  // Otherwise, the comparison has failed and the rest of this is only to
  // pick the most appropriate error message.
  //
  // Note: A weaker form of comparison would allow matching 'Ljava/lang/String;'
  // against 'jobject', etc. However the policy choice here is to enforce the strictest
  // comparison that we can to utilize the type system to its fullest.

  if (derived.type_finality == kFinal || user.type_finality == kFinal) {
    // Final types, e.g. "I", "Ljava/lang/String;" etc must match exactly
    // the C++ jni descriptor string ('I' -> jint, 'Ljava/lang/String;' -> jstring).
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "The JNI descriptor string must be the exact type equivalent of the "
            "C++ function signature.");
  } else if (user_shorty == '[') {
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "The array JNI descriptor must correspond to j${type}Array or jarray");
  } else if (user_shorty == 'L') {
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "The object JNI descriptor must correspond to jobject.");
  } else {
    X_ASSERT(false);  // We should never get here, but either way this means the types did not match
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "The JNI type descriptor string does not correspond to the C++ JNI type.");
  }
}

// Matches a user-defined JNI function descriptor against the C++ function type.
//
// If matches fails, then:
//    parses are fatal -> assertion is triggered (default behavior),
//    parses are nonfatal -> returns false (test behavior).
template<NativeKind native_kind, typename T, T* fn, size_t kMaxSize>
constexpr bool
MatchJniDescriptorWithFunctionType(ConstexprStringView user_function_descriptor) {
  constexpr size_t kReifiedMaxSize = FunctionTypeMetafunction<T, fn>::count;

  ConstexprOptional<ReifiedJniSignature<kReifiedMaxSize>>
      reified_signature_opt =
      MaybeMakeReifiedJniSignature<native_kind, T, fn>();
  if (!reified_signature_opt) {
    // Assertion handling done by MaybeMakeReifiedJniSignature.
    return false;
  }

  ConstexprOptional<JniSignatureDescriptor<kMaxSize>> user_jni_sig_desc_opt =
      ParseSignatureAsList<kMaxSize>(user_function_descriptor);

  if (!user_jni_sig_desc_opt) {
    // Assertion handling done by ParseSignatureAsList.
    return false;
  }

  ReifiedJniSignature<kReifiedMaxSize>
      reified_signature = reified_signature_opt.value();
  JniSignatureDescriptor<kMaxSize>
      user_jni_sig_desc = user_jni_sig_desc_opt.value();

  if (reified_signature.args.size() != user_jni_sig_desc.args.size()) {
    COMPARE_DESCRIPTOR_FAILURE_MSG(
        "Number of parameters in JNI descriptor string"
            "did not match number of parameters in C++ function type");
  } else if (!CompareJniDescriptorNodeErased(user_jni_sig_desc.ret,
                                             reified_signature.ret)) {
    // Assertion handling done by CompareJniDescriptorNodeErased.
    return false;
  } else {
    for (size_t i = 0; i < user_jni_sig_desc.args.size(); ++i) {
      if (!CompareJniDescriptorNodeErased(user_jni_sig_desc.args[i],
                                          reified_signature.args[i])) {
        // Assertion handling done by CompareJniDescriptorNodeErased.
        return false;
      }
    }
  }

  return true;
}

// Supports inferring the JNI function descriptor string from the C++
// function type when all type components are final.
template<NativeKind native_kind, typename T, T* fn>
struct InferJniDescriptor {
  static constexpr size_t kMaxSize = FunctionTypeMetafunction<T, fn>::count;

  // Convert the C++ function type into a JniSignatureDescriptor which holds
  // the canonical (according to jni_traits) descriptors for each component.
  // The C++ type -> JNI mapping must be nonambiguous (see jni_macros.h for exact rules).
  //
  // If conversion fails (i.e. C++ signatures is illegal for JNI, or the types are ambiguous):
  //    if parsing is fatal -> assertion failure (default behavior)
  //    if parsing is nonfatal -> returns nullopt (test behavior).
  static constexpr ConstexprOptional<JniSignatureDescriptor<kMaxSize>> FromFunctionType() {
    constexpr size_t kReifiedMaxSize = kMaxSize;
    ConstexprOptional<ReifiedJniSignature<kReifiedMaxSize>>
        reified_signature_opt =
        MaybeMakeReifiedJniSignature<native_kind, T, fn>();
    if (!reified_signature_opt) {
      // Assertion handling done by MaybeMakeReifiedJniSignature.
      return NullConstexprOptional{};
    }

    ReifiedJniSignature<kReifiedMaxSize>
        reified_signature = reified_signature_opt.value();

    JniSignatureDescriptor<kReifiedMaxSize> signature_descriptor;

    if (reified_signature.ret.type_finality != kFinal) {
      // e.g. jint, jfloatArray, jstring, jclass are ok. jobject, jthrowable, jarray are not.
      PARSE_FAILURE("Bad return type. Only unambigous (final) types can be used to infer a signature.");  // NOLINT
    }
    signature_descriptor.ret =
        JniDescriptorNode{reified_signature.ret.type_descriptor};

    for (size_t i = 0; i < reified_signature.args.size(); ++i) {
      const ReifiedJniTypeTrait& arg_trait = reified_signature.args[i];
      if (arg_trait.type_finality != kFinal) {
        PARSE_FAILURE("Bad parameter type. Only unambigous (final) types can be used to infer a signature.");  // NOLINT
      }
      signature_descriptor.args.push_back(JniDescriptorNode{
          arg_trait.type_descriptor});
    }

    return {signature_descriptor};
  }

  // Calculate the exact string size that the JNI descriptor will be
  // at runtime.
  //
  // Without this we cannot allocate enough space within static storage
  // to fit the compile-time evaluated string.
  static constexpr size_t CalculateStringSize() {
    ConstexprOptional<JniSignatureDescriptor<kMaxSize>>
        signature_descriptor_opt =
        FromFunctionType();
    if (!signature_descriptor_opt) {
      // Assertion handling done by FromFunctionType.
      return 0u;
    }

    JniSignatureDescriptor<kMaxSize> signature_descriptor =
        signature_descriptor_opt.value();

    size_t acc_size = 1u;  // All sigs start with '('.

    // Now add every parameter.
    for (size_t j = 0; j < signature_descriptor.args.size(); ++j) {
      const JniDescriptorNode& arg_descriptor = signature_descriptor.args[j];
      // for (const JniDescriptorNode& arg_descriptor : signature_descriptor.args) {
      acc_size += arg_descriptor.longy.size();
    }

    acc_size += 1u;   // Add space for ')'.

    // Add space for the return value.
    acc_size += signature_descriptor.ret.longy.size();

    return acc_size;
  }

  static constexpr size_t kMaxStringSize = CalculateStringSize();
  using ConstexprStringDescriptorType = ConstexprArray<char,
                                                       kMaxStringSize + 1>;

  // Convert the JniSignatureDescriptor we get in FromFunctionType()
  // into a flat constexpr char array.
  //
  // This is done by repeated string concatenation at compile-time.
  static constexpr ConstexprStringDescriptorType GetString() {
    ConstexprStringDescriptorType c_str{};

    ConstexprOptional<JniSignatureDescriptor<kMaxSize>>
        signature_descriptor_opt =
        FromFunctionType();
    if (!signature_descriptor_opt.has_value()) {
      // Assertion handling done by FromFunctionType.
      c_str[0] = '\0';
      return c_str;
    }

    JniSignatureDescriptor<kMaxSize> signature_descriptor =
        signature_descriptor_opt.value();

    size_t pos = 0u;
    c_str[pos++] = '(';

    // Copy all parameter descriptors.
    for (size_t j = 0; j < signature_descriptor.args.size(); ++j) {
      const JniDescriptorNode& arg_descriptor = signature_descriptor.args[j];
      ConstexprStringView longy = arg_descriptor.longy;
      for (size_t i = 0; i < longy.size(); ++i) {
        c_str[pos++] = longy[i];
      }
    }

    c_str[pos++] = ')';

    // Copy return descriptor.
    ConstexprStringView longy = signature_descriptor.ret.longy;
    for (size_t i = 0; i < longy.size(); ++i) {
      c_str[pos++] = longy[i];
    }

    X_ASSERT(pos == kMaxStringSize);

    c_str[pos] = '\0';

    return c_str;
  }

  // Turn a pure constexpr string into one that can be accessed at non-constexpr
  // time. Note that the 'static constexpr' storage must be in the scope of a
  // function (prior to C++17) to avoid linking errors.
  static const char* GetStringAtRuntime() {
    static constexpr ConstexprStringDescriptorType str = GetString();
    return &str[0];
  }
};

// Expression to return JNINativeMethod, performs checking on signature+fn.
#define MAKE_CHECKED_JNI_NATIVE_METHOD(native_kind, name_, signature_, fn) \
  ([]() {                                                                \
    using namespace nativehelper::detail;  /* NOLINT(google-build-using-namespace) */ \
    static_assert(                                                       \
        MatchJniDescriptorWithFunctionType<native_kind,                  \
                                           decltype(fn),                 \
                                           fn,                           \
                                           sizeof(signature_)>(signature_),\
        "JNI signature doesn't match C++ function type.");               \
    /* Suppress implicit cast warnings by explicitly casting. */         \
    return JNINativeMethod {                                             \
        const_cast<decltype(JNINativeMethod::name)>(name_),              \
        const_cast<decltype(JNINativeMethod::signature)>(signature_),    \
        reinterpret_cast<void*>(&(fn))};                                 \
  })()

// Expression to return JNINativeMethod, infers signature from fn.
#define MAKE_INFERRED_JNI_NATIVE_METHOD(native_kind, name_, fn)          \
  ([]() {                                                                \
    using namespace nativehelper::detail;  /* NOLINT(google-build-using-namespace) */ \
    /* Suppress implicit cast warnings by explicitly casting. */         \
    return JNINativeMethod {                                             \
        const_cast<decltype(JNINativeMethod::name)>(name_),              \
        const_cast<decltype(JNINativeMethod::signature)>(                \
            InferJniDescriptor<native_kind,                              \
                               decltype(fn),                             \
                               fn>::GetStringAtRuntime()),               \
        reinterpret_cast<void*>(&(fn))};                                 \
  })()

}  // namespace detail
}  // namespace nativehelper