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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
|
//===-------- ConstExtract.cpp -- Gather Compile-Time-Known Values --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
#include "swift/ConstExtract/ConstExtract.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/Evaluator.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/TypeID.h"
#include "swift/ConstExtract/ConstExtractRequests.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include <set>
#include <sstream>
#include <string>
using namespace swift;
namespace {
/// A helper class to collect all nominal type declarations that conform to
/// specific protocols provided as input.
class NominalTypeConformanceCollector : public ASTWalker {
const std::unordered_set<std::string> &Protocols;
std::vector<NominalTypeDecl *> &ConformanceTypeDecls;
public:
NominalTypeConformanceCollector(
const std::unordered_set<std::string> &Protocols,
std::vector<NominalTypeDecl *> &ConformanceDecls)
: Protocols(Protocols), ConformanceTypeDecls(ConformanceDecls) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
PreWalkAction walkToDeclPre(Decl *D) override {
auto *NTD = llvm::dyn_cast<NominalTypeDecl>(D);
if (!NTD)
if (auto *ETD = dyn_cast<ExtensionDecl>(D))
NTD = ETD->getExtendedNominal();
if (NTD)
if (!isa<ProtocolDecl>(NTD) && CheckedDecls.insert(NTD).second) {
if (NTD->getAttrs().hasAttribute<ExtractConstantsFromMembersAttr>()) {
ConformanceTypeDecls.push_back(NTD);
goto visitAuxiliaryDecls;
}
for (auto &Protocol : NTD->getAllProtocols())
if (Protocol->getAttrs()
.hasAttribute<ExtractConstantsFromMembersAttr>() ||
Protocols.count(Protocol->getName().str().str()) != 0) {
ConformanceTypeDecls.push_back(NTD);
goto visitAuxiliaryDecls;
}
}
visitAuxiliaryDecls:
// Visit peers expanded from macros
D->visitAuxiliaryDecls([&](Decl *decl) { decl->walk(*this); },
/*visitFreestandingExpanded=*/false);
return Action::Continue();
}
private:
std::unordered_set<NominalTypeDecl *> CheckedDecls;
};
std::string toFullyQualifiedTypeNameString(const swift::Type &Type) {
std::string TypeNameOutput;
llvm::raw_string_ostream OutputStream(TypeNameOutput);
swift::PrintOptions Options;
Options.FullyQualifiedTypes = true;
Options.PreferTypeRepr = true;
Options.AlwaysDesugarArraySliceTypes = true;
Options.AlwaysDesugarDictionaryTypes = true;
Options.AlwaysDesugarOptionalTypes = true;
Options.PrintTypeAliasUnderlyingType = true;
Options.OpaqueReturnTypePrinting =
PrintOptions::OpaqueReturnTypePrintingMode::WithOpaqueKeyword;
Type.print(OutputStream, Options);
OutputStream.flush();
return TypeNameOutput;
}
std::string toFullyQualifiedProtocolNameString(const swift::ProtocolDecl &Protocol) {
// Protocols cannot be nested in other declarations, so the only fully-qualified
// context is the declaring module name.
return Protocol.getParentModule()->getNameStr().str() + "." + Protocol.getNameStr().str();
}
std::string toMangledTypeNameString(const swift::Type &Type) {
auto PrintingType = Type;
if (Type->hasArchetype())
PrintingType = Type->mapTypeOutOfContext();
return Mangle::ASTMangler().mangleTypeWithoutPrefix(PrintingType->getCanonicalType());
}
} // namespace
namespace swift {
bool
parseProtocolListFromFile(StringRef protocolListFilePath,
DiagnosticEngine &diags,
std::unordered_set<std::string> &protocols) {
// Load the input file.
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(protocolListFilePath);
if (!FileBufOrErr) {
diags.diagnose(SourceLoc(),
diag::const_extract_protocol_list_input_file_missing,
protocolListFilePath);
return false;
}
// Parse a JSON file containing a list of the format:
// [proto1, proto2, proto3]
bool ParseFailed = false;
{
StringRef Buffer = FileBufOrErr->get()->getBuffer();
llvm::SourceMgr SM;
llvm::yaml::Stream S(Buffer, SM);
llvm::yaml::SequenceNode *Sequence =
dyn_cast<llvm::yaml::SequenceNode>(S.begin()->getRoot());
if (Sequence) {
for (auto &ProtocolNameNode : *Sequence) {
auto *ScalarNode = dyn_cast<llvm::yaml::ScalarNode>(&ProtocolNameNode);
if (!ScalarNode) {
ParseFailed = true;
break;
}
auto protocolNameStr = ScalarNode->getRawValue().str();
if (protocolNameStr.front() == '"' && protocolNameStr.back() == '"')
protocolNameStr = protocolNameStr.substr(1, protocolNameStr.size() - 2);
protocols.insert(protocolNameStr);
}
} else
ParseFailed = true;
}
if (ParseFailed) {
diags.diagnose(SourceLoc(),
diag::const_extract_protocol_list_input_file_corrupted,
protocolListFilePath);
return false;
}
return true;
}
static std::shared_ptr<CompileTimeValue> extractCompileTimeValue(Expr *expr);
static std::vector<FunctionParameter>
extractFunctionArguments(const ArgumentList *args) {
std::vector<FunctionParameter> parameters;
for (auto arg : *args) {
auto argExpr = arg.getExpr();
const auto label = arg.getLabel().str().str();
const auto type = argExpr->getType();
if (auto defaultArgument = dyn_cast<DefaultArgumentExpr>(argExpr)) {
auto *decl = defaultArgument->getParamDecl();
if (decl->hasDefaultExpr()) {
argExpr = decl->getTypeCheckedDefaultExpr();
}
} else if (auto optionalInject = dyn_cast<InjectIntoOptionalExpr>(argExpr)) {
argExpr = optionalInject->getSubExpr();
}
parameters.push_back({label, type, extractCompileTimeValue(argExpr)});
}
return parameters;
}
static std::optional<std::string> extractRawLiteral(Expr *expr) {
if (expr) {
switch (expr->getKind()) {
case ExprKind::BooleanLiteral:
case ExprKind::FloatLiteral:
case ExprKind::IntegerLiteral:
case ExprKind::NilLiteral: {
std::string literalOutput;
llvm::raw_string_ostream OutputStream(literalOutput);
expr->printConstExprValue(&OutputStream, nullptr);
if (!literalOutput.empty()) {
return literalOutput;
}
break;
}
case ExprKind::StringLiteral: {
auto stringLiteralExpression = cast<StringLiteralExpr>(expr);
std::string literalOutput;
llvm::raw_string_ostream OutputStream(literalOutput);
OutputStream << stringLiteralExpression->getValue();
return literalOutput;
}
default:
break;
}
}
return std::nullopt;
}
static std::shared_ptr<CompileTimeValue> extractCompileTimeValue(Expr *expr) {
if (expr) {
switch (expr->getKind()) {
case ExprKind::BooleanLiteral:
case ExprKind::FloatLiteral:
case ExprKind::IntegerLiteral:
case ExprKind::NilLiteral:
case ExprKind::StringLiteral: {
auto rawLiteral = extractRawLiteral(expr);
if (rawLiteral.has_value()) {
return std::make_shared<RawLiteralValue>(rawLiteral.value());
}
break;
}
case ExprKind::Array: {
auto arrayExpr = cast<ArrayExpr>(expr);
std::vector<std::shared_ptr<CompileTimeValue>> elementValues;
for (const auto elementExpr : arrayExpr->getElements()) {
elementValues.push_back(extractCompileTimeValue(elementExpr));
}
return std::make_shared<ArrayValue>(elementValues);
}
case ExprKind::Dictionary: {
auto dictionaryExpr = cast<DictionaryExpr>(expr);
std::vector<std::shared_ptr<TupleValue>> tuples;
for (auto elementExpr : dictionaryExpr->getElements()) {
auto elementValue = extractCompileTimeValue(elementExpr);
if (isa<TupleValue>(elementValue.get())) {
tuples.push_back(std::static_pointer_cast<TupleValue>(elementValue));
}
}
return std::make_shared<DictionaryValue>(tuples);
}
case ExprKind::Tuple: {
auto tupleExpr = cast<TupleExpr>(expr);
std::vector<TupleElement> elements;
if (tupleExpr->hasElementNames()) {
for (auto pair : llvm::zip(tupleExpr->getElements(),
tupleExpr->getElementNames())) {
auto elementExpr = std::get<0>(pair);
auto elementName = std::get<1>(pair);
std::optional<std::string> label =
elementName.empty()
? std::nullopt
: std::optional<std::string>(elementName.str().str());
elements.push_back({label, elementExpr->getType(),
extractCompileTimeValue(elementExpr)});
}
} else {
for (auto elementExpr : tupleExpr->getElements()) {
elements.push_back({std::nullopt, elementExpr->getType(),
extractCompileTimeValue(elementExpr)});
}
}
return std::make_shared<TupleValue>(elements);
}
case ExprKind::Call: {
auto callExpr = cast<CallExpr>(expr);
if (callExpr->getFn()->getKind() == ExprKind::ConstructorRefCall) {
std::vector<FunctionParameter> parameters =
extractFunctionArguments(callExpr->getArgs());
return std::make_shared<InitCallValue>(callExpr->getType(), parameters);
}
if (callExpr->getFn()->getKind() == ExprKind::DotSyntaxCall) {
auto dotSyntaxCallExpr = cast<DotSyntaxCallExpr>(callExpr->getFn());
auto fn = dotSyntaxCallExpr->getFn();
if (fn->getKind() == ExprKind::DeclRef) {
auto declRefExpr = cast<DeclRefExpr>(fn);
auto caseName =
declRefExpr->getDecl()->getName().getBaseIdentifier().str().str();
std::vector<FunctionParameter> parameters =
extractFunctionArguments(callExpr->getArgs());
return std::make_shared<EnumValue>(caseName, parameters);
}
}
break;
}
case ExprKind::DotSyntaxCall: {
auto dotSyntaxCallExpr = cast<DotSyntaxCallExpr>(expr);
auto fn = dotSyntaxCallExpr->getFn();
if (fn->getKind() == ExprKind::DeclRef) {
auto declRefExpr = cast<DeclRefExpr>(fn);
auto caseName =
declRefExpr->getDecl()->getName().getBaseIdentifier().str().str();
return std::make_shared<EnumValue>(caseName, std::nullopt);
}
break;
}
case ExprKind::Erasure: {
auto erasureExpr = cast<ErasureExpr>(expr);
return extractCompileTimeValue(erasureExpr->getSubExpr());
}
case ExprKind::Paren: {
auto parenExpr = cast<ParenExpr>(expr);
return extractCompileTimeValue(parenExpr->getSubExpr());
}
case ExprKind::PropertyWrapperValuePlaceholder: {
auto placeholderExpr = cast<PropertyWrapperValuePlaceholderExpr>(expr);
return extractCompileTimeValue(
placeholderExpr->getOriginalWrappedValue());
}
case ExprKind::Coerce: {
auto coerceExpr = cast<CoerceExpr>(expr);
return extractCompileTimeValue(coerceExpr->getSubExpr());
}
case ExprKind::DotSelf: {
auto dotSelfExpr = cast<DotSelfExpr>(expr);
auto dotSelfMetaType = dotSelfExpr->getType()->getAs<AnyMetatypeType>();
if (dotSelfMetaType)
return std::make_shared<TypeValue>(dotSelfMetaType->getInstanceType());
else
break;
}
case ExprKind::UnderlyingToOpaque: {
auto underlyingToOpaque = cast<UnderlyingToOpaqueExpr>(expr);
return extractCompileTimeValue(underlyingToOpaque->getSubExpr());
}
case ExprKind::DefaultArgument: {
auto defaultArgExpr = cast<DefaultArgumentExpr>(expr);
auto *decl = defaultArgExpr->getParamDecl();
// If there is a default expr, we should have looked through to it
assert(!decl->hasDefaultExpr());
switch (decl->getDefaultArgumentKind()) {
case DefaultArgumentKind::NilLiteral:
return std::make_shared<RawLiteralValue>("nil");
case DefaultArgumentKind::EmptyArray:
return std::make_shared<ArrayValue>(
std::vector<std::shared_ptr<CompileTimeValue>>());
case DefaultArgumentKind::EmptyDictionary:
return std::make_shared<DictionaryValue>(
std::vector<std::shared_ptr<TupleValue>>());
default:
break;
}
} break;
case ExprKind::InjectIntoOptional: {
auto injectIntoOptionalExpr = cast<InjectIntoOptionalExpr>(expr);
return extractCompileTimeValue(injectIntoOptionalExpr->getSubExpr());
}
default: {
break;
}
}
}
return std::make_shared<RuntimeValue>();
}
static CustomAttrValue
extractAttributeValue(const CustomAttr *attr) {
std::vector<FunctionParameter> parameters;
if (const auto *args = attr->getArgs()) {
for (auto arg : *args) {
const auto label = arg.getLabel().str().str();
auto argExpr = arg.getExpr();
if (auto defaultArgument = dyn_cast<DefaultArgumentExpr>(argExpr)) {
auto *decl = defaultArgument->getParamDecl();
if (decl->hasDefaultExpr()) {
argExpr = decl->getTypeCheckedDefaultExpr();
}
}
parameters.push_back(
{label, argExpr->getType(), extractCompileTimeValue(argExpr)});
}
}
return {attr, parameters};
}
static AttrValueVector
extractPropertyWrapperAttrValues(VarDecl *propertyDecl) {
AttrValueVector customAttrValues;
for (auto *propertyWrapper : propertyDecl->getAttachedPropertyWrappers())
customAttrValues.push_back(extractAttributeValue(propertyWrapper));
return customAttrValues;
}
static ConstValueTypePropertyInfo
extractTypePropertyInfo(VarDecl *propertyDecl) {
std::optional<AttrValueVector> propertyWrapperValues;
if (propertyDecl->hasAttachedPropertyWrapper())
propertyWrapperValues = extractPropertyWrapperAttrValues(propertyDecl);
if (const auto binding = propertyDecl->getParentPatternBinding()) {
if (const auto originalInit = binding->getInit(0)) {
if (propertyDecl->hasAttachedPropertyWrapper()) {
return {propertyDecl, extractCompileTimeValue(originalInit),
propertyWrapperValues};
}
return {propertyDecl, extractCompileTimeValue(originalInit),
propertyWrapperValues};
}
}
if (auto accessorDecl = propertyDecl->getAccessor(AccessorKind::Get)) {
if (auto body = accessorDecl->getTypecheckedBody()) {
auto node = body->getFirstElement();
if (auto *stmt = node.dyn_cast<Stmt *>()) {
if (stmt->getKind() == StmtKind::Return) {
return {propertyDecl,
extractCompileTimeValue(cast<ReturnStmt>(stmt)->getResult()),
propertyWrapperValues};
}
}
}
}
return {propertyDecl, std::make_shared<RuntimeValue>()};
}
std::optional<std::vector<EnumElementDeclValue>>
extractEnumCases(NominalTypeDecl *Decl) {
if (Decl->getKind() == DeclKind::Enum) {
std::vector<EnumElementDeclValue> Elements;
for (EnumCaseDecl *ECD : cast<EnumDecl>(Decl)->getAllCases()) {
for (EnumElementDecl *EED : ECD->getElements()) {
std::string Name = EED->getNameStr().str();
std::optional<std::string> RawValue =
extractRawLiteral(EED->getRawValueExpr());
std::vector<EnumElementParameterValue> Parameters;
if (const ParameterList *Params = EED->getParameterList()) {
for (const ParamDecl *Parameter : Params->getArray()) {
std::optional<std::string> Label =
Parameter->getParameterName().empty()
? std::nullopt
: std::optional<std::string>(
Parameter->getParameterName().str().str());
Parameters.push_back({Label, Parameter->getInterfaceType()});
}
}
if (Parameters.empty()) {
Elements.push_back({Name, RawValue, std::nullopt});
} else {
Elements.push_back({Name, RawValue, Parameters});
}
}
}
return Elements;
}
return std::nullopt;
}
ConstValueTypeInfo ConstantValueInfoRequest::evaluate(
Evaluator &Evaluator, NominalTypeDecl *Decl,
llvm::PointerUnion<const SourceFile *, ModuleDecl *> extractionScope)
const {
auto shouldExtract = [&](DeclContext *decl) {
if (auto SF = extractionScope.dyn_cast<const SourceFile *>())
return decl->getOutermostParentSourceFile() == SF;
return decl->getParentModule() == extractionScope.get<ModuleDecl *>();
};
std::vector<ConstValueTypePropertyInfo> Properties;
std::optional<std::vector<EnumElementDeclValue>> EnumCases;
// Use 'getStoredProperties' to get lowered lazy and wrapped properties.
// @_objcImplementation extensions might contain stored properties.
auto StoredProperties = Decl->getStoredProperties();
std::unordered_set<VarDecl *> StoredPropertiesSet(StoredProperties.begin(),
StoredProperties.end());
for (auto Property : StoredProperties) {
if (shouldExtract(Property->getDeclContext())) {
Properties.push_back(extractTypePropertyInfo(Property));
}
}
auto extract = [&](class Decl *Member) {
// Ignore plain stored properties collected above,
// instead gather up remaining static and computed properties.
if (auto *VD = dyn_cast<VarDecl>(Member))
if (!StoredPropertiesSet.count(VD))
Properties.push_back(extractTypePropertyInfo(VD));
};
if (shouldExtract(Decl)) {
for (auto Member : Decl->getAllMembers()) {
extract(Member);
}
EnumCases = extractEnumCases(Decl);
}
for (auto Extension: Decl->getExtensions()) {
if (shouldExtract(Extension)) {
for (auto Member : Extension->getAllMembers()) {
extract(Member);
}
}
}
return ConstValueTypeInfo{Decl, Properties, EnumCases};
}
std::vector<ConstValueTypeInfo>
gatherConstValuesForModule(const std::unordered_set<std::string> &Protocols,
ModuleDecl *Module) {
std::vector<ConstValueTypeInfo> Result;
std::vector<NominalTypeDecl *> ConformanceDecls;
NominalTypeConformanceCollector ConformanceCollector(Protocols,
ConformanceDecls);
Module->walk(ConformanceCollector);
// Visit macro expanded extensions
for (auto *FU : Module->getFiles())
if (auto *synthesizedSF = FU->getSynthesizedFile())
for (auto D : synthesizedSF->getTopLevelDecls())
if (isa<ExtensionDecl>(D))
D->walk(ConformanceCollector);
for (auto *CD : ConformanceDecls)
Result.emplace_back(evaluateOrDefault(CD->getASTContext().evaluator,
ConstantValueInfoRequest{CD, Module},
{}));
return Result;
}
std::vector<ConstValueTypeInfo>
gatherConstValuesForPrimary(const std::unordered_set<std::string> &Protocols,
const SourceFile *SF) {
std::vector<ConstValueTypeInfo> Result;
std::vector<NominalTypeDecl *> ConformanceDecls;
NominalTypeConformanceCollector ConformanceCollector(Protocols,
ConformanceDecls);
for (auto D : SF->getTopLevelDecls())
D->walk(ConformanceCollector);
// Visit macro expanded extensions
if (auto *synthesizedSF = SF->getSynthesizedFile())
for (auto D : synthesizedSF->getTopLevelDecls())
if (isa<ExtensionDecl>(D))
D->walk(ConformanceCollector);
for (auto *CD : ConformanceDecls)
Result.emplace_back(evaluateOrDefault(
CD->getASTContext().evaluator, ConstantValueInfoRequest{CD, SF}, {}));
return Result;
}
void writeLocationInformation(llvm::json::OStream &JSON, SourceLoc Loc,
const ASTContext &ctx) {
if (Loc.isInvalid())
return;
JSON.attribute("file", ctx.SourceMgr.getDisplayNameForLoc(Loc));
JSON.attribute("line",
ctx.SourceMgr.getPresumedLineAndColumnForLoc(Loc).first);
}
void writeValue(llvm::json::OStream &JSON,
std::shared_ptr<CompileTimeValue> Value) {
auto value = Value.get();
switch (value->getKind()) {
case CompileTimeValue::ValueKind::RawLiteral: {
JSON.attribute("valueKind", "RawLiteral");
JSON.attribute("value", cast<RawLiteralValue>(value)->getValue());
break;
}
case CompileTimeValue::ValueKind::InitCall: {
auto initCallValue = cast<InitCallValue>(value);
JSON.attribute("valueKind", "InitCall");
JSON.attributeObject("value", [&]() {
JSON.attribute("type",
toFullyQualifiedTypeNameString(initCallValue->getType()));
JSON.attributeArray("arguments", [&] {
for (auto FP : initCallValue->getParameters()) {
JSON.object([&] {
JSON.attribute("label", FP.Label);
JSON.attribute("type", toFullyQualifiedTypeNameString(FP.Type));
writeValue(JSON, FP.Value);
});
}
});
});
break;
}
case CompileTimeValue::ValueKind::Tuple: {
auto tupleValue = cast<TupleValue>(value);
JSON.attribute("valueKind", "Tuple");
JSON.attributeArray("value", [&] {
for (auto TV : tupleValue->getElements()) {
JSON.object([&] {
if (auto Label = TV.Label) {
JSON.attribute("label", Label);
}
JSON.attribute("type", toFullyQualifiedTypeNameString(TV.Type));
writeValue(JSON, TV.Value);
});
}
});
break;
}
case CompileTimeValue::ValueKind::Builder: {
JSON.attribute("valueKind", "Builder");
break;
}
case CompileTimeValue::ValueKind::Dictionary: {
JSON.attribute("valueKind", "Dictionary");
JSON.attributeArray("value", [&] {
for (auto tupleValue : cast<DictionaryValue>(value)->getElements()) {
auto tupleElements = tupleValue.get()->getElements();
JSON.object([&] {
JSON.attributeObject(
"key", [&] { writeValue(JSON, tupleElements[0].Value); });
JSON.attributeObject(
"value", [&] { writeValue(JSON, tupleElements[1].Value); });
});
}
});
break;
}
case CompileTimeValue::ValueKind::Array: {
auto arrayValue = cast<ArrayValue>(value);
JSON.attribute("valueKind", "Array");
JSON.attributeArray("value", [&] {
for (auto CTP : arrayValue->getElements()) {
JSON.object([&] { writeValue(JSON, CTP); });
}
});
break;
}
case CompileTimeValue::ValueKind::Enum: {
auto enumValue = cast<EnumValue>(value);
JSON.attribute("valueKind", "Enum");
JSON.attributeObject("value", [&]() {
JSON.attribute("name", enumValue->getIdentifier());
if (enumValue->getParameters().has_value()) {
auto params = enumValue->getParameters().value();
JSON.attributeArray("arguments", [&] {
for (auto FP : params) {
JSON.object([&] {
JSON.attribute("label", FP.Label);
JSON.attribute("type", toFullyQualifiedTypeNameString(FP.Type));
writeValue(JSON, FP.Value);
});
}
});
}
});
break;
}
case CompileTimeValue::ValueKind::Type: {
auto typeValue = cast<TypeValue>(value);
Type type = typeValue->getType();
JSON.attribute("valueKind", "Type");
JSON.attributeObject("value", [&]() {
JSON.attribute("type",
toFullyQualifiedTypeNameString(type));
JSON.attribute("mangledName",
toMangledTypeNameString(type));
});
break;
}
case CompileTimeValue::ValueKind::Runtime: {
JSON.attribute("valueKind", "Runtime");
break;
}
}
}
void writeAttributeInfo(llvm::json::OStream &JSON,
const CustomAttrValue &AttrVal,
const ASTContext &ctx) {
JSON.object([&] {
JSON.attribute("type",
toFullyQualifiedTypeNameString(AttrVal.Attr->getType()));
writeLocationInformation(JSON, AttrVal.Attr->getLocation(), ctx);
JSON.attributeArray("arguments", [&] {
for (auto FP : AttrVal.Parameters) {
JSON.object([&] {
JSON.attribute("label", FP.Label);
JSON.attribute("type", toFullyQualifiedTypeNameString(FP.Type));
writeValue(JSON, FP.Value);
});
}
});
});
}
void writePropertyWrapperAttributes(
llvm::json::OStream &JSON, std::optional<AttrValueVector> PropertyWrappers,
const ASTContext &ctx) {
if (!PropertyWrappers.has_value()) {
return;
}
JSON.attributeArray("propertyWrappers", [&] {
for (auto PW : PropertyWrappers.value())
writeAttributeInfo(JSON, PW, ctx);
});
}
void writeEnumCases(
llvm::json::OStream &JSON,
std::optional<std::vector<EnumElementDeclValue>> EnumElements) {
if (!EnumElements.has_value()) {
return;
}
JSON.attributeArray("cases", [&] {
for (const auto &Case : EnumElements.value()) {
JSON.object([&] {
JSON.attribute("name", Case.Name);
if (Case.RawValue.has_value()) {
JSON.attribute("rawValue", Case.RawValue.value());
}
if (Case.Parameters.has_value()) {
JSON.attributeArray("parameters", [&] {
for (const auto &Parameter : Case.Parameters.value()) {
JSON.object([&] {
if (auto Label = Parameter.Label) {
JSON.attribute("label", Label);
}
JSON.attribute("type",
toFullyQualifiedTypeNameString(Parameter.Type));
});
}
});
}
});
}
});
}
void writeResultBuilderInformation(llvm::json::OStream &JSON,
const swift::NominalTypeDecl *TypeDecl,
const swift::VarDecl *VarDecl) {
if (auto *attr = VarDecl->getAttachedResultBuilder()) {
JSON.attributeObject("resultBuilder", [&] {
JSON.attribute("type", toFullyQualifiedTypeNameString(attr->getType()));
});
return;
}
for (ProtocolDecl *Decl :
TypeDecl->getLocalProtocols(ConformanceLookupKind::All)) {
// FIXME(noncopyable_generics): Should these be included?
if (Decl->getInvertibleProtocolKind())
continue;
for (auto Member : Decl->getMembers()) {
if (auto *VD = dyn_cast<swift::VarDecl>(Member)) {
if (VD->getName() != VarDecl->getName())
continue;
if (auto *attr = VD->getAttachedResultBuilder()) {
JSON.attributeObject("resultBuilder", [&] {
JSON.attribute("type",
toFullyQualifiedTypeNameString(attr->getType()));
});
}
return;
}
}
}
}
void writeAttrInformation(llvm::json::OStream &JSON,
const DeclAttributes &Attrs) {
auto availableAttr = Attrs.getAttributes<AvailableAttr>();
if (availableAttr.empty())
return;
JSON.attributeArray("availabilityAttributes", [&] {
for (const AvailableAttr *attr : availableAttr) {
JSON.object([&] {
if (!attr->platformString().empty())
JSON.attribute("platform", attr->platformString());
if (!attr->Message.empty())
JSON.attribute("message", attr->Message);
if (!attr->Rename.empty())
JSON.attribute("rename", attr->Rename);
if (attr->Introduced.has_value())
JSON.attribute("introducedVersion",
attr->Introduced.value().getAsString());
if (attr->Deprecated.has_value())
JSON.attribute("deprecatedVersion",
attr->Deprecated.value().getAsString());
if (attr->Obsoleted.has_value())
JSON.attribute("obsoletedVersion",
attr->Obsoleted.value().getAsString());
JSON.attribute("isUnavailable", attr->isUnconditionallyUnavailable());
JSON.attribute("isDeprecated", attr->isUnconditionallyDeprecated());
});
}
});
}
void writeSubstitutedOpaqueTypeAliasDetails(
llvm::json::OStream &JSON, const OpaqueTypeArchetypeType &OpaqueTy) {
auto Signature = OpaqueTy.getDecl()->getOpaqueInterfaceGenericSignature();
JSON.attributeArray("opaqueTypeProtocolRequirements", [&] {
for (const auto Requirement : Signature.getRequirements()) {
// Ignore requirements whose subject type is that of the owner decl
if (!Requirement.getFirstType()->isEqual(OpaqueTy.getInterfaceType()))
continue;
if (Requirement.getKind() != RequirementKind::Conformance)
continue;
// FIXME(noncopyable_generics): Should these be included?
if (Requirement.getProtocolDecl()->getInvertibleProtocolKind())
continue;
JSON.value(
toFullyQualifiedProtocolNameString(*Requirement.getProtocolDecl()));
}
});
JSON.attributeArray("opaqueTypeSameTypeRequirements", [&] {
for (const auto Requirement : Signature.getRequirements()) {
if (Requirement.getKind() == RequirementKind::SameType) {
auto TypeAliasType = Requirement.getFirstType();
auto TypeWitness = Requirement.getSecondType();
JSON.object([&] {
auto TypeAliasName = toFullyQualifiedTypeNameString(TypeAliasType);
if (auto DependentMemberTy =
TypeAliasType->getAs<DependentMemberType>())
if (const auto *Assoc = DependentMemberTy->getAssocType())
TypeAliasName =
toFullyQualifiedProtocolNameString(*Assoc->getProtocol()) +
"." + DependentMemberTy->getName().str().str();
JSON.attribute("typeAliasName", TypeAliasName);
JSON.attribute("substitutedTypeName",
toFullyQualifiedTypeNameString(TypeWitness));
JSON.attribute("substitutedMangledTypeName",
toMangledTypeNameString(TypeWitness));
});
}
}
});
}
void writeAssociatedTypeAliases(llvm::json::OStream &JSON,
const NominalTypeDecl &NomTypeDecl) {
JSON.attributeArray("associatedTypeAliases", [&] {
for (auto &Conformance : NomTypeDecl.getAllConformances()) {
Conformance->forEachTypeWitness(
[&](AssociatedTypeDecl *assoc, Type type, TypeDecl *typeDecl) {
JSON.object([&] {
JSON.attribute("typeAliasName", assoc->getName().str().str());
JSON.attribute("substitutedTypeName",
toFullyQualifiedTypeNameString(type));
JSON.attribute("substitutedMangledTypeName",
toMangledTypeNameString(type));
if (auto OpaqueTy = dyn_cast<OpaqueTypeArchetypeType>(type)) {
writeSubstitutedOpaqueTypeAliasDetails(JSON, *OpaqueTy);
}
});
return false;
});
}
});
}
void writeProperties(llvm::json::OStream &JSON,
const ConstValueTypeInfo &TypeInfo,
const NominalTypeDecl &NomTypeDecl) {
JSON.attributeArray("properties", [&] {
for (const auto &PropertyInfo : TypeInfo.Properties) {
JSON.object([&] {
const auto *decl = PropertyInfo.VarDecl;
JSON.attribute("label", decl->getName().str().str());
JSON.attribute("type", toFullyQualifiedTypeNameString(
decl->getInterfaceType()));
JSON.attribute("mangledTypeName", "n/a - deprecated");
JSON.attribute("isStatic", decl->isStatic() ? "true" : "false");
JSON.attribute("isComputed", !decl->hasStorage() ? "true" : "false");
writeLocationInformation(JSON, decl->getLoc(),
decl->getDeclContext()->getASTContext());
writeValue(JSON, PropertyInfo.Value);
writePropertyWrapperAttributes(JSON, PropertyInfo.PropertyWrappers,
decl->getASTContext());
writeResultBuilderInformation(JSON, &NomTypeDecl, decl);
writeAttrInformation(JSON, decl->getAttrs());
});
}
});
}
void writeConformances(llvm::json::OStream &JSON,
const NominalTypeDecl &NomTypeDecl) {
JSON.attributeArray("conformances", [&] {
for (auto *Conformance : NomTypeDecl.getAllConformances()) {
auto Proto = Conformance->getProtocol();
// FIXME(noncopyable_generics): Should these be included?
if (Proto->getInvertibleProtocolKind())
continue;
JSON.value(toFullyQualifiedProtocolNameString(*Proto));
}
});
}
void writeTypeName(llvm::json::OStream &JSON, const TypeDecl &TypeDecl) {
JSON.attribute("typeName",
toFullyQualifiedTypeNameString(
TypeDecl.getDeclaredInterfaceType()));
JSON.attribute("mangledTypeName",
toMangledTypeNameString(TypeDecl.getDeclaredInterfaceType()));
}
void writeNominalTypeKind(llvm::json::OStream &JSON,
const NominalTypeDecl &NomTypeDecl) {
JSON.attribute(
"kind",
NomTypeDecl.getDescriptiveKindName(NomTypeDecl.getDescriptiveKind())
.str());
}
bool writeAsJSONToFile(const std::vector<ConstValueTypeInfo> &ConstValueInfos,
llvm::raw_ostream &OS) {
llvm::json::OStream JSON(OS, 2);
JSON.array([&] {
for (const auto &TypeInfo : ConstValueInfos) {
assert(isa<NominalTypeDecl>(TypeInfo.TypeDecl) &&
"Expected Nominal Type Decl for a conformance");
const auto *NomTypeDecl = cast<NominalTypeDecl>(TypeInfo.TypeDecl);
const auto SourceLoc =
extractNearestSourceLoc(NomTypeDecl->getInnermostDeclContext());
const auto &Ctx = NomTypeDecl->getInnermostDeclContext()->getASTContext();
JSON.object([&] {
writeTypeName(JSON, *NomTypeDecl);
writeNominalTypeKind(JSON, *NomTypeDecl);
writeLocationInformation(JSON, SourceLoc, Ctx);
writeConformances(JSON, *NomTypeDecl);
writeAssociatedTypeAliases(JSON, *NomTypeDecl);
writeProperties(JSON, TypeInfo, *NomTypeDecl);
writeEnumCases(JSON, TypeInfo.EnumElements);
writeAttrInformation(JSON, NomTypeDecl->getAttrs());
});
}
});
JSON.flush();
return false;
}
} // namespace swift
#define SWIFT_TYPEID_ZONE ConstExtract
#define SWIFT_TYPEID_HEADER "swift/ConstExtract/ConstExtractTypeIDZone.def"
#include "swift/Basic/ImplementTypeIDZone.h"
#undef SWIFT_TYPEID_ZONE
#undef SWIFT_TYPEID_HEADER
// Define request evaluation functions for each of the name lookup requests.
static AbstractRequestFunction *constExtractRequestFunctions[] = {
#define SWIFT_REQUEST(Zone, Name, Sig, Caching, LocOptions) \
reinterpret_cast<AbstractRequestFunction *>(&Name::evaluateRequest),
#include "swift/ConstExtract/ConstExtractTypeIDZone.def"
#undef SWIFT_REQUEST
};
void swift::registerConstExtractRequestFunctions(Evaluator &evaluator) {
evaluator.registerRequestFunctions(Zone::ConstExtract,
constExtractRequestFunctions);
}
|