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 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-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
//
//===----------------------------------------------------------------------===//
@_implementationOnly import _RegexParser
// TODO: Add an expansion level, both from top to bottom.
// After `printAsCanonical` is fleshed out, these two
// printers can call each other. This would enable
// incremental conversion, such that leaves remain
// as canonical regex literals.
/// Renders an AST tree as a Pattern DSL.
///
/// - Parameters:
/// - ast: A `_RegexParser.AST` instance.
/// - maxTopDownLevels: The number of levels down from the root of the tree
/// to perform conversion. `nil` means no limit.
/// - minBottomUpLevels: The number of levels up from the leaves of the tree
/// to perform conversion. `nil` means no limit.
/// - Returns: A string representation of `ast` in the `RegexBuilder` syntax.
@_spi(PatternConverter)
public func renderAsBuilderDSL(
ast: Any,
maxTopDownLevels: Int? = nil,
minBottomUpLevels: Int? = nil
) -> String {
var printer = PrettyPrinter(
maxTopDownLevels: maxTopDownLevels,
minBottomUpLevels: minBottomUpLevels)
printer.printAsPattern(ast as! AST)
return printer.finish()
}
extension PrettyPrinter {
/// If pattern printing should back off, prints the regex literal and returns true
mutating func patternBackoff<T: _TreeNode>(
_ ast: T
) -> Bool {
if let max = maxTopDownLevels, depth >= max {
return true
}
if let min = minBottomUpLevels, ast.height <= min {
return true
}
return false
}
mutating func printBackoff(_ node: DSLTree.Node) {
precondition(node.astNode != nil, "unconverted node")
printAsCanonical(
.init(node.astNode!, globalOptions: nil, diags: Diagnostics()),
delimiters: true)
}
mutating func printAsPattern(_ ast: AST) {
// TODO: Handle global options...
let node = ast.root.dslTreeNode
// If we have any named captures, create references to those above the regex.
let namedCaptures = node.getNamedCaptures()
for namedCapture in namedCaptures {
print("let \(namedCapture) = Reference(Substring.self)")
}
printBlock("Regex") { printer in
printer.printAsPattern(convertedFromAST: node, isTopLevel: true)
}
printInlineMatchingOptions()
}
mutating func printInlineMatchingOptions() {
while !inlineMatchingOptions.isEmpty {
let (options, condition) = popMatchingOptions()
printIndented { printer in
for option in options {
switch option.kind {
case .asciiOnlyDigit:
printer.print(".asciiOnlyDigits(\(condition))")
case .asciiOnlyPOSIXProps:
printer.print(".asciiOnlyCharacterClasses(\(condition))")
case .asciiOnlySpace:
printer.print(".asciiOnlyWhitespace(\(condition))")
case .asciiOnlyWord:
printer.print(".asciiOnlyWordCharacters(\(condition))")
case .caseInsensitive:
printer.print(".ignoresCase(\(condition))")
case .multiline:
printer.print(".anchorsMatchLineEndings(\(condition))")
case .reluctantByDefault:
// This is handled by altering every OneOrMore, etc by changing each
// individual repetition behavior instead of creating a nested regex.
continue
case .singleLine:
printer.print(".dotMatchesNewlines(\(condition))")
default:
break
}
}
}
print("}")
}
}
// FIXME: Use of back-offs like height and depth
// imply that this DSLTree node has a corresponding
// AST. That's not always true, and it would be nice
// to have a non-backing-off pretty-printer that this
// can defer to.
private mutating func printAsPattern(
convertedFromAST node: DSLTree.Node, isTopLevel: Bool = false
) {
if patternBackoff(DSLTree._Tree(node)) {
printBackoff(node)
return
}
switch node {
case let .orderedChoice(a):
printBlock("ChoiceOf") { printer in
a.forEach {
printer.printAsPattern(convertedFromAST: $0)
}
}
case let .concatenation(c):
printConcatenationAsPattern(c, isTopLevel: isTopLevel)
case let .nonCapturingGroup(kind, child):
switch kind.ast {
case .atomicNonCapturing:
printBlock("Local") { printer in
printer.printAsPattern(convertedFromAST: child)
}
case .lookahead:
printBlock("Lookahead") { printer in
printer.printAsPattern(convertedFromAST: child)
}
case .negativeLookahead:
printBlock("NegativeLookahead") { printer in
printer.printAsPattern(convertedFromAST: child)
}
default:
printAsPattern(convertedFromAST: child)
}
case let .capture(name, _, child, _):
var cap = "Capture"
if let n = name {
cap += "(as: \(n))"
}
printBlock(cap) { printer in
printer.printAsPattern(convertedFromAST: child)
}
case let .ignoreCapturesInTypedOutput(child):
printAsPattern(convertedFromAST: child, isTopLevel: isTopLevel)
case .conditional:
print("/* TODO: conditional */")
case let .quantification(amount, kind, child):
let amountStr = amount.ast._patternBase
var kind = kind.ast?._patternBase ?? ""
// If we've updated our quantification behavior, then use that. This
// occurs in scenarios where we use things like '(?U)' to indicate that
// we want reluctant default quantification behavior.
if quantificationBehavior != .eager {
kind = quantificationBehavior._patternBase
}
var blockName = "\(amountStr)(\(kind))"
if kind == ".eager" {
blockName = "\(amountStr)"
}
// Special case single child character classes for repetition nodes.
// This lets us do something like the following:
//
// OneOrMore(.digit)
// vs
// OneOrMore {
// One(.digit)
// }
//
func printAtom(_ pattern: String) {
indent()
if kind != ".eager" {
blockName.removeLast()
output("\(blockName), ")
} else {
output("\(blockName)(")
}
output("\(pattern))")
terminateLine()
}
func printSimpleCCC(
_ ccc: DSLTree.CustomCharacterClass
) {
indent()
if kind != ".eager" {
blockName.removeLast()
output("\(blockName), ")
} else {
output("\(blockName)(")
}
printAsPattern(ccc, wrap: false, terminateLine: false)
output(")")
terminateLine()
}
// We can only do this for Optionally, ZeroOrMore, and OneOrMore. Cannot
// do it right now for Repeat.
if amount.ast.supportsInlineComponent {
switch child {
case let .atom(a):
if let pattern = a._patternBase(&self), pattern.canBeWrapped {
printAtom(pattern.0)
return
}
break
case let .customCharacterClass(ccc):
if ccc.isSimplePrint {
printSimpleCCC(ccc)
return
}
break
case let .convertedRegexLiteral(.atom(a), _):
if let pattern = a._patternBase(&self), pattern.canBeWrapped {
printAtom(pattern.0)
return
}
break
case let .convertedRegexLiteral(.customCharacterClass(ccc), _):
if ccc.isSimplePrint {
printSimpleCCC(ccc)
return
}
break
default:
break
}
}
printBlock(blockName) { printer in
printer.printAsPattern(convertedFromAST: child)
}
case let .atom(a):
if case .unconverted(let a) = a, a.ast.isUnprintableAtom {
print("#/\(a.ast._regexBase)/#")
return
}
if let pattern = a._patternBase(&self) {
if pattern.canBeWrapped {
print("One(\(pattern.0))")
} else {
print(pattern.0)
}
}
case .trivia:
// We never print trivia
break
case .empty:
print("")
case let .quotedLiteral(v):
print(v._quoted)
case let .convertedRegexLiteral(n, _):
// FIXME: This recursion coordinates with back-off
// check above, so it should work out. Need a
// cleaner way to do this. This means the argument
// label is a lie.
printAsPattern(convertedFromAST: n, isTopLevel: isTopLevel)
case let .customCharacterClass(ccc):
printAsPattern(ccc)
case .consumer:
print("/* TODO: consumers */")
case .matcher:
print("/* TODO: consumer validators */")
case .characterPredicate:
print("/* TODO: character predicates */")
case .absentFunction:
print("/* TODO: absent function */")
}
}
enum NodeToPrint {
case dslNode(DSLTree.Node)
case stringLiteral(String)
}
mutating func printAsPattern(_ node: NodeToPrint) {
switch node {
case .dslNode(let n):
printAsPattern(convertedFromAST: n)
case .stringLiteral(let str):
print(str)
}
}
mutating func printConcatenationAsPattern(
_ nodes: [DSLTree.Node], isTopLevel: Bool
) {
// We need to coalesce any adjacent character and scalar elements into a
// string literal, preserving scalar syntax.
let nodes = nodes
.map { NodeToPrint.dslNode($0.lookingThroughConvertedLiteral) }
.coalescing(
with: StringLiteralBuilder(), into: { .stringLiteral($0.result) }
) { literal, node in
guard case .dslNode(let node) = node else { return false }
switch node {
case let .atom(.char(c)):
literal.append(c)
return true
case let .atom(.scalar(s)):
literal.append(unescaped: s._dslBase)
return true
case .quotedLiteral(let q):
literal.append(q)
return true
case .trivia:
// Trivia can be completely ignored if we've already coalesced
// something.
return !literal.isEmpty
default:
return false
}
}
if isTopLevel || nodes.count == 1 {
// If we're at the top level, or we coalesced everything into a single
// element, we don't need to print a surrounding Regex { ... }.
for n in nodes {
printAsPattern(n)
}
return
}
printBlock("Regex") { printer in
for n in nodes {
printer.printAsPattern(n)
}
}
}
mutating func printAsPattern(
_ ccc: DSLTree.CustomCharacterClass,
wrap: Bool = true,
terminateLine: Bool = true
) {
if ccc.hasUnprintableProperty {
printAsRegex(ccc, terminateLine: terminateLine)
return
}
defer {
if ccc.isInverted {
printIndented { printer in
printer.indent()
printer.output(".inverted")
if terminateLine {
printer.terminateLine()
}
}
}
}
// If we only have 1 member, then we can emit it without the extra
// CharacterClass initialization
if ccc.members.count == 1 {
printAsPattern(ccc.members[0], wrap: wrap)
if terminateLine {
self.terminateLine()
}
return
}
var charMembers = StringLiteralBuilder()
// This iterates through all of the character class members collecting all
// of the members who can be stuffed into a singular '.anyOf(...)' vs.
// having multiple. This does alter the original representation, but the
// result is the same. For example:
//
// Convert: '[abc\d\Qxyz\E[:space:]def]'
//
// CharacterClass(
// .anyOf("abcxyzdef"),
// .digit,
// .whitespace
// )
//
// This also allows us to determine if after collecting all of the members
// and stuffing them if we can just emit a standalone '.anyOf' instead of
// initializing a 'CharacterClass'.
let nonCharMembers = ccc.members.filter {
switch $0 {
case let .atom(a):
switch a {
case let .char(c):
charMembers.append(c)
return false
case let .scalar(s):
charMembers.append(unescaped: s._dslBase)
return false
case .unconverted(_):
return true
default:
return true
}
case let .quotedLiteral(s):
charMembers.append(s)
return false
case .trivia(_):
return false
default:
return true
}
}
// Also in the same vein, if we have a few atom members but no
// nonAtomMembers, then we can emit a single .anyOf(...) for them.
if !charMembers.isEmpty, nonCharMembers.isEmpty {
let anyOf = "CharacterClass.anyOf(\(charMembers))"
indent()
if wrap {
output("One(\(anyOf))")
} else {
output(anyOf)
}
if terminateLine {
self.terminateLine()
}
return
}
// Otherwise, use the CharacterClass initialization with multiple members.
print("CharacterClass(")
printIndented { printer in
printer.indent()
if !charMembers.isEmpty {
printer.output(".anyOf(\(charMembers))")
if nonCharMembers.count > 0 {
printer.output(",")
}
printer.terminateLine()
}
for (i, member) in nonCharMembers.enumerated() {
printer.printAsPattern(member, wrap: false)
if i != nonCharMembers.count - 1 {
printer.output(",")
}
printer.terminateLine()
}
}
indent()
output(")")
if terminateLine {
self.terminateLine()
}
}
// TODO: Some way to integrate this with conversion...
mutating func printAsPattern(
_ member: DSLTree.CustomCharacterClass.Member,
wrap: Bool = true
) {
switch member {
case let .custom(ccc):
printAsPattern(ccc, terminateLine: false)
case let .range(lhs, rhs):
if let lhs = lhs._patternBase(&self), let rhs = rhs._patternBase(&self) {
indent()
output("(")
output(lhs.0)
output("...")
output(rhs.0)
output(")")
}
case let .atom(a):
indent()
switch a {
case let .char(c):
if wrap {
output("One(.anyOf(\(String(c)._quoted)))")
} else {
output("CharacterClass.anyOf(\(String(c)._quoted))")
}
case let .scalar(s):
if wrap {
output("One(.anyOf(\(s._dslBase._bareQuoted)))")
} else {
output("CharacterClass.anyOf(\(s._dslBase._bareQuoted))")
}
case let .unconverted(a):
let base = a.ast._patternBase
if base.canBeWrapped, wrap {
output("One(\(base.0))")
} else {
output(base.0)
}
case let .characterClass(cc):
if wrap {
output("One(\(cc._patternBase))")
} else {
output(cc._patternBase)
}
default:
print(" // TODO: Atom \(a)")
}
case .quotedLiteral(let s):
if wrap {
output("One(.anyOf(\(s._quoted)))")
} else {
output("CharacterClass.anyOf(\(s._quoted))")
}
case .trivia(_):
// We never print trivia
break
case .intersection(let first, let second):
if wrap, first.isSimplePrint {
indent()
output("One(")
}
printAsPattern(first, wrap: false)
printIndented { printer in
printer.indent()
printer.output(".intersection(")
printer.printAsPattern(second, wrap: false, terminateLine: false)
printer.output(")")
}
if wrap, first.isSimplePrint {
output(")")
}
case .subtraction(let first, let second):
if wrap, first.isSimplePrint {
indent()
output("One(")
}
printAsPattern(first, wrap: false)
printIndented { printer in
printer.indent()
printer.output(".subtracting(")
printer.printAsPattern(second, wrap: false, terminateLine: false)
printer.output(")")
}
if wrap, first.isSimplePrint {
output(")")
}
case .symmetricDifference(let first, let second):
if wrap, first.isSimplePrint {
indent()
output("One(")
}
printAsPattern(first, wrap: false)
printIndented { printer in
printer.indent()
printer.output(".symmetricDifference(")
printer.printAsPattern(second, wrap: false, terminateLine: false)
printer.output(")")
}
if wrap, first.isSimplePrint {
output(")")
}
}
}
mutating func printAsRegex(
_ ccc: DSLTree.CustomCharacterClass,
asFullRegex: Bool = true,
terminateLine: Bool = true
) {
indent()
if asFullRegex {
output("#/")
}
output("[")
if ccc.isInverted {
output("^")
}
for member in ccc.members {
printAsRegex(member)
}
output("]")
if asFullRegex {
if terminateLine {
print("/#")
} else {
output("/#")
}
}
}
mutating func printAsRegex(_ member: DSLTree.CustomCharacterClass.Member) {
switch member {
case let .custom(ccc):
printAsRegex(ccc, terminateLine: false)
case let .range(lhs, rhs):
output(lhs._regexBase)
output("-")
output(rhs._regexBase)
case let .atom(a):
switch a {
case let .char(c):
output(String(c))
case let .unconverted(a):
output(a.ast._regexBase)
default:
print(" // TODO: Atom \(a)")
}
case .quotedLiteral(let s):
output("\\Q\(s)\\E")
case .trivia(_):
// We never print trivia
break
case .intersection(let first, let second):
printAsRegex(first, asFullRegex: false, terminateLine: false)
output("&&")
printAsRegex(second, asFullRegex: false, terminateLine: false)
case .subtraction(let first, let second):
printAsRegex(first, asFullRegex: false, terminateLine: false)
output("--")
printAsRegex(second, asFullRegex: false, terminateLine: false)
case .symmetricDifference(let first, let second):
printAsRegex(first, asFullRegex: false, terminateLine: false)
output("~~")
printAsRegex(second, asFullRegex: false, terminateLine: false)
}
}
}
extension String {
fileprivate var _escaped: String {
_replacing(#"\"#, with: #"\\"#)._replacing(#"""#, with: #"\""#)
}
fileprivate var _quoted: String {
_escaped._bareQuoted
}
fileprivate var _bareQuoted: String {
#""\#(self)""#
}
}
extension UnicodeScalar {
var _dslBase: String { "\\u{\(String(value, radix: 16, uppercase: true))}" }
}
/// A helper for building string literals, which handles escaping the contents
/// appended.
fileprivate struct StringLiteralBuilder {
private var contents = ""
var result: String { contents._bareQuoted }
var isEmpty: Bool { contents.isEmpty }
mutating func append(_ str: String) {
contents += str._escaped
}
mutating func append(_ c: Character) {
contents += String(c)._escaped
}
mutating func append(unescaped str: String) {
contents += str
}
}
extension StringLiteralBuilder: CustomStringConvertible {
var description: String { result }
}
extension DSLTree.Atom.Assertion {
// TODO: Some way to integrate this with conversion...
var _patternBase: String {
switch self {
case .startOfLine:
return "Anchor.startOfLine"
case .endOfLine:
return "Anchor.endOfLine"
case .caretAnchor:
// The DSL doesn't have an equivalent to this, so print as regex.
return "/^/"
case .dollarAnchor:
// The DSL doesn't have an equivalent to this, so print as regex.
return "/$/"
case .wordBoundary:
return "Anchor.wordBoundary"
case .notWordBoundary:
return "Anchor.wordBoundary.inverted"
case .startOfSubject:
return "Anchor.startOfSubject"
case .endOfSubject:
return "Anchor.endOfSubject"
case .endOfSubjectBeforeNewline:
return "Anchor.endOfSubjectBeforeNewline"
case .textSegment:
return "Anchor.textSegmentBoundary"
case .notTextSegment:
return "Anchor.textSegmentBoundary.inverted"
case .firstMatchingPositionInSubject:
return "Anchor.firstMatchingPositionInSubject"
case .resetStartOfMatch:
return "TODO: Assertion resetStartOfMatch"
}
}
}
extension DSLTree.Atom.CharacterClass {
var _patternBase: String {
switch self {
case .anyGrapheme:
return ".anyGraphemeCluster"
case .digit:
return ".digit"
case .notDigit:
return ".digit.inverted"
case .word:
return ".word"
case .notWord:
return ".word.inverted"
case .horizontalWhitespace:
return ".horizontalWhitespace"
case .notHorizontalWhitespace:
return ".horizontalWhitespace.inverted"
case .newlineSequence:
return ".newlineSequence"
case .notNewline:
return ".newlineSequence.inverted"
case .verticalWhitespace:
return ".verticalWhitespace"
case .notVerticalWhitespace:
return ".verticalWhitespace.inverted"
case .whitespace:
return ".whitespace"
case .notWhitespace:
return ".whitespace.inverted"
case .anyUnicodeScalar:
fatalError("Unsupported")
}
}
}
extension AST.Atom.CharacterProperty {
var isUnprintableProperty: Bool {
switch kind {
case .ascii:
return true
case .binary(let b, value: _):
return isUnprintableBinary(b)
case .generalCategory(let gc):
return isUnprintableGeneralCategory(gc)
case .posix(let p):
return isUnprintablePOSIX(p)
case .script(_), .scriptExtension(_):
return true
default:
return false
}
}
func isUnprintableBinary(_ binary: Unicode.BinaryProperty) -> Bool {
// List out the ones we can print because that list is smaller.
switch binary {
case .whitespace:
return false
default:
return true
}
}
func isUnprintableGeneralCategory(
_ gc: Unicode.ExtendedGeneralCategory
) -> Bool {
// List out the ones we can print because that list is smaller.
switch gc {
case .decimalNumber:
return false
default:
return true
}
}
func isUnprintablePOSIX(_ posix: Unicode.POSIXProperty) -> Bool {
// List out the ones we can print because that list is smaller.
switch posix {
case .xdigit:
return false
case .word:
return false
default:
return true
}
}
}
extension AST.Atom.CharacterProperty {
// TODO: Some way to integrate this with conversion...
var _patternBase: String {
if isUnprintableProperty {
return _regexBase ?? " // TODO: Property \(self)"
}
return _dslBase
}
var _dslBase: String {
switch kind {
case .binary(let bp, _):
switch bp {
case .whitespace:
return ".whitespace"
default:
return ""
}
case .generalCategory(let gc):
switch gc {
case .decimalNumber:
return ".digit"
default:
return ""
}
case .posix(let p):
switch p {
case .xdigit:
return ".hexDigit"
case .word:
return ".word"
default:
return ""
}
default:
return ""
}
}
var _regexBase: String? {
let prefix = isInverted ? "\\P" : "\\p"
switch kind {
case .ascii:
return "[:\(isInverted ? "^" : "")ascii:]"
case .binary(let b, value: let value):
let suffix = value ? "" : "=false"
return "\(prefix){\(b.rawValue)\(suffix)}"
case .generalCategory(let gc):
return "\(prefix){\(gc.rawValue)}"
case .posix(let p):
return "[:\(isInverted ? "^" : "")\(p.rawValue):]"
case .script(let s):
return "[:\(isInverted ? "^" : "")script=\(s.rawValue):]"
case .scriptExtension(let s):
return "[:\(isInverted ? "^" : "")scx=\(s.rawValue):]"
case .any:
return "\(prefix){Any}"
case .assigned:
return "\(prefix){Assigned}"
case .named(let name):
return "\\N{\(name)}"
default:
return nil
}
}
}
extension AST.Atom {
var isUnprintableAtom: Bool {
switch kind {
case .keyboardControl, .keyboardMeta, .keyboardMetaControl:
return true
case .namedCharacter(_):
return true
case .property(let p):
return p.isUnprintableProperty
default:
return false
}
}
}
extension AST.Atom {
/// Base string to use when rendering as a component in a
/// pattern. Note that when the atom is rendered individually,
/// it still may need to be wrapped in quotes.
///
/// TODO: We want to coalesce adjacent atoms, likely in
/// caller, but we might want to be parameterized at that point.
///
/// TODO: Some way to integrate this with conversion...
var _patternBase: (String, canBeWrapped: Bool) {
if let anchor = self.dslAssertionKind {
return (anchor._patternBase, false)
}
if isUnprintableAtom {
return (_regexBase, false)
}
return _dslBase
}
var _dslBase: (String, canBeWrapped: Bool) {
switch kind {
case let .char(c):
return (String(c), false)
case let .scalar(s):
return (s.value._dslBase, false)
case let .scalarSequence(seq):
return (seq.scalarValues.map(\._dslBase).joined(), false)
case let .property(p):
return (p._dslBase, true)
case let .escaped(e):
switch e {
// Anchors
case .wordBoundary:
return ("Anchor.wordBoundary", false)
case .notWordBoundary:
return ("Anchor.wordBoundary.inverted", false)
case .startOfSubject:
return ("Anchor.startOfSubject", false)
case .endOfSubject:
return ("Anchor.endOfSubject", false)
case .endOfSubjectBeforeNewline:
return ("Anchor.endOfSubjectBeforeNewline", false)
case .firstMatchingPositionInSubject:
return ("Anchor.firstMatchingPositionInSubject", false)
case .textSegment:
return ("Anchor.textSegmentBoundary", false)
case .notTextSegment:
return ("Anchor.textSegmentBoundary.inverted", false)
// Character Classes
case .decimalDigit:
return (".digit", true)
case .notDecimalDigit:
return (".digit.inverted", true)
case .horizontalWhitespace:
return (".horizontalWhitespace", true)
case .notHorizontalWhitespace:
return (".horizontalWhitespace.inverted", true)
case .whitespace:
return (".whitespace", true)
case .notWhitespace:
return (".whitespace.inverted", true)
case .wordCharacter:
return (".word", true)
case .notWordCharacter:
return (".word.inverted", true)
case .graphemeCluster:
return (".anyGraphemeCluster", true)
case .newlineSequence:
return (".newlineSequence", true)
case .notNewline:
return (".newlineSequence.inverted", true)
case .verticalTab:
return (".verticalWhitespace", true)
case .notVerticalTab:
return (".verticalWhitespace.inverted", true)
// Literal single characters all get converted into DSLTree.Atom.scalar
default:
return ("TODO: escaped \(e)", false)
}
case .namedCharacter:
return (" /* TODO: named character */", false)
case .dot:
// The DSL does not have an equivalent to '.', print as a regex.
return ("/./", false)
case .caretAnchor, .dollarAnchor:
fatalError("unreachable")
case .backreference:
return (" /* TODO: back reference */", false)
case .subpattern:
return (" /* TODO: subpattern */", false)
case .callout:
return (" /* TODO: callout */", false)
case .backtrackingDirective:
return (" /* TODO: backtracking directive */", false)
case .changeMatchingOptions:
return ("/* TODO: change matching options */", false)
// Every other case we've already decided cannot be represented inside the
// DSL.
default:
return ("", false)
}
}
var _regexBase: String {
switch kind {
case .char, .scalar, .scalarSequence:
return literalStringValue!
case .invalid:
// TODO: Can we recover the original regex text from the source range?
return "<#value#>"
case let .property(p):
return p._regexBase ?? " // TODO: Property \(p)"
case let .escaped(e):
return "\\\(e.character)"
case .keyboardControl(let k):
return "\\c\(k)"
case .keyboardMeta(let k):
return "\\M-\(k)"
case .keyboardMetaControl(let k):
return "\\M-\\C-\(k)"
case .namedCharacter(let n):
return "\\N{\(n)}"
case .dot:
return "."
case .caretAnchor, .dollarAnchor:
fatalError("unreachable")
case .backreference:
return " /* TODO: back reference */"
case .subpattern:
return " /* TODO: subpattern */"
case .callout:
return " /* TODO: callout */"
case .backtrackingDirective:
return " /* TODO: backtracking directive */"
case .changeMatchingOptions:
return "/* TODO: change matching options */"
#if RESILIENT_LIBRARIES
@unknown default:
fatalError()
#endif
}
}
}
extension AST.Atom.Number {
var _patternBase: String {
value.map { "\($0)" } ?? "<#number#>"
}
}
extension AST.Quantification.Amount {
var _patternBase: String {
switch self {
case .zeroOrMore: return "ZeroOrMore"
case .oneOrMore: return "OneOrMore"
case .zeroOrOne: return "Optionally"
case let .exactly(n): return "Repeat(count: \(n._patternBase))"
case let .nOrMore(n): return "Repeat(\(n._patternBase)...)"
case let .upToN(n): return "Repeat(...\(n._patternBase))"
case let .range(n, m): return "Repeat(\(n._patternBase)...\(m._patternBase))"
#if RESILIENT_LIBRARIES
@unknown default: fatalError()
#endif
}
}
var supportsInlineComponent: Bool {
switch self {
case .zeroOrMore: return true
case .oneOrMore: return true
case .zeroOrOne: return true
default: return false
}
}
}
extension AST.Quantification.Kind {
var _patternBase: String {
switch self {
case .eager: return ".eager"
case .reluctant: return ".reluctant"
case .possessive: return ".possessive"
#if RESILIENT_LIBRARIES
@unknown default: fatalError()
#endif
}
}
}
extension DSLTree.QuantificationKind {
var _patternBase: String {
(ast ?? .eager)._patternBase
}
}
extension DSLTree.CustomCharacterClass.Member {
var isUnprintableMember: Bool {
switch self {
case .atom(.unconverted(let a)):
return a.ast.isUnprintableAtom
case .custom(let c):
return c.hasUnprintableProperty
case .range(.unconverted(let lhs), .unconverted(let rhs)):
return lhs.ast.isUnprintableAtom || rhs.ast.isQuantifiable
case .intersection(let first, let second):
return first.hasUnprintableProperty || second.hasUnprintableProperty
case .subtraction(let first, let second):
return first.hasUnprintableProperty || second.hasUnprintableProperty
case .symmetricDifference(let first, let second):
return first.hasUnprintableProperty || second.hasUnprintableProperty
default:
return false
}
}
}
extension DSLTree.CustomCharacterClass {
var hasUnprintableProperty: Bool {
members.contains {
$0.isUnprintableMember
}
}
var isSimplePrint: Bool {
if members.count == 1 {
switch members[0] {
case .intersection(_, _):
return false
case .subtraction(_, _):
return false
case .symmetricDifference(_, _):
return false
default:
return true
}
}
let nonCharMembers = members.filter {
switch $0 {
case let .atom(a):
switch a {
case .char(_):
return false
case .scalar(_):
return false
case .unconverted(_):
return true
default:
return true
}
case .quotedLiteral(_):
return false
case .trivia(_):
return false
default:
return true
}
}
if nonCharMembers.isEmpty {
return true
}
return false
}
}
extension DSLTree.Atom {
func _patternBase(
_ printer: inout PrettyPrinter
) -> (String, canBeWrapped: Bool)? {
switch self {
case .any:
return (".any", true)
case .anyNonNewline:
return (".anyNonNewline", true)
case .dot:
// The DSL does not have an equivalent to '.', print as a regex.
return ("/./", false)
case let .char(c):
return (String(c)._quoted, false)
case let .scalar(s):
let hex = String(s.value, radix: 16, uppercase: true)
return ("\\u{\(hex)}"._bareQuoted, false)
case let .unconverted(a):
if a.ast.isUnprintableAtom {
return ("#/\(a.ast._regexBase)/#", false)
} else {
return a.ast._dslBase
}
case .assertion(let a):
return (a._patternBase, false)
case .characterClass(let cc):
return (cc._patternBase, true)
case .backreference(_):
return ("/* TODO: backreferences */", false)
case .symbolicReference:
return ("/* TODO: symbolic references */", false)
case .changeMatchingOptions(let matchingOptions):
let options: [AST.MatchingOption]
let isAdd: Bool
if matchingOptions.ast.removing.isEmpty {
options = matchingOptions.ast.adding
isAdd = true
} else {
options = matchingOptions.ast.removing
isAdd = false
}
for option in options {
switch option.kind {
case .extended:
// We don't currently support (?x) in the DSL, so if we see it, just
// do nothing.
if options.count == 1 {
return nil
}
case .reluctantByDefault:
if isAdd {
printer.quantificationBehavior = .reluctant
} else {
printer.quantificationBehavior = .eager
}
// Don't create a nested Regex for (?U), we handle this by altering
// every individual repetitionBehavior for things like OneOrMore.
if options.count == 1 {
return nil
}
default:
break
}
}
printer.print("Regex {")
printer.pushMatchingOptions(options, isAdded: isAdd)
}
return nil
}
var _regexBase: String {
switch self {
case .any:
return "(?s:.)"
case .anyNonNewline:
return "(?-s:.)"
case .dot:
return "."
case let .char(c):
return String(c)
case let .scalar(s):
let hex = String(s.value, radix: 16, uppercase: true)
return "\\u{\(hex)}"._bareQuoted
case let .unconverted(a):
return a.ast._regexBase
case .assertion:
return "/* TODO: assertions */"
case .characterClass:
return "/* TODO: character classes */"
case .backreference:
return "/* TODO: backreferences */"
case .symbolicReference:
return "/* TODO: symbolic references */"
case .changeMatchingOptions(let matchingOptions):
var result = ""
for add in matchingOptions.ast.adding {
switch add.kind {
case .reluctantByDefault:
result += "(?U)"
default:
break
}
}
return result
}
}
}
extension DSLTree.Node {
func getNamedCaptures() -> [String] {
var result: [String] = []
switch self {
case .capture(let name?, _, _, _):
result.append(name)
case .concatenation(let nodes):
for node in nodes {
result += node.getNamedCaptures()
}
case .convertedRegexLiteral(let node, _):
result += node.getNamedCaptures()
case .quantification(_, _, let node):
result += node.getNamedCaptures()
default:
break
}
return result
}
}
|