Skip to content

[sourcekitd] Replace a slow std::regex with custom parsing #5350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2016
Merged
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
122 changes: 76 additions & 46 deletions lib/IDE/SyntaxModel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include "swift/Parse/Token.h"
#include "swift/Config.h"
#include "swift/Subsystems.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/MemoryBuffer.h"
#include <vector>
Expand Down Expand Up @@ -274,17 +275,6 @@ static const char *const RegexStrURL =
"tn3270|urn|vemmi|wais|xcdoc|z39\\.50r|z39\\.50s)://"
"([a-zA-Z0-9\\-_.]+/)?[a-zA-Z0-9;/?:@\\&=+$,\\-_.!~*'()%#]+";

#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \
#Keyword "|"
static const char *const RegexStrDocCommentField =
"^[ ]*- ("
#include "swift/Markup/SimpleFields.def"
"returns):";

static const char *const RegexStrParameter = "^[ ]?- (parameter) [^:]*:";

static const char *const RegexStrDocCommentParametersHeading = "^[ ]?- (Parameters):";

static const char *const RegexStrMailURL =
"(mailto|im):[a-zA-Z0-9\\-_]+@[a-zA-Z0-9\\-_\\.!%]+";

Expand All @@ -298,7 +288,6 @@ class ModelASTWalker : public ASTWalker {
std::vector<StructureElement> SubStructureStack;
SourceLoc LastLoc;
static const std::regex &getURLRegex(StringRef Protocol);
static const std::regex &getDocCommentRegex(unsigned Index);

Optional<SyntaxNode> parseFieldNode(StringRef Text, StringRef OrigText,
SourceLoc OrigLoc);
Expand Down Expand Up @@ -389,24 +378,6 @@ const std::regex &ModelASTWalker::getURLRegex(StringRef Pro) {
return Regexes[2];
}

const std::regex &ModelASTWalker::getDocCommentRegex(unsigned Index) {
static const std::regex Regexes[3] = {
std::regex {
RegexStrParameter,
std::regex::egrep | std::regex::icase | std::regex::optimize
},
std::regex {
RegexStrDocCommentParametersHeading,
std::regex::egrep | std::regex::icase | std::regex::optimize
},
std::regex {
RegexStrDocCommentField,
std::regex::egrep | std::regex::icase | std::regex::optimize
}
};
return Regexes[Index];
}

SyntaxStructureKind syntaxStructureKindFromNominalTypeDecl(NominalTypeDecl *N) {
if (isa<ClassDecl>(N))
return SyntaxStructureKind::Class;
Expand Down Expand Up @@ -1469,27 +1440,86 @@ bool ModelASTWalker::searchForURL(CharSourceRange Range) {
return true;
}

namespace {
class DocFieldParser {
const char *ptr;
const char *end;

bool advanceIf(char c) {
if (ptr == end || c != *ptr)
return false;
++ptr;
return true;
}
bool advanceIf(llvm::function_ref<bool(char)> predicate) {
if (ptr == end || !predicate(*ptr))
return false;
++ptr;
return true;
}

public:
DocFieldParser(StringRef text) : ptr(text.begin()), end(text.end()) {
assert(text.rtrim().find('\n') == StringRef::npos &&
"expected single line");
}

// Case-insensitively match one of the following patterns:
// ^[ ]?- (parameter) [^:]*:
// ^[ ]?- (Parameters):
// ^[ ]*- (...MarkupSimpleFields.def...|returns):
Optional<StringRef> parseFieldName() {
unsigned numSpaces = 0;
while (advanceIf(' '))
++numSpaces;
if (!advanceIf('-') || !advanceIf(' '))
return None;

if (ptr == end || !clang::isIdentifierBody(*ptr))
return None;
const char *identStart = ptr++;
while (advanceIf([](char c) { return clang::isIdentifierBody(c); }))
;
StringRef ident(identStart, ptr - identStart);

if (ident.equals_lower("parameter")) {
if (numSpaces > 1 || !advanceIf(' '))
return None;
while (advanceIf([](char c) { return c != ':'; }))
;
if (!advanceIf(':'))
return None;
return ident;

} else if (advanceIf(':')) {
if (ident.equals_lower("parameters") && numSpaces > 1)
return None;
auto lowerIdent = ident.lower();
bool isField = llvm::StringSwitch<bool>(lowerIdent)
#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) .Case(#Keyword, true)
#include "swift/Markup/SimpleFields.def"
.Case("parameters", true)
.Case("returns", true)
.Default(false);
if (isField)
return ident;
}

return None;
}
};
} // end anonymous namespace

Optional<SyntaxNode> ModelASTWalker::parseFieldNode(StringRef Text,
StringRef OrigText,
SourceLoc OrigLoc) {
Optional<SyntaxNode> Node;
#ifdef SWIFT_HAVE_WORKING_STD_REGEX
std::match_results<StringRef::iterator> Matches;
for (unsigned i = 0; i != 3; ++i) {
auto &Rx = getDocCommentRegex(i);
bool HadMatch = std::regex_search(Text.begin(), Text.end(), Matches, Rx);
if (HadMatch)
break;
DocFieldParser parser(Text);
if (auto ident = parser.parseFieldName()) {
auto loc = OrigLoc.getAdvancedLoc(ident->data() - OrigText.data());
CharSourceRange range(loc, ident->size());
Node = Optional<SyntaxNode>({SyntaxNodeKind::DocCommentField, range});
}
if (Matches.empty())
return None;

auto &Match = Matches[1];
StringRef MatchStr(Match.first, Match.second - Match.first);
auto Loc = OrigLoc.getAdvancedLoc(MatchStr.data() - OrigText.data());
CharSourceRange Range(Loc, MatchStr.size());
Node = Optional<SyntaxNode>({ SyntaxNodeKind::DocCommentField, Range });
#endif
return Node;
}

Expand Down
30 changes: 30 additions & 0 deletions test/IDE/coloring.swift
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,21 @@ func <#test1#> () {}
///
/// - parameter x: A number
/// - parameter y: Another number
/// - PaRamEteR z-hyphen-q: Another number
/// - parameter : A strange number...
/// - parameternope1: Another number
/// - parameter nope2
/// - parameter: nope3
/// -parameter nope4: Another number
/// * parameter nope5: Another number
/// - parameter nope6: Another number
/// - Parameters: nope7
/// - seealso: yes
/// - seealso: yes
/// - seealso:
/// -seealso: nope
/// - seealso : nope
/// - seealso nope
/// - returns: `x + y`
func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
Expand All @@ -377,6 +392,21 @@ func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number...
// CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3
// CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }

Expand Down