omtcyfz created this revision. This patch introduces cosmetic changes while making ClangD code slightly more LLVM Coding Standards-compliant by
- Convert names of struct fields in Protocol.h from `camelCase` to `CamelCase` - Enclose code in .cpp implementation files in appropriate namespaces instead of doing `using namespace clang; using namespace clangd;` - Putting few `const`s and references where appropriate Testing: $ ninja check-clang-tools All ClangD-related tests are green. https://reviews.llvm.org/D34636 Files: clangd/ClangdLSPServer.cpp clangd/ClangdServer.cpp clangd/ClangdServer.h clangd/ClangdUnit.cpp clangd/ClangdUnit.h clangd/ClangdUnitStore.cpp clangd/DraftStore.cpp clangd/GlobalCompilationDatabase.cpp clangd/JSONRPCDispatcher.cpp clangd/Protocol.cpp clangd/Protocol.h clangd/ProtocolHandlers.cpp clangd/tool/ClangdMain.cpp unittests/clangd/ClangdTests.cpp
Index: unittests/clangd/ClangdTests.cpp =================================================================== --- unittests/clangd/ClangdTests.cpp +++ unittests/clangd/ClangdTests.cpp @@ -139,7 +139,7 @@ // FIXME: severities returned by clangd should have a descriptive // diagnostic severity enum const int ErrorSeverity = 1; - HadError = DiagAndFixIts.Diag.severity == ErrorSeverity; + HadError = DiagAndFixIts.Diag.Severity == ErrorSeverity; } std::lock_guard<std::mutex> Lock(Mutex); @@ -398,7 +398,7 @@ protected: bool ContainsItem(std::vector<CompletionItem> const &Items, StringRef Name) { for (const auto &Item : Items) { - if (Item.insertText == Name) + if (Item.InsertText == Name) return true; } return false; Index: clangd/tool/ClangdMain.cpp =================================================================== --- clangd/tool/ClangdMain.cpp +++ clangd/tool/ClangdMain.cpp @@ -22,7 +22,7 @@ static llvm::cl::opt<bool> RunSynchronously("run-synchronously", - llvm::cl::desc("parse on main thread"), + llvm::cl::desc("Parse code in main thread"), llvm::cl::init(false), llvm::cl::Hidden); int main(int argc, char *argv[]) { Index: clangd/ProtocolHandlers.cpp =================================================================== --- clangd/ProtocolHandlers.cpp +++ clangd/ProtocolHandlers.cpp @@ -11,8 +11,9 @@ #include "ClangdLSPServer.h" #include "ClangdServer.h" #include "DraftStore.h" -using namespace clang; -using namespace clangd; + +namespace clang { +namespace clangd { namespace { @@ -188,7 +189,7 @@ } // namespace -void clangd::regiterCallbackHandlers(JSONRPCDispatcher &Dispatcher, +void regiterCallbackHandlers(JSONRPCDispatcher &Dispatcher, JSONOutput &Out, ProtocolCallbacks &Callbacks) { Dispatcher.registerHandler( @@ -220,3 +221,6 @@ "textDocument/completion", llvm::make_unique<CompletionHandler>(Out, Callbacks)); } + +} // namespace clangd +} // namespace clang Index: clangd/Protocol.h =================================================================== --- clangd/Protocol.h +++ clangd/Protocol.h @@ -31,10 +31,10 @@ struct URI { std::string uri; - std::string file; + std::string File; static URI fromUri(llvm::StringRef uri); - static URI fromFile(llvm::StringRef file); + static URI fromFile(llvm::StringRef Filename); static URI parse(llvm::yaml::ScalarNode *Param); static std::string unparse(const URI &U); @@ -50,36 +50,37 @@ struct Position { /// Line position in a document (zero-based). - int line; + unsigned Line; /// Character offset on a line in a document (zero-based). - int character; + unsigned LineOffset; friend bool operator==(const Position &LHS, const Position &RHS) { - return std::tie(LHS.line, LHS.character) == - std::tie(RHS.line, RHS.character); + return std::tie(LHS.Line, LHS.LineOffset) == + std::tie(RHS.Line, RHS.LineOffset); } + friend bool operator<(const Position &LHS, const Position &RHS) { - return std::tie(LHS.line, LHS.character) < - std::tie(RHS.line, RHS.character); + return std::tie(LHS.Line, LHS.LineOffset) < + std::tie(RHS.Line, RHS.LineOffset); } static llvm::Optional<Position> parse(llvm::yaml::MappingNode *Params); static std::string unparse(const Position &P); }; struct Range { /// The range's start position. - Position start; + Position Start; /// The range's end position. - Position end; + Position End; friend bool operator==(const Range &LHS, const Range &RHS) { - return std::tie(LHS.start, LHS.end) == std::tie(RHS.start, RHS.end); + return std::tie(LHS.Start, LHS.End) == std::tie(RHS.Start, RHS.End); } friend bool operator<(const Range &LHS, const Range &RHS) { - return std::tie(LHS.start, LHS.end) < std::tie(RHS.start, RHS.end); + return std::tie(LHS.Start, LHS.End) < std::tie(RHS.Start, RHS.End); } static llvm::Optional<Range> parse(llvm::yaml::MappingNode *Params); @@ -89,11 +90,11 @@ struct TextEdit { /// The range of the text document to be manipulated. To insert /// text into a document create a range where start === end. - Range range; + Range Range; /// The string to be inserted. For delete operations use an /// empty string. - std::string newText; + std::string NewText; static llvm::Optional<TextEdit> parse(llvm::yaml::MappingNode *Params); static std::string unparse(const TextEdit &P); @@ -104,37 +105,37 @@ URI uri; /// The text document's language identifier. - std::string languageId; + std::string LanguageId; /// The version number of this document (it will strictly increase after each - int version; + int Version; /// The content of the opened text document. - std::string text; + std::string Text; static llvm::Optional<TextDocumentItem> parse(llvm::yaml::MappingNode *Params); }; struct DidOpenTextDocumentParams { /// The document that was opened. - TextDocumentItem textDocument; + TextDocumentItem TextDocument; static llvm::Optional<DidOpenTextDocumentParams> parse(llvm::yaml::MappingNode *Params); }; struct DidCloseTextDocumentParams { /// The document that was closed. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; static llvm::Optional<DidCloseTextDocumentParams> parse(llvm::yaml::MappingNode *Params); }; struct TextDocumentContentChangeEvent { /// The new text of the document. - std::string text; + std::string Text; static llvm::Optional<TextDocumentContentChangeEvent> parse(llvm::yaml::MappingNode *Params); @@ -144,7 +145,7 @@ /// The document that did change. The version number points /// to the version after all provided content changes have /// been applied. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The actual content changes. std::vector<TextDocumentContentChangeEvent> contentChanges; @@ -155,109 +156,109 @@ struct FormattingOptions { /// Size of a tab in spaces. - int tabSize; + unsigned TabSize; /// Prefer spaces over tabs. - bool insertSpaces; + bool InsertSpaces; static llvm::Optional<FormattingOptions> parse(llvm::yaml::MappingNode *Params); static std::string unparse(const FormattingOptions &P); }; struct DocumentRangeFormattingParams { /// The document to format. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The range to format - Range range; + Range FormatRange; /// The format options - FormattingOptions options; + FormattingOptions Options; static llvm::Optional<DocumentRangeFormattingParams> parse(llvm::yaml::MappingNode *Params); }; struct DocumentOnTypeFormattingParams { /// The document to format. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The position at which this request was sent. - Position position; + Position RequestPosition; /// The character that has been typed. - std::string ch; + std::string TypedCharacter; /// The format options. - FormattingOptions options; + FormattingOptions Options; static llvm::Optional<DocumentOnTypeFormattingParams> parse(llvm::yaml::MappingNode *Params); }; struct DocumentFormattingParams { /// The document to format. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The format options - FormattingOptions options; + FormattingOptions Options; static llvm::Optional<DocumentFormattingParams> parse(llvm::yaml::MappingNode *Params); }; struct Diagnostic { /// The range at which the message applies. - Range range; + Range Range; /// The diagnostic's severity. Can be omitted. If omitted it is up to the /// client to interpret diagnostics as error, warning, info or hint. - int severity; + int Severity; /// The diagnostic's message. - std::string message; + std::string Message; friend bool operator==(const Diagnostic &LHS, const Diagnostic &RHS) { - return std::tie(LHS.range, LHS.severity, LHS.message) == - std::tie(RHS.range, RHS.severity, RHS.message); + return std::tie(LHS.Range, LHS.Severity, LHS.Message) == + std::tie(RHS.Range, RHS.Severity, RHS.Message); } friend bool operator<(const Diagnostic &LHS, const Diagnostic &RHS) { - return std::tie(LHS.range, LHS.severity, LHS.message) < - std::tie(RHS.range, RHS.severity, RHS.message); + return std::tie(LHS.Range, LHS.Severity, LHS.Message) < + std::tie(RHS.Range, RHS.Severity, RHS.Message); } static llvm::Optional<Diagnostic> parse(llvm::yaml::MappingNode *Params); }; struct CodeActionContext { /// An array of diagnostics. - std::vector<Diagnostic> diagnostics; + std::vector<Diagnostic> Diagnostics; static llvm::Optional<CodeActionContext> parse(llvm::yaml::MappingNode *Params); }; struct CodeActionParams { /// The document in which the command was invoked. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The range for which the command was invoked. - Range range; + Range Range; /// Context carrying additional information. - CodeActionContext context; + CodeActionContext Context; static llvm::Optional<CodeActionParams> parse(llvm::yaml::MappingNode *Params); }; struct TextDocumentPositionParams { /// The text document. - TextDocumentIdentifier textDocument; + TextDocumentIdentifier TextDocument; /// The position inside the text document. - Position position; + Position Position; static llvm::Optional<TextDocumentPositionParams> parse(llvm::yaml::MappingNode *Params); @@ -307,46 +308,46 @@ struct CompletionItem { /// The label of this completion item. By default also the text that is /// inserted when selecting this completion. - std::string label; + std::string Label; /// The kind of this completion item. Based of the kind an icon is chosen by /// the editor. - CompletionItemKind kind = CompletionItemKind::Missing; + CompletionItemKind Kind = CompletionItemKind::Missing; /// A human-readable string with additional information about this item, like /// type or symbol information. - std::string detail; + std::string Detail; /// A human-readable string that represents a doc-comment. - std::string documentation; + std::string Documentation; /// A string that should be used when comparing this item with other items. /// When `falsy` the label is used. - std::string sortText; + std::string SortText; /// A string that should be used when filtering a set of completion items. /// When `falsy` the label is used. - std::string filterText; + std::string FilterText; /// A string that should be inserted to a document when selecting this /// completion. When `falsy` the label is used. - std::string insertText; + std::string InsertText; /// The format of the insert text. The format applies to both the `insertText` /// property and the `newText` property of a provided `textEdit`. - InsertTextFormat insertTextFormat = InsertTextFormat::Missing; + InsertTextFormat InsertTextFormat = InsertTextFormat::Missing; /// An edit which is applied to a document when selecting this completion. /// When an edit is provided `insertText` is ignored. /// /// Note: The range of the edit must be a single line range and it must /// contain the position at which completion has been requested. - llvm::Optional<TextEdit> textEdit; + llvm::Optional<TextEdit> Edit; /// An optional array of additional text edits that are applied when selecting /// this completion. Edits must not overlap with the main edit nor with /// themselves. - std::vector<TextEdit> additionalTextEdits; + std::vector<TextEdit> AdditionalTextEdits; // TODO(krasimir): The following optional fields defined by the language // server protocol are unsupported: Index: clangd/Protocol.cpp =================================================================== --- clangd/Protocol.cpp +++ clangd/Protocol.cpp @@ -16,10 +16,11 @@ #include "clang/Basic/LLVM.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Format.h" -#include "llvm/Support/raw_ostream.h" #include "llvm/Support/Path.h" -using namespace clang::clangd; +#include "llvm/Support/raw_ostream.h" +namespace clang { +namespace clangd { URI URI::fromUri(llvm::StringRef uri) { URI Result; @@ -31,31 +32,29 @@ if (uri.size() > 2 && uri[0] == '/' && uri[2] == ':') uri.consume_front("/"); // Make sure that file paths are in native separators - Result.file = llvm::sys::path::convert_to_slash(uri); + Result.File = llvm::sys::path::convert_to_slash(uri); return Result; } -URI URI::fromFile(llvm::StringRef file) { +URI URI::fromFile(llvm::StringRef Filename) { using namespace llvm::sys; URI Result; - Result.file = file; + Result.File = Filename; Result.uri = "file://"; // For Windows paths e.g. X: - if (file.size() > 1 && file[1] == ':') + if (Filename.size() > 1 && Filename[1] == ':') Result.uri += "/"; // Make sure that uri paths are with posix separators - Result.uri += path::convert_to_slash(file, path::Style::posix); + Result.uri += path::convert_to_slash(Filename, path::Style::posix); return Result; } URI URI::parse(llvm::yaml::ScalarNode *Param) { llvm::SmallString<10> Storage; return URI::fromUri(Param->getValue(Storage)); } -std::string URI::unparse(const URI &U) { - return U.uri; -} +std::string URI::unparse(const URI &U) { return U.uri; } llvm::Optional<TextDocumentIdentifier> TextDocumentIdentifier::parse(llvm::yaml::MappingNode *Params) { @@ -102,12 +101,12 @@ long long Val; if (llvm::getAsSignedInteger(Value->getValue(Storage), 0, Val)) return llvm::None; - Result.line = Val; + Result.Line = Val; } else if (KeyValue == "character") { long long Val; if (llvm::getAsSignedInteger(Value->getValue(Storage), 0, Val)) return llvm::None; - Result.character = Val; + Result.LineOffset = Val; } else { return llvm::None; } @@ -118,7 +117,7 @@ std::string Position::unparse(const Position &P) { std::string Result; llvm::raw_string_ostream(Result) - << llvm::format(R"({"line": %d, "character": %d})", P.line, P.character); + << llvm::format(R"({"line": %d, "character": %d})", P.Line, P.LineOffset); return Result; } @@ -141,12 +140,12 @@ auto Parsed = Position::parse(Value); if (!Parsed) return llvm::None; - Result.start = std::move(*Parsed); + Result.Start = std::move(*Parsed); } else if (KeyValue == "end") { auto Parsed = Position::parse(Value); if (!Parsed) return llvm::None; - Result.end = std::move(*Parsed); + Result.End = std::move(*Parsed); } else { return llvm::None; } @@ -157,8 +156,8 @@ std::string Range::unparse(const Range &P) { std::string Result; llvm::raw_string_ostream(Result) << llvm::format( - R"({"start": %s, "end": %s})", Position::unparse(P.start).c_str(), - Position::unparse(P.end).c_str()); + R"({"start": %s, "end": %s})", Position::unparse(P.Start).c_str(), + Position::unparse(P.End).c_str()); return Result; } @@ -181,14 +180,14 @@ if (KeyValue == "uri") { Result.uri = URI::parse(Value); } else if (KeyValue == "languageId") { - Result.languageId = Value->getValue(Storage); + Result.LanguageId = Value->getValue(Storage); } else if (KeyValue == "version") { long long Val; if (llvm::getAsSignedInteger(Value->getValue(Storage), 0, Val)) return llvm::None; - Result.version = Val; + Result.Version = Val; } else if (KeyValue == "text") { - Result.text = Value->getValue(Storage); + Result.Text = Value->getValue(Storage); } else { return llvm::None; } @@ -215,12 +214,12 @@ auto Parsed = Range::parse(Map); if (!Parsed) return llvm::None; - Result.range = std::move(*Parsed); + Result.Range = std::move(*Parsed); } else if (KeyValue == "newText") { auto *Node = dyn_cast<llvm::yaml::ScalarNode>(Value); if (!Node) return llvm::None; - Result.newText = Node->getValue(Storage); + Result.NewText = Node->getValue(Storage); } else { return llvm::None; } @@ -231,8 +230,8 @@ std::string TextEdit::unparse(const TextEdit &P) { std::string Result; llvm::raw_string_ostream(Result) << llvm::format( - R"({"range": %s, "newText": "%s"})", Range::unparse(P.range).c_str(), - llvm::yaml::escape(P.newText).c_str()); + R"({"range": %s, "newText": "%s"})", Range::unparse(P.Range).c_str(), + llvm::yaml::escape(P.NewText).c_str()); return Result; } @@ -256,7 +255,7 @@ auto Parsed = TextDocumentItem::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else { return llvm::None; } @@ -283,7 +282,7 @@ auto Parsed = TextDocumentIdentifier::parse(Map); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else { return llvm::None; } @@ -311,7 +310,7 @@ auto Parsed = TextDocumentIdentifier::parse(Map); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "contentChanges") { auto *Seq = dyn_cast<llvm::yaml::SequenceNode>(Value); if (!Seq) @@ -349,7 +348,7 @@ llvm::SmallString<10> Storage; if (KeyValue == "text") { - Result.text = Value->getValue(Storage); + Result.Text = Value->getValue(Storage); } else { return llvm::None; } @@ -377,7 +376,7 @@ long long Val; if (llvm::getAsSignedInteger(Value->getValue(Storage), 0, Val)) return llvm::None; - Result.tabSize = Val; + Result.TabSize = Val; } else if (KeyValue == "insertSpaces") { long long Val; StringRef Str = Value->getValue(Storage); @@ -389,7 +388,7 @@ else return llvm::None; } - Result.insertSpaces = Val; + Result.InsertSpaces = Val; } else { return llvm::None; } @@ -400,7 +399,7 @@ std::string FormattingOptions::unparse(const FormattingOptions &P) { std::string Result; llvm::raw_string_ostream(Result) << llvm::format( - R"({"tabSize": %d, "insertSpaces": %d})", P.tabSize, P.insertSpaces); + R"({"tabSize": %d, "insertSpaces": %d})", P.TabSize, P.InsertSpaces); return Result; } @@ -424,17 +423,17 @@ auto Parsed = TextDocumentIdentifier::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "range") { auto Parsed = Range::parse(Value); if (!Parsed) return llvm::None; - Result.range = std::move(*Parsed); + Result.FormatRange = std::move(*Parsed); } else if (KeyValue == "options") { auto Parsed = FormattingOptions::parse(Value); if (!Parsed) return llvm::None; - Result.options = std::move(*Parsed); + Result.Options = std::move(*Parsed); } else { return llvm::None; } @@ -459,7 +458,7 @@ if (!ScalarValue) return llvm::None; llvm::SmallString<10> Storage; - Result.ch = ScalarValue->getValue(Storage); + Result.TypedCharacter = ScalarValue->getValue(Storage); continue; } @@ -471,17 +470,17 @@ auto Parsed = TextDocumentIdentifier::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "position") { auto Parsed = Position::parse(Value); if (!Parsed) return llvm::None; - Result.position = std::move(*Parsed); + Result.RequestPosition = std::move(*Parsed); } else if (KeyValue == "options") { auto Parsed = FormattingOptions::parse(Value); if (!Parsed) return llvm::None; - Result.options = std::move(*Parsed); + Result.Options = std::move(*Parsed); } else { return llvm::None; } @@ -509,12 +508,12 @@ auto Parsed = TextDocumentIdentifier::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "options") { auto Parsed = FormattingOptions::parse(Value); if (!Parsed) return llvm::None; - Result.options = std::move(*Parsed); + Result.Options = std::move(*Parsed); } else { return llvm::None; } @@ -541,22 +540,22 @@ auto Parsed = Range::parse(Value); if (!Parsed) return llvm::None; - Result.range = std::move(*Parsed); + Result.Range = std::move(*Parsed); } else if (KeyValue == "severity") { auto *Value = dyn_cast_or_null<llvm::yaml::ScalarNode>(NextKeyValue.getValue()); if (!Value) return llvm::None; long long Val; if (llvm::getAsSignedInteger(Value->getValue(Storage), 0, Val)) return llvm::None; - Result.severity = Val; + Result.Severity = Val; } else if (KeyValue == "message") { auto *Value = dyn_cast_or_null<llvm::yaml::ScalarNode>(NextKeyValue.getValue()); if (!Value) return llvm::None; - Result.message = Value->getValue(Storage); + Result.Message = Value->getValue(Storage); } else { return llvm::None; } @@ -588,7 +587,7 @@ auto Parsed = Diagnostic::parse(I); if (!Parsed) return llvm::None; - Result.diagnostics.push_back(std::move(*Parsed)); + Result.Diagnostics.push_back(std::move(*Parsed)); } } else { return llvm::None; @@ -617,17 +616,17 @@ auto Parsed = TextDocumentIdentifier::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "range") { auto Parsed = Range::parse(Value); if (!Parsed) return llvm::None; - Result.range = std::move(*Parsed); + Result.Range = std::move(*Parsed); } else if (KeyValue == "context") { auto Parsed = CodeActionContext::parse(Value); if (!Parsed) return llvm::None; - Result.context = std::move(*Parsed); + Result.Context = std::move(*Parsed); } else { return llvm::None; } @@ -655,12 +654,12 @@ auto Parsed = TextDocumentIdentifier::parse(Value); if (!Parsed) return llvm::None; - Result.textDocument = std::move(*Parsed); + Result.TextDocument = std::move(*Parsed); } else if (KeyValue == "position") { auto Parsed = Position::parse(Value); if (!Parsed) return llvm::None; - Result.position = std::move(*Parsed); + Result.Position = std::move(*Parsed); } else { return llvm::None; } @@ -670,39 +669,42 @@ std::string CompletionItem::unparse(const CompletionItem &CI) { std::string Result = "{"; - llvm::raw_string_ostream Os(Result); + llvm::raw_string_ostream OS(Result); assert(!CI.label.empty() && "completion item label is required"); - Os << R"("label":")" << llvm::yaml::escape(CI.label) << R"(",)"; - if (CI.kind != CompletionItemKind::Missing) - Os << R"("kind":)" << static_cast<int>(CI.kind) << R"(,)"; - if (!CI.detail.empty()) - Os << R"("detail":")" << llvm::yaml::escape(CI.detail) << R"(",)"; - if (!CI.documentation.empty()) - Os << R"("documentation":")" << llvm::yaml::escape(CI.documentation) + OS << R"("label":")" << llvm::yaml::escape(CI.Label) << R"(",)"; + if (CI.Kind != CompletionItemKind::Missing) + OS << R"("kind":)" << static_cast<int>(CI.Kind) << R"(,)"; + if (!CI.Detail.empty()) + OS << R"("detail":")" << llvm::yaml::escape(CI.Detail) << R"(",)"; + if (!CI.Documentation.empty()) + OS << R"("documentation":")" << llvm::yaml::escape(CI.Documentation) << R"(",)"; - if (!CI.sortText.empty()) - Os << R"("sortText":")" << llvm::yaml::escape(CI.sortText) << R"(",)"; - if (!CI.filterText.empty()) - Os << R"("filterText":")" << llvm::yaml::escape(CI.filterText) << R"(",)"; - if (!CI.insertText.empty()) - Os << R"("insertText":")" << llvm::yaml::escape(CI.insertText) << R"(",)"; - if (CI.insertTextFormat != InsertTextFormat::Missing) { - Os << R"("insertTextFormat":")" << static_cast<int>(CI.insertTextFormat) + if (!CI.SortText.empty()) + OS << R"("sortText":")" << llvm::yaml::escape(CI.SortText) << R"(",)"; + if (!CI.FilterText.empty()) + OS << R"("filterText":")" << llvm::yaml::escape(CI.FilterText) << R"(",)"; + if (!CI.InsertText.empty()) + OS << R"("insertText":")" << llvm::yaml::escape(CI.InsertText) << R"(",)"; + if (CI.InsertTextFormat != InsertTextFormat::Missing) { + OS << R"("insertTextFormat":")" << static_cast<int>(CI.InsertTextFormat) << R"(",)"; } - if (CI.textEdit) - Os << R"("textEdit":)" << TextEdit::unparse(*CI.textEdit) << ','; - if (!CI.additionalTextEdits.empty()) { - Os << R"("additionalTextEdits":[)"; - for (const auto &Edit : CI.additionalTextEdits) - Os << TextEdit::unparse(Edit) << ","; - Os.flush(); + if (CI.Edit) + OS << R"("textEdit":)" << TextEdit::unparse(*CI.Edit) << ','; + if (!CI.AdditionalTextEdits.empty()) { + OS << R"("additionalTextEdits":[)"; + for (const auto &Edit : CI.AdditionalTextEdits) + OS << TextEdit::unparse(Edit) << ","; + OS.flush(); // The list additionalTextEdits is guaranteed nonempty at this point. // Replace the trailing comma with right brace. Result.back() = ']'; } - Os.flush(); + OS.flush(); // Label is required, so Result is guaranteed to have a trailing comma. Result.back() = '}'; return Result; } + +} // namespace clangd +} // namespace clang Index: clangd/JSONRPCDispatcher.cpp =================================================================== --- clangd/JSONRPCDispatcher.cpp +++ clangd/JSONRPCDispatcher.cpp @@ -14,8 +14,8 @@ #include "llvm/Support/YAMLParser.h" #include <istream> -using namespace clang; -using namespace clangd; +namespace clang { +namespace clangd { void JSONOutput::writeMessage(const Twine &Message) { llvm::SmallString<128> Storage; @@ -57,15 +57,13 @@ static void callHandler(const llvm::StringMap<std::unique_ptr<Handler>> &Handlers, - llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id, + llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *ID, llvm::yaml::MappingNode *Params, Handler *UnknownHandler) { llvm::SmallString<10> MethodStorage; auto I = Handlers.find(Method->getValue(MethodStorage)); auto *Handler = I != Handlers.end() ? I->second.get() : UnknownHandler; - if (Id) - Handler->handleMethod(Params, Id->getRawValue()); - else - Handler->handleNotification(Params); + return (ID) ? Handler->handleMethod(Params, ID->getRawValue()) + : Handler->handleNotification(Params); } bool JSONRPCDispatcher::call(StringRef Content) const { @@ -102,7 +100,7 @@ if (KeyValue == "jsonrpc") { // This should be "2.0". Always. Version = dyn_cast<llvm::yaml::ScalarNode>(Value); - if (!Version || Version->getRawValue() != "\"2.0\"") + if (!Version || Version->getRawValue() != R"("2.0")") return false; } else if (KeyValue == "method") { Method = dyn_cast<llvm::yaml::ScalarNode>(Value); @@ -132,9 +130,8 @@ return true; } -void clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out, - JSONRPCDispatcher &Dispatcher, - bool &IsDone) { +void runLanguageServerLoop(std::istream &In, JSONOutput &Out, + JSONRPCDispatcher &Dispatcher, bool &IsDone) { while (In.good()) { // A Language Server Protocol message starts with a HTTP header, delimited // by \r\n. @@ -152,6 +149,7 @@ // We allow YAML-style comments. Technically this isn't part of the // LSP specification, but makes writing tests easier. + // FIXME: It's probably worth to reflect that in documentation. if (LineRef.startswith("#")) continue; @@ -189,3 +187,6 @@ } } } + +} // namespace clangd +} // namespace clang Index: clangd/GlobalCompilationDatabase.cpp =================================================================== --- clangd/GlobalCompilationDatabase.cpp +++ clangd/GlobalCompilationDatabase.cpp @@ -12,8 +12,8 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" -using namespace clang::clangd; -using namespace clang; +namespace clang { +namespace clangd { std::vector<tooling::CompileCommand> DirectoryBasedGlobalCompilationDatabase::getCompileCommands(PathRef File) { @@ -63,3 +63,6 @@ // "\n"); return nullptr; } + +} // namespace clangd +} // namespace clang Index: clangd/DraftStore.cpp =================================================================== --- clangd/DraftStore.cpp +++ clangd/DraftStore.cpp @@ -9,8 +9,8 @@ #include "DraftStore.h" -using namespace clang; -using namespace clang::clangd; +namespace clang { +namespace clangd { VersionedDraft DraftStore::getDraft(PathRef File) const { std::lock_guard<std::mutex> Lock(Mutex); @@ -47,3 +47,6 @@ Entry.Draft = llvm::None; return NewVersion; } + +} // namespace clangd +} // namespace clang Index: clangd/ClangdUnitStore.cpp =================================================================== --- clangd/ClangdUnitStore.cpp +++ clangd/ClangdUnitStore.cpp @@ -10,8 +10,8 @@ #include "ClangdUnitStore.h" #include "llvm/Support/Path.h" -using namespace clang::clangd; -using namespace clang; +namespace clang { +namespace clangd { void ClangdUnitStore::removeUnitIfPresent(PathRef File) { std::lock_guard<std::mutex> Lock(Mutex); @@ -22,7 +22,9 @@ OpenedFiles.erase(It); } -std::vector<tooling::CompileCommand> ClangdUnitStore::getCompileCommands(GlobalCompilationDatabase &CDB, PathRef File) { +std::vector<tooling::CompileCommand> +ClangdUnitStore::getCompileCommands(GlobalCompilationDatabase &CDB, + PathRef File) { std::vector<tooling::CompileCommand> Commands = CDB.getCompileCommands(File); if (Commands.empty()) { // Add a fake command line if we know nothing. @@ -32,3 +34,6 @@ } return Commands; } + +} // namespace clangd +} // namespace clang Index: clangd/ClangdUnit.h =================================================================== --- clangd/ClangdUnit.h +++ clangd/ClangdUnit.h @@ -21,6 +21,7 @@ } namespace clang { + class ASTUnit; class PCHContainerOperations; @@ -75,4 +76,5 @@ } // namespace clangd } // namespace clang + #endif Index: clangd/ClangdUnit.cpp =================================================================== --- clangd/ClangdUnit.cpp +++ clangd/ClangdUnit.cpp @@ -15,8 +15,8 @@ #include "clang/Tooling/CompilationDatabase.h" #include "llvm/Support/Format.h" -using namespace clang::clangd; -using namespace clang; +namespace clang { +namespace clangd { ClangdUnit::ClangdUnit(PathRef FileName, StringRef Contents, std::shared_ptr<PCHContainerOperations> PCHs, @@ -143,30 +143,30 @@ for (CodeCompletionString::Chunk C : *CCS) { switch (C.Kind) { case CodeCompletionString::CK_ResultType: - Item.detail = C.Text; + Item.Detail = C.Text; break; case CodeCompletionString::CK_Optional: break; default: - Item.label += C.Text; + Item.Label += C.Text; break; } } assert(CCS->getTypedText()); - Item.kind = getKind(Result.CursorKind); + Item.Kind = getKind(Result.CursorKind); // Priority is a 16-bit integer, hence at most 5 digits. // Since identifiers with higher priority need to come first, // we subtract the priority from 99999. // For example, the sort text of the identifier 'a' with priority 35 // is 99964a. assert(CCS->getPriority() < 99999 && "Expecting code completion result " "priority to have at most " "5-digits"); - llvm::raw_string_ostream(Item.sortText) << llvm::format( + llvm::raw_string_ostream(Item.SortText) << llvm::format( "%05d%s", 99999 - CCS->getPriority(), CCS->getTypedText()); - Item.insertText = Item.filterText = CCS->getTypedText(); + Item.InsertText = Item.FilterText = CCS->getTypedText(); if (CCS->getBriefComment()) - Item.documentation = CCS->getBriefComment(); + Item.Documentation = CCS->getBriefComment(); Items->push_back(std::move(Item)); } } @@ -203,8 +203,8 @@ // CodeComplete seems to require fresh LangOptions. LangOptions LangOpts = Unit->getLangOpts(); // The language server protocol uses zero-based line and column numbers. - // The clang code completion uses one-based numbers. - Unit->CodeComplete(FileName, Pos.line + 1, Pos.character + 1, RemappedSource, + // The Clang code completion uses one-based numbers. + Unit->CodeComplete(FileName, Pos.Line + 1, Pos.LineOffset + 1, RemappedSource, CCO.IncludeMacros, CCO.IncludeCodePatterns, CCO.IncludeBriefComments, Collector, PCHs, *DiagEngine, LangOpts, *SourceMgr, *FileMgr, StoredDiagnostics, @@ -243,8 +243,8 @@ !D->getLocation().getManager().isInMainFile(D->getLocation())) continue; Position P; - P.line = D->getLocation().getSpellingLineNumber() - 1; - P.character = D->getLocation().getSpellingColumnNumber(); + P.Line= D->getLocation().getSpellingLineNumber() - 1; + P.LineOffset= D->getLocation().getSpellingColumnNumber(); Range R = {P, P}; clangd::Diagnostic Diag = {R, getSeverity(D->getLevel()), D->getMessage()}; @@ -261,3 +261,6 @@ void ClangdUnit::dumpAST(llvm::raw_ostream &OS) const { Unit->getASTContext().getTranslationUnitDecl()->dump(OS, true); } + +} // namespace clangd +} // namespace clang Index: clangd/ClangdServer.h =================================================================== --- clangd/ClangdServer.h +++ clangd/ClangdServer.h @@ -112,12 +112,12 @@ /// separate worker thread. /// \p Request is scheduled to be executed before all currently added /// requests. - void addToFront(std::function<void()> Request); + void addToFront(const std::function<void()> &Request); /// Add \p Request to the end of the queue. \p Request will be run on a /// separate worker thread. /// \p Request is scheduled to be executed after all currently added /// requests. - void addToEnd(std::function<void()> Request); + void addToEnd(const std::function<void()> &Request); private: bool RunSynchronously; Index: clangd/ClangdServer.cpp =================================================================== --- clangd/ClangdServer.cpp +++ clangd/ClangdServer.cpp @@ -18,8 +18,8 @@ #include "llvm/Support/raw_ostream.h" #include <future> -using namespace clang; -using namespace clang::clangd; +namespace clang { +namespace clangd { namespace { @@ -35,26 +35,26 @@ } // namespace -size_t clangd::positionToOffset(StringRef Code, Position P) { +size_t positionToOffset(StringRef Code, Position P) { size_t Offset = 0; - for (int I = 0; I != P.line; ++I) { + for (unsigned I = 0; I != P.Line; ++I) { // FIXME: \r\n // FIXME: UTF-8 size_t F = Code.find('\n', Offset); if (F == StringRef::npos) return 0; // FIXME: Is this reasonable? Offset = F + 1; } - return (Offset == 0 ? 0 : (Offset - 1)) + P.character; + return (Offset == 0 ? 0 : (Offset - 1)) + P.LineOffset; } /// Turn an offset in Code into a [line, column] pair. -Position clangd::offsetToPosition(StringRef Code, size_t Offset) { +Position offsetToPosition(StringRef Code, size_t Offset) { StringRef JustBefore = Code.substr(0, Offset); // FIXME: \r\n // FIXME: UTF-8 - int Lines = JustBefore.count('\n'); - int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1; + unsigned Lines = JustBefore.count('\n'); + unsigned Cols = JustBefore.size() - JustBefore.rfind('\n') - 1; return {Lines, Cols}; } @@ -112,7 +112,7 @@ Worker.join(); } -void ClangdScheduler::addToFront(std::function<void()> Request) { +void ClangdScheduler::addToFront(const std::function<void()> &Request) { if (RunSynchronously) { Request(); return; @@ -125,7 +125,7 @@ RequestCV.notify_one(); } -void ClangdScheduler::addToEnd(std::function<void()> Request) { +void ClangdScheduler::addToEnd(const std::function<void()> &Request) { if (RunSynchronously) { Request(); return; @@ -213,8 +213,8 @@ Range Rng) { std::string Code = getDocument(File); - size_t Begin = positionToOffset(Code, Rng.start); - size_t Len = positionToOffset(Code, Rng.end) - Begin; + size_t Begin = positionToOffset(Code, Rng.Start); + size_t Len = positionToOffset(Code, Rng.End) - Begin; return formatCode(Code, File, {tooling::Range(Begin, Len)}); } @@ -264,3 +264,6 @@ }); return DumpFuture.get(); } + +} // namespace clangd +} // namespace clang Index: clangd/ClangdLSPServer.cpp =================================================================== --- clangd/ClangdLSPServer.cpp +++ clangd/ClangdLSPServer.cpp @@ -11,8 +11,8 @@ #include "JSONRPCDispatcher.h" #include "ProtocolHandlers.h" -using namespace clang::clangd; -using namespace clang; +namespace clang { +namespace clangd { namespace { @@ -94,47 +94,46 @@ void ClangdLSPServer::LSPProtocolCallbacks::onDocumentDidOpen( DidOpenTextDocumentParams Params, JSONOutput &Out) { - LangServer.Server.addDocument(Params.textDocument.uri.file, - Params.textDocument.text); + LangServer.Server.addDocument(Params.TextDocument.uri.File, + Params.TextDocument.Text); } void ClangdLSPServer::LSPProtocolCallbacks::onDocumentDidChange( DidChangeTextDocumentParams Params, JSONOutput &Out) { // We only support full syncing right now. - LangServer.Server.addDocument(Params.textDocument.uri.file, - Params.contentChanges[0].text); + LangServer.Server.addDocument(Params.TextDocument.uri.File, + Params.contentChanges[0].Text); } void ClangdLSPServer::LSPProtocolCallbacks::onDocumentDidClose( DidCloseTextDocumentParams Params, JSONOutput &Out) { - LangServer.Server.removeDocument(Params.textDocument.uri.file); + LangServer.Server.removeDocument(Params.TextDocument.uri.File); } void ClangdLSPServer::LSPProtocolCallbacks::onDocumentOnTypeFormatting( DocumentOnTypeFormattingParams Params, StringRef ID, JSONOutput &Out) { - auto File = Params.textDocument.uri.file; + auto File = Params.TextDocument.uri.File; std::string Code = LangServer.Server.getDocument(File); std::string Edits = replacementsToEdits( - Code, LangServer.Server.formatOnType(File, Params.position)); + Code, LangServer.Server.formatOnType(File, Params.RequestPosition)); Out.writeMessage(R"({"jsonrpc":"2.0","id":)" + ID.str() + R"(,"result":[)" + Edits + R"(]})"); } void ClangdLSPServer::LSPProtocolCallbacks::onDocumentRangeFormatting( DocumentRangeFormattingParams Params, StringRef ID, JSONOutput &Out) { - auto File = Params.textDocument.uri.file; + auto File = Params.TextDocument.uri.File; std::string Code = LangServer.Server.getDocument(File); std::string Edits = replacementsToEdits( - Code, LangServer.Server.formatRange(File, Params.range)); - + Code, LangServer.Server.formatRange(File, Params.FormatRange)); Out.writeMessage(R"({"jsonrpc":"2.0","id":)" + ID.str() + R"(,"result":[)" + Edits + R"(]})"); } void ClangdLSPServer::LSPProtocolCallbacks::onDocumentFormatting( DocumentFormattingParams Params, StringRef ID, JSONOutput &Out) { - auto File = Params.textDocument.uri.file; + auto File = Params.TextDocument.uri.File; std::string Code = LangServer.Server.getDocument(File); std::string Edits = replacementsToEdits(Code, LangServer.Server.formatFile(File)); @@ -148,18 +147,18 @@ // We provide a code action for each diagnostic at the requested location // which has FixIts available. std::string Code = - LangServer.Server.getDocument(Params.textDocument.uri.file); + LangServer.Server.getDocument(Params.TextDocument.uri.File); std::string Commands; - for (Diagnostic &D : Params.context.diagnostics) { + for (Diagnostic &D : Params.Context.Diagnostics) { std::vector<clang::tooling::Replacement> Fixes = - LangServer.getFixIts(Params.textDocument.uri.file, D); + LangServer.getFixIts(Params.TextDocument.uri.File, D); std::string Edits = replacementsToEdits(Code, Fixes); if (!Edits.empty()) Commands += - R"({"title":"Apply FixIt ')" + llvm::yaml::escape(D.message) + + R"({"title":"Apply FixIt ')" + llvm::yaml::escape(D.Message) + R"('", "command": "clangd.applyFix", "arguments": [")" + - llvm::yaml::escape(Params.textDocument.uri.uri) + + llvm::yaml::escape(Params.TextDocument.uri.uri) + R"(", [)" + Edits + R"(]]},)"; } @@ -175,9 +174,11 @@ void ClangdLSPServer::LSPProtocolCallbacks::onCompletion( TextDocumentPositionParams Params, StringRef ID, JSONOutput &Out) { - auto Items = LangServer.Server.codeComplete( - Params.textDocument.uri.file, - Position{Params.position.line, Params.position.character}).Value; + auto Items = LangServer.Server + .codeComplete(Params.TextDocument.uri.File, + Position{Params.Position.Line, + Params.Position.LineOffset}) + .Value; std::string Completions; for (const auto &Item : Items) { @@ -232,11 +233,11 @@ DiagnosticToReplacementMap LocalFixIts; // Temporary storage for (auto &DiagWithFixes : Diagnostics) { - auto Diag = DiagWithFixes.Diag; + const auto Diag = DiagWithFixes.Diag; DiagnosticsJSON += - R"({"range":)" + Range::unparse(Diag.range) + - R"(,"severity":)" + std::to_string(Diag.severity) + - R"(,"message":")" + llvm::yaml::escape(Diag.message) + + R"({"range":)" + Range::unparse(Diag.Range) + + R"(,"severity":)" + std::to_string(Diag.Severity) + + R"(,"message":")" + llvm::yaml::escape(Diag.Message) + R"("},)"; // We convert to Replacements to become independent of the SourceManager. @@ -260,3 +261,6 @@ URI::fromFile(File).uri + R"(","diagnostics":[)" + DiagnosticsJSON + R"(]}})"); } + +} // namespace clangd +} // namespace clang
_______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits