Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions clang/docs/LanguageExtensions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -416,8 +416,7 @@ Builtin Macros
``__clang_literal_encoding__``
Defined to a narrow string literal that represents the current encoding of
narrow string literals, e.g., ``"hello"``. This macro typically expands to
"UTF-8" (but may change in the future if the
``-fexec-charset="Encoding-Name"`` option is implemented.)
the charset specified by -fexec-charset if specified, or the system charset.

``__clang_wide_literal_encoding__``
Defined to a narrow string literal that represents the current encoding of
Expand Down
3 changes: 3 additions & 0 deletions clang/include/clang/Basic/LangOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,9 @@ class LangOptions : public LangOptionsBase {
bool AtomicFineGrainedMemory = false;
bool AtomicIgnoreDenormalMode = false;

/// Name of the exec charset to convert the internal charset to.
std::string ExecCharset;

LangOptions();

/// Set language defaults for the given input language and
Expand Down
7 changes: 7 additions & 0 deletions clang/include/clang/Basic/TokenKinds.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@ inline bool isLiteral(TokenKind K) {
isStringLiteral(K) || K == tok::header_name || K == tok::binary_data;
}

/// Return true if this is a utf literal kind.
inline bool isUTFLiteral(TokenKind K) {
return K == tok::utf8_char_constant || K == tok::utf8_string_literal ||
K == tok::utf16_char_constant || K == tok::utf16_string_literal ||
K == tok::utf32_char_constant || K == tok::utf32_string_literal;
}

/// Return true if this is any of tok::annot_* kinds.
bool isAnnotation(TokenKind K);

Expand Down
5 changes: 5 additions & 0 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -7158,6 +7158,11 @@ let Visibility = [CC1Option, CC1AsOption, FC1Option] in {
def tune_cpu : Separate<["-"], "tune-cpu">,
HelpText<"Tune for a specific cpu type">,
MarshallingInfoString<TargetOpts<"TuneCPU">>;
def fexec_charset : Separate<["-"], "fexec-charset">, MetaVarName<"<charset>">,
HelpText<"Set the execution <charset> for string and character literals. "
"Supported character encodings include ISO8859-1, UTF-8, IBM-1047 "
"and those supported by the host icu or iconv library.">,
MarshallingInfoString<LangOpts<"ExecCharset">>;
def target_cpu : Separate<["-"], "target-cpu">,
HelpText<"Target a specific cpu type">,
MarshallingInfoString<TargetOpts<"CPU">>;
Expand Down
36 changes: 36 additions & 0 deletions clang/include/clang/Lex/LiteralConverter.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//===--- clang/Lex/LiteralConverter.h - Translator for Literals -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_LEX_LITERALCONVERTER_H
#define LLVM_CLANG_LEX_LITERALCONVERTER_H

#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CharSet.h"

enum ConversionAction { NoConversion, ToSystemCharset, ToExecCharset };

class LiteralConverter {
llvm::StringRef InternalCharset;
llvm::StringRef SystemCharset;
llvm::StringRef ExecCharset;
llvm::StringMap<llvm::CharSetConverter> CharsetConverters;

public:
llvm::CharSetConverter *getConverter(const char *Codepage);
llvm::CharSetConverter *getConverter(ConversionAction Action);
llvm::CharSetConverter *createAndInsertCharConverter(const char *To);
void setConvertersFromOptions(const clang::LangOptions &Opts,
const clang::TargetInfo &TInfo,
clang::DiagnosticsEngine &Diags);
};

#endif
12 changes: 8 additions & 4 deletions clang/include/clang/Lex/LiteralSupport.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/LiteralConverter.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CharSet.h"
#include "llvm/Support/DataTypes.h"

namespace clang {
Expand Down Expand Up @@ -233,6 +235,7 @@ class StringLiteralParser {
const LangOptions &Features;
const TargetInfo &Target;
DiagnosticsEngine *Diags;
LiteralConverter *LiteralConv;

unsigned MaxTokenLength;
unsigned SizeBound;
Expand All @@ -248,16 +251,17 @@ class StringLiteralParser {
public:
StringLiteralParser(ArrayRef<Token> StringToks, Preprocessor &PP,
StringLiteralEvalMethod StringMethod =
StringLiteralEvalMethod::Evaluated);
StringLiteralEvalMethod::Evaluated,
ConversionAction Action = ToExecCharset);
StringLiteralParser(ArrayRef<Token> StringToks, const SourceManager &sm,
const LangOptions &features, const TargetInfo &target,
DiagnosticsEngine *diags = nullptr)
: SM(sm), Features(features), Target(target), Diags(diags),
MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
LiteralConv(nullptr), MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
ResultPtr(ResultBuf.data()),
EvalMethod(StringLiteralEvalMethod::Evaluated), hadError(false),
Pascal(false) {
init(StringToks);
init(StringToks, NoConversion);
}

bool hadError;
Expand Down Expand Up @@ -305,7 +309,7 @@ class StringLiteralParser {
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix);

private:
void init(ArrayRef<Token> StringToks);
void init(ArrayRef<Token> StringToks, ConversionAction Action);
bool CopyStringFragment(const Token &Tok, const char *TokBegin,
StringRef Fragment);
void DiagnoseLexingError(SourceLocation Loc);
Expand Down
3 changes: 3 additions & 0 deletions clang/include/clang/Lex/Preprocessor.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/LiteralConverter.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/ModuleMap.h"
Expand Down Expand Up @@ -150,6 +151,7 @@ class Preprocessor {
std::unique_ptr<ScratchBuffer> ScratchBuf;
HeaderSearch &HeaderInfo;
ModuleLoader &TheModuleLoader;
LiteralConverter LiteralConv;

/// External source of macros.
ExternalPreprocessorSource *ExternalSource;
Expand Down Expand Up @@ -1212,6 +1214,7 @@ class Preprocessor {
SelectorTable &getSelectorTable() { return Selectors; }
Builtin::Context &getBuiltinInfo() { return *BuiltinInfo; }
llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; }
LiteralConverter &getLiteralConverter() { return LiteralConv; }

void setExternalSource(ExternalPreprocessorSource *Source) {
ExternalSource = Source;
Expand Down
17 changes: 13 additions & 4 deletions clang/lib/Driver/ToolChains/Clang.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
#include "llvm/Frontend/Debug/Options.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/CharSet.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Compression.h"
Expand Down Expand Up @@ -7592,12 +7593,20 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
<< value;
}

// -fexec_charset=UTF-8 is default. Reject others
// Set the default fexec-charset as the system charset.
CmdArgs.push_back("-fexec-charset");
CmdArgs.push_back(Args.MakeArgString(Triple.getSystemCharset()));
if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
StringRef value = execCharset->getValue();
if (!value.equals_insensitive("utf-8"))
D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
<< value;
llvm::ErrorOr<llvm::CharSetConverter> ErrorOrConverter =
llvm::CharSetConverter::create("UTF-8", value.data());
if (ErrorOrConverter) {
CmdArgs.push_back("-fexec-charset");
CmdArgs.push_back(Args.MakeArgString(value));
} else {
D.Diag(diag::err_drv_invalid_value)
<< execCharset->getAsString(Args) << value;
}
}

RenderDiagnosticsOptions(D, Args, CmdArgs);
Expand Down
3 changes: 3 additions & 0 deletions clang/lib/Frontend/CompilerInstance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "clang/Frontend/Utils.h"
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LiteralConverter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/CodeCompleteConsumer.h"
Expand Down Expand Up @@ -535,6 +536,8 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
/*ShowAllHeaders=*/true, /*OutputPath=*/"",
/*ShowDepth=*/true, /*MSStyle=*/true);
}
PP->getLiteralConverter().setConvertersFromOptions(getLangOpts(), getTarget(),
getDiagnostics());
}

std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
Expand Down
12 changes: 8 additions & 4 deletions clang/lib/Frontend/InitPreprocessor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1056,10 +1056,14 @@ static void InitializePredefinedMacros(const TargetInfo &TI,
}
}

