1 //===--- Token.cpp - Tokens and token streams in the pseudoparser ---------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 #include "clang/Basic/LangOptions.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/Support/Format.h"
13 #include "llvm/Support/FormatVariadic.h"
18 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&OS
, const Token
&T
) {
19 OS
<< llvm::formatv("{0} {1}:{2} ", clang::tok::getTokenName(T
.Kind
), T
.Line
,
22 llvm::printEscapedString(T
.text(), OS
);
25 OS
<< llvm::format(" flags=%x", T
.Flags
);
29 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&OS
, const TokenStream
&TS
) {
30 OS
<< "Index Kind Line Text\n";
31 for (const auto &T
: TS
.tokens()) {
32 OS
<< llvm::format("%5d: %16s %4d:%-2d ", TS
.index(T
),
33 clang::tok::getTokenName(T
.Kind
), T
.Line
, T
.Indent
);
35 llvm::printEscapedString(T
.text(), OS
);
38 OS
<< llvm::format(" flags=%x", T
.Flags
);
44 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&OS
, const Token::Range
&R
) {
45 OS
<< llvm::formatv("[{0},{1})", R
.Begin
, R
.End
);
49 TokenStream::TokenStream(std::shared_ptr
<void> Payload
)
50 : Payload(std::move(Payload
)) {
51 Storage
.emplace_back();
52 Storage
.back().Kind
= clang::tok::eof
;
55 void TokenStream::finalize() {
56 assert(!isFinalized());
57 unsigned LastLine
= Storage
.back().Line
;
58 Storage
.emplace_back();
59 Storage
.back().Kind
= tok::eof
;
60 Storage
.back().Line
= LastLine
+ 1;
63 Tokens
= Tokens
.drop_front().drop_back();
66 bool TokenStream::isFinalized() const {
67 assert(!Storage
.empty() && Storage
.front().Kind
== tok::eof
);
68 if (Storage
.size() == 1)
70 return Storage
.back().Kind
== tok::eof
;
73 void TokenStream::print(llvm::raw_ostream
&OS
) const {
74 bool FirstToken
= true;
75 unsigned LastLine
= -1;
77 for (const auto &T
: tokens()) {
78 StringRef Text
= T
.text();
81 } else if (T
.Line
== LastLine
) {
82 if (LastText
.data() + LastText
.size() != Text
.data())
96 clang::LangOptions
genericLangOpts(clang::Language Lang
,
97 clang::LangStandard::Kind Standard
) {
98 clang::LangOptions Opts
;
99 std::vector
<std::string
> UnusedIncludes
;
100 LangOptions::setLangDefaults(Opts
, Lang
, llvm::Triple(), UnusedIncludes
,
103 // Some options are "on by default", but e.g. at the driver level.
105 Opts
.CXXOperatorNames
= true;
106 if (Opts
.CPlusPlus20
)
107 Opts
.Coroutines
= true;
109 // Some options are off by default, but define keywords we want to tolerate.
111 Opts
.MicrosoftExt
= true; // kw__try, kw__finally
112 Opts
.DeclSpecKeyword
= true; // __declspec
118 TokenStream
stripComments(const TokenStream
&Input
) {
119 TokenStream
Out(Input
.getPayload());
120 for (const Token
&T
: Input
.tokens()) {
121 if (T
.Kind
== tok::comment
)
129 } // namespace clangd