// Copyright (c) 2009-2024, Google LLC
// All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

#include "upb_generator/common/names.h"

#include <cstddef>
#include <string>

#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"

namespace upb {
namespace generator {

namespace {

std::string ToCIdent(absl::string_view str) {
  return absl::StrReplaceAll(str, {{".", "_"}, {"/", "_"}, {"-", "_"}});
}

std::string ToPreproc(absl::string_view str) {
  return absl::AsciiStrToUpper(ToCIdent(str));
}

}  // namespace

bool IsReflectionBootstrapProto(absl::string_view filename) {
  return filename == "net/proto2/proto/descriptor.proto" ||
         filename == "google/protobuf/descriptor.proto" ||
         filename == "src/google/protobuf/descriptor.proto" ||
         filename == "third_party/protobuf/json_enumvalue_options.proto" ||
         filename == "google/protobuf/json_enumvalue_options.proto" ||
         filename == "src/google/protobuf/json_enumvalue_options.proto";
}

std::string StripExtension(absl::string_view fname) {
  size_t lastdot = fname.find_last_of('.');
  if (lastdot == std::string::npos) {
    return std::string(fname);
  }
  return std::string(fname.substr(0, lastdot));
}

std::string IncludeGuard(absl::string_view filename) {
  return ToPreproc(filename) + "_UPB_H_";
}

std::string FileWarning(absl::string_view filename) {
  return absl::Substitute(
      "/* This file was generated by upb_generator from the input file:\n"
      " *\n"
      " *     $0\n"
      " *\n"
      " * Do not edit -- your changes will be discarded when the file is\n"
      " * regenerated.\n"
      " * NO CHECKED-IN "
      // Intentional line break.
      "PROTOBUF GENCODE */\n"
      "\n",
      filename);
}

std::string PadPrefix(absl::string_view tag) {
  return tag.empty() ? "" : absl::StrCat(" ", tag);
}

}  // namespace generator
}  // namespace upb
