1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
|
//===--- RawComment.cpp - Extraction of raw comments ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements extraction of raw comments.
///
//===----------------------------------------------------------------------===//
#include "swift/AST/RawComment.h"
#include "swift/AST/Comment.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/Module.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Markup/Markup.h"
#include "swift/Parse/Lexer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
static SingleRawComment::CommentKind getCommentKind(StringRef Comment) {
assert(Comment.size() >= 2);
assert(Comment[0] == '/');
if (Comment[1] == '/') {
if (Comment.size() < 3)
return SingleRawComment::CommentKind::OrdinaryLine;
if (Comment[2] == '/') {
return SingleRawComment::CommentKind::LineDoc;
}
return SingleRawComment::CommentKind::OrdinaryLine;
} else {
assert(Comment[1] == '*');
assert(Comment.size() >= 4);
if (Comment[2] == '*') {
return SingleRawComment::CommentKind::BlockDoc;
}
return SingleRawComment::CommentKind::OrdinaryBlock;
}
}
SingleRawComment::SingleRawComment(CharSourceRange Range,
const SourceManager &SourceMgr)
: Range(Range), RawText(SourceMgr.extractText(Range)),
Kind(static_cast<unsigned>(getCommentKind(RawText))) {
ColumnIndent = SourceMgr.getLineAndColumnInBuffer(Range.getStart()).second;
}
SingleRawComment::SingleRawComment(StringRef RawText, unsigned ColumnIndent)
: RawText(RawText), Kind(static_cast<unsigned>(getCommentKind(RawText))),
ColumnIndent(ColumnIndent) {}
/// Converts a range of comments (ordinary or doc) to a \c RawComment with
/// only the last range of doc comments. Gyb comments, ie. "// ###" are skipped
/// entirely as if they did not exist (so two doc comments would still be
/// merged if there was a gyb comment inbetween).
static RawComment toRawComment(ASTContext &Context, CharSourceRange Range) {
if (Range.isInvalid())
return RawComment();
auto &SM = Context.SourceMgr;
unsigned BufferID = SM.findBufferContainingLoc(Range.getStart());
unsigned Offset = SM.getLocOffsetInBuffer(Range.getStart(), BufferID);
unsigned EndOffset = SM.getLocOffsetInBuffer(Range.getEnd(), BufferID);
LangOptions FakeLangOpts;
Lexer L(FakeLangOpts, SM, BufferID, nullptr, LexerMode::Swift,
HashbangMode::Disallowed, CommentRetentionMode::ReturnAsTokens,
Offset, EndOffset);
SmallVector<SingleRawComment, 16> Comments;
Token Tok;
unsigned LastEnd = 0;
while (true) {
L.lex(Tok);
if (Tok.is(tok::eof))
break;
assert(Tok.is(tok::comment));
auto SRC = SingleRawComment(Tok.getRange(), SM);
unsigned Start =
SM.getLineAndColumnInBuffer(Tok.getRange().getStart()).first;
unsigned End = SM.getLineAndColumnInBuffer(Tok.getRange().getEnd()).first;
if (SRC.RawText.back() == '\n')
End--;
if (SRC.isOrdinary()) {
// If there's a regular comment just skip it
LastEnd = End;
continue;
}
// Merge and keep the *last* group, ie. if there's:
// <comment1>
// <whitespace>
// <comment2>
// <comment3>
// Only keep <comment2/3> and group into the one RawComment.
if (!Comments.empty() && Start > LastEnd + 1)
Comments.clear();
Comments.push_back(SRC);
LastEnd = End;
}
RawComment Result;
Result.Comments = Context.AllocateCopy(Comments);
return Result;
}
RawComment RawCommentRequest::evaluate(Evaluator &eval, const Decl *D) const {
auto *DC = D->getDeclContext();
auto &ctx = DC->getASTContext();
// Check the declaration itself.
if (auto *Attr = D->getAttrs().getAttribute<RawDocCommentAttr>())
return toRawComment(ctx, Attr->getCommentRange());
auto *Unit = dyn_cast<FileUnit>(DC->getModuleScopeContext());
if (!Unit)
return RawComment();
switch (Unit->getKind()) {
case FileUnitKind::SerializedAST: {
// First check to see if we have the comment location available in the
// swiftsourceinfo, allowing us to grab it from the original file.
auto *CachedLocs = D->getSerializedLocs();
if (!CachedLocs->DocRanges.empty()) {
SmallVector<SingleRawComment, 4> SRCs;
for (const auto &Range : CachedLocs->DocRanges) {
if (Range.isValid()) {
SRCs.push_back({Range, ctx.SourceMgr});
} else {
// if we've run into an invalid range, don't bother trying to load
// any of the other comments
SRCs.clear();
break;
}
}
if (!SRCs.empty())
return RawComment(ctx.AllocateCopy(llvm::ArrayRef(SRCs)));
}
// Otherwise check to see if we have a comment available in the swiftdoc.
if (auto C = Unit->getCommentForDecl(D))
return C->Raw;
return RawComment();
}
case FileUnitKind::Source:
case FileUnitKind::Builtin:
case FileUnitKind::Synthesized:
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
return RawComment();
}
llvm_unreachable("invalid file kind");
}
RawComment Decl::getRawComment() const {
if (!this->canHaveComment())
return RawComment();
auto &eval = getASTContext().evaluator;
return evaluateOrDefault(eval, RawCommentRequest{this}, RawComment());
}
std::optional<StringRef> Decl::getGroupName() const {
if (hasClangNode())
return std::nullopt;
if (auto *Unit =
dyn_cast<FileUnit>(getDeclContext()->getModuleScopeContext())) {
// We can only get group information from deserialized module files.
return Unit->getGroupNameForDecl(this);
}
return std::nullopt;
}
std::optional<StringRef> Decl::getSourceFileName() const {
if (hasClangNode())
return std::nullopt;
if (auto *Unit =
dyn_cast<FileUnit>(getDeclContext()->getModuleScopeContext())) {
// We can only get group information from deserialized module files.
return Unit->getSourceFileNameForDecl(this);
}
return std::nullopt;
}
std::optional<unsigned> Decl::getSourceOrder() const {
if (hasClangNode())
return std::nullopt;
if (auto *Unit =
dyn_cast<FileUnit>(this->getDeclContext()->getModuleScopeContext())) {
// We can only get source orders from deserialized module files.
return Unit->getSourceOrderForDecl(this);
}
return std::nullopt;
}
CharSourceRange RawComment::getCharSourceRange() {
if (this->isEmpty()) {
return CharSourceRange();
}
auto Start = this->Comments.front().Range.getStart();
if (Start.isInvalid()) {
return CharSourceRange();
}
auto End = this->Comments.back().Range.getEnd();
auto Length = static_cast<const char *>(End.getOpaquePointerValue()) -
static_cast<const char *>(Start.getOpaquePointerValue());
return CharSourceRange(Start, Length);
}
static bool hasDoubleUnderscore(const Decl *D) {
// Exclude decls with double-underscored names, either in arguments or
// base names.
static StringRef Prefix = "__";
// If it's a function or subscript with a parameter with leading
// double underscore, it's a private function or subscript.
if (isa<AbstractFunctionDecl>(D) || isa<SubscriptDecl>(D)) {
auto *params = getParameterList(cast<ValueDecl>(const_cast<Decl *>(D)));
if (params->hasInternalParameter(Prefix))
return true;
}
if (auto *VD = dyn_cast<ValueDecl>(D)) {
auto Name = VD->getBaseName();
if (!Name.isSpecial() && Name.getIdentifier().str().starts_with(Prefix)) {
return true;
}
}
return false;
}
static DocCommentSerializationTarget
getDocCommentSerializationTargetImpl(const Decl *D) {
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
auto *extended = ED->getExtendedNominal();
if (!extended)
return DocCommentSerializationTarget::None;
return getDocCommentSerializationTargetFor(extended);
}
auto *VD = dyn_cast<ValueDecl>(D);
if (!VD)
return DocCommentSerializationTarget::None;
// The use of getEffectiveAccess is unusual here; we want to take the
// testability state into account and emit documentation if and only if they
// are visible to clients (which means public ordinarily, but public+internal
// when testing enabled).
switch (VD->getEffectiveAccess()) {
case AccessLevel::Private:
case AccessLevel::FilePrivate:
case AccessLevel::Internal:
// There's no point serializing anything internal or below, as they are not
// accessible outside their defining module.
return DocCommentSerializationTarget::None;
case AccessLevel::Package:
// Package doc comments can be referenced outside their module, but only
// locally, so can't be included in swiftdoc.
return DocCommentSerializationTarget::SourceInfoOnly;
case AccessLevel::Public:
case AccessLevel::Open:
return DocCommentSerializationTarget::SwiftDocAndSourceInfo;
}
llvm_unreachable("Unhandled case in switch!");
}
DocCommentSerializationTarget
swift::getDocCommentSerializationTargetFor(const Decl *D) {
auto Limit = DocCommentSerializationTarget::SwiftDocAndSourceInfo;
// We can't include SPI decls in swiftdoc.
if (D->isSPI())
Limit = DocCommentSerializationTarget::SourceInfoOnly;
// .swiftdoc doesn't include comments for double underscored symbols, but
// for .swiftsourceinfo, having the source location for these symbols isn't
// a concern because these symbols are in .swiftinterface anyway.
if (hasDoubleUnderscore(D))
Limit = DocCommentSerializationTarget::SourceInfoOnly;
auto Result = getDocCommentSerializationTargetImpl(D);
return std::min(Result, Limit);
}
|