• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2024 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Codegen common to .h files."""
5
6import common
7import java_types
8
9
10def class_accessors(sb, java_classes, module_name):
11  split_arg = f'"{module_name}", ' if module_name else ''
12  for java_class in java_classes:
13    if java_class in (java_types.OBJECT_CLASS, java_types.STRING_CLASS):
14      continue
15    escaped_name = java_class.to_cpp()
16    name_with_dots = java_class.full_name_with_slashes.replace("/", ".")
17    # #ifdef needed when multple .h files are #included that common classes.
18    sb(f"""\
19#ifndef {escaped_name}_clazz_defined
20#define {escaped_name}_clazz_defined
21""")
22    # Uses std::atomic<> instead of "static jclass cached_class = ..." because
23    # that moves the initialize-once logic into the helper method (smaller code
24    # size).
25    sb(f"""\
26inline jclass {escaped_name}_clazz(JNIEnv* env) {{
27  static const char kClassName[] = "{name_with_dots}";
28  static std::atomic<jclass> cached_class;
29  return jni_zero::internal::LazyGetClass(env, kClassName, {split_arg}&cached_class);
30}}
31#endif
32
33""")
34
35
36def class_accessor_expression(java_class):
37  if java_class == java_types.OBJECT_CLASS:
38    return 'jni_zero::g_object_class'
39  if java_class == java_types.STRING_CLASS:
40    return 'jni_zero::g_string_class'
41
42  return f'{java_class.to_cpp()}_clazz(env)'
43
44
45def header_preamble(script_name,
46                    java_class,
47                    system_includes,
48                    user_includes,
49                    header_guard=None):
50  if header_guard is None:
51    header_guard = f'{java_class.to_cpp()}_JNI'
52  sb = []
53  sb.append(f"""\
54// This file was generated by
55//     {script_name}
56// For
57//     {java_class.full_name_with_dots}
58
59#ifndef {header_guard}
60#define {header_guard}
61
62""")
63  sb.extend(f'#include <{x}>\n' for x in system_includes)
64  sb.append('\n')
65  sb.extend(f'#include "{x}"\n' for x in user_includes)
66  preamble = ''.join(sb)
67
68  epilogue = f"""
69#endif  // {header_guard}
70"""
71  return preamble, epilogue
72