// Macros to help identify the narrow and wide character sets
// FIXME: clang currently ignores -fexec-charset=. If this changes,
// then this may need to be updated.
Builder.defineMacro("__clang_literal_encoding__", "\"UTF-8\"");
// Macros to help identify the narrow and wide character sets. This is set
// to fexec-charset. If fexec-charset is not specified, the default is the
// system charset.
if (!LangOpts.ExecCharset.empty())
Builder.defineMacro("__clang_literal_encoding__", LangOpts.ExecCharset);
else
Builder.defineMacro("__clang_literal_encoding__",
TI.getTriple().getSystemCharset());
if (TI.getTypeWidth(TI.getWCharType()) >= 32) {
// FIXME: 32-bit wchar_t signals UTF-32. This may change
// if -fwide-exec-charset= is ever supported.
Expand Down
1 change: 1 addition & 0 deletions clang/lib/Lex/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ add_clang_library(clangLex
InitHeaderSearch.cpp
Lexer.cpp
LexHLSLRootSignature.cpp
LiteralConverter.cpp
LiteralSupport.cpp
MacroArgs.cpp
MacroInfo.cpp
Expand Down
68 changes: 68 additions & 0 deletions clang/lib/Lex/LiteralConverter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//===--- LiteralConverter.cpp - Translator for String Literals -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang/Lex/LiteralConverter.h"
#include "clang/Basic/DiagnosticDriver.h"

using namespace llvm;

llvm::CharSetConverter *LiteralConverter::getConverter(const char *Codepage) {
auto Iter = CharsetConverters.find(Codepage);
if (Iter != CharsetConverters.end())
return &Iter->second;
return nullptr;
}

llvm::CharSetConverter *
LiteralConverter::getConverter(ConversionAction Action) {
StringRef CodePage;
if (Action == ToSystemCharset)
CodePage = SystemCharset;
else if (Action == ToExecCharset)
CodePage = ExecCharset;
else
CodePage = InternalCharset;
return getConverter(CodePage.data());
}

llvm::CharSetConverter *
LiteralConverter::createAndInsertCharConverter(const char *To) {
const char *From = InternalCharset.data();
llvm::CharSetConverter *Converter = getConverter(To);
if (Converter)
return Converter;

ErrorOr<CharSetConverter> ErrorOrConverter =
llvm::CharSetConverter::create(From, To);
if (!ErrorOrConverter)
return nullptr;
CharsetConverters.insert_or_assign(StringRef(To),
std::move(*ErrorOrConverter));
return getConverter(To);
}

void LiteralConverter::setConvertersFromOptions(
const clang::LangOptions &Opts, const clang::TargetInfo &TInfo,
clang::DiagnosticsEngine &Diags) {
using namespace llvm;
SystemCharset = TInfo.getTriple().getSystemCharset();
InternalCharset = "UTF-8";
ExecCharset = Opts.ExecCharset.empty() ? InternalCharset : Opts.ExecCharset;
// Create converter between internal and system charset
if (!InternalCharset.equals(SystemCharset))
createAndInsertCharConverter(SystemCharset.data());

// Create converter between internal and exec charset specified
// in fexec-charset option.
if (InternalCharset.equals(ExecCharset))
return;
if (!createAndInsertCharConverter(ExecCharset.data())) {
Diags.Report(clang::diag::err_drv_invalid_value)
<< "-fexec-charset" << ExecCharset;
}
}
Loading