Giter Club home page Giter Club logo

swift-syntax's Introduction

Swift Syntax

The swift-syntax package is a set of libraries that work on a source-accurate tree representation of Swift source code, called the SwiftSyntax tree. The SwiftSyntax tree forms the backbone of Swift’s macro system – the macro expansion nodes are represented as SwiftSyntax nodes and a macro generates a SwiftSyntax tree to be inserted into the source file.

Documentation

You can read SwiftSyntax’s documentation on swiftpackageindex.com.

A great way to interactively explore the SwiftSyntax tree of a source file is https://swift-ast-explorer.com, developed by @kishikawakatsumi.

A set of example usages of swift-syntax can be found in Examples.

Releases

Releases of SwiftSyntax are aligned with corresponding language and tooling releases, for example the major version 509 of swift-syntax is aligned with Swift 5.9.

To depend on swift-syntax in a SwiftPM package, add the following to your Package.swift.

dependencies: [
  .package(url: "https://github.com/swiftlang/swift-syntax.git", from: "<#latest swift-syntax tag#>"),
],

To add swift-syntax as a dependency of your Xcode project, go to the Package Dependencies tab of your Xcode project, click the plus button and search for https://github.com/swiftlang/swift-syntax.git.

Reporting Issues

If you should hit any issues while using SwiftSyntax, we appreciate bug reports on GitHub Issue.

Contributing

Start contributing to SwiftSyntax see this guide for more information.

Bazel

SwiftSyntax provides an experimental Bazel build configuration, maintained by Keith Smiley. To use it you can pull the source archive from the relevant release tag into your WORKSPACE and depend on the libraries you need from the BUILD.bazel file. Each library also has an associated Library_opt target (such as SwiftSyntax_opt) which forces SwiftSyntax to always build with optimizations enabled. This may help local runtime performance at the cost of debuggability, and initial build time. Please tag any issues related to the Bazel configuration with the label "Bazel".

License

Please see LICENSE for more information.

swift-syntax's People

Contributors

ahoppen avatar akyrtzi avatar anthonylatsis avatar beccadax avatar bnbarham avatar codafi avatar douggregor avatar evnik avatar flashspys avatar fwcd avatar gottesmm avatar hamishknight avatar harlanhaskins avatar hborla avatar kavon avatar keith avatar kimdv avatar kitasuke avatar ktoso avatar majkfl avatar matejkob avatar meg-gupta avatar natikgadzhi avatar nkcsgexi avatar omochi avatar rintaro avatar sophiapoirier avatar stevapple avatar stevenwong12 avatar ttozzi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift-syntax's Issues

[SR-14392] No such module 'MaterialComponents' only when archiving?

Previous ID SR-14392
Radar None
Original Reporter besart.haxhidema (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s CodeCompletion, Compiler, SwiftSyntax
Labels Bug
Assignee besart.haxhidema (JIRA)
Priority Medium

md5: 632482ec7a801dbde43c2d4492e5168d

Issue Description:

I am trying to archive my app, but I get 'No such module 'MaterialComponents' error. The app runs on simulator and real device.

This is my ppod file:

Uncomment the next line to define a global platform for your project# Uncomment the next line to define a global platform for your project# platform :ios, '10.0'*

Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks!
# Pods for Učiti Engleski

pod 'Firebase/Core'

pod 'Firebase/Database'

pod 'Firebase/Auth'

pod 'Firebase/Crash'

pod 'Google-Mobile-Ads-SDK','~>8.0'

pod 'MaterialComponents/Cards'

pod 'OneSignal', '>= 3.0.0', '< 4.0'
end
target 'OneSignalNotificationServiceExtension' do

#only copy below line use_frameworks!
pod 'OneSignal', '>= 3.0.0', '< 4.0'end

[SR-11827] Missing "in" => bad diagnostic

Previous ID SR-11827
Radar rdar://problem/57418525
Original Reporter @dabrahams
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 29d9832455f9840f7ae31e4c0ca0baec

Issue Description:

  1> (0..<10).map { x
  2.     x + 1
  3. }
error: repl.swift:1:10: error: cannot invoke 'map' with an argument list of type '(@escaping () -> ())'
(0..<10).map { x
         ^

repl.swift:1:10: note: expected an argument list of type '((Self.Element) throws -> T)'
(0..<10).map { x
         ^

I've also seen, "Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored" (small reproducer harder to generate). Either way we should have an error saying "in" is missing and a fixit to insert it.

[SR-9445] InitializerDeclSyntax.initKeyword position is incorrect

Previous ID SR-9445
Radar None
Original Reporter Leitch (JIRA User)
Type Bug
Status Resolved
Resolution Done
Environment

swift-syntax:

0.40200.0

swiftc:

Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Target: x86_64-apple-darwin18.2.0

Xcode:

10.1, Build version 10B61

macOS:

10.14.1

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 12e54c370c6a569e89cec387a15cfe5e

Issue Description:

Given the following code:

class MyFunc {
    init(param: String) {}
}

The position of `initKeyword` returns the incorrect values:

(lldb) po syntax.initKeyword.position
 AbsolutePosition
  - utf8Offset : 14
  - line : 1
  - column : 15

Expected values are:

line: 2

column: 5

offset: 19

[SR-8768] Protect against version mismatch of SwiftSyntax with swift compiler

Previous ID SR-8768
Radar rdar://problem/44522431
Original Reporter @mdiep
Type Bug
Environment

Xcode 10.0.0 beta 6
Apple Swift version 4.2 (swiftlang-1000.0.36 clang-1000.10.44)
Target: x86_64-apple-darwin17.7.0
SwiftSyntax 26b6ef6

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 3399c662150bbbca96a7a1b96f0ead6a

Issue Description:

I get a crash running a visitor over this Swift code:

extension AnyError: LocalizedError {
    public var failureReason: String? {
        return (error as? LocalizedError)?.failureReason
    }
}

Here's the top of the backtrace:

* thread #&#8203;27, queue = 'com.apple.root.user-initiated-qos', stop reason = EXC_BAD_ACCESS (code=2, address=0x70000602ffd8)
    frame #&#8203;0: 0x00000001003526a2 SwiftSyntax`outlined copy of SwiftSyntax.TokenKind + 130
    frame #&#8203;1: 0x00000001003525fd SwiftSyntax`outlined copy of SwiftSyntax.(RawSyntaxData in _387FCEF5221330B5D0404835477A54E9) + 93
    frame #&#8203;2: 0x000000010035cf77 SwiftSyntax`initializeWithCopy for RawSyntax at <compiler-generated>:0
    frame #&#8203;3: 0x000000010139d9c6 libswiftCore.dylib`initializeWithCopy value witness for (extension in Swift):Swift.ClosedRange< where A: Swift.Strideable, A.Stride: Swift.SignedInteger>.Index + 86
    frame #&#8203;4: 0x0000000101122dc3 libswiftCore.dylib`Swift.Array._getElement(_: Swift.Int, wasNativeTypeChecked: Swift.Bool, matchingSubscriptCheck: Swift._DependenceToken) -> A + 83
    frame #&#8203;5: 0x0000000101122cc2 libswiftCore.dylib`Swift.Array.subscript.getter : (Swift.Int) -> A + 130
    frame #&#8203;6: 0x0000000101123727 libswiftCore.dylib`protocol witness for Swift.BidirectionalCollection.subscript.getter : (A.Index) -> A.Element in conformance Swift.Array<A> : Swift.BidirectionalCollection in Swift + 23
    frame #&#8203;7: 0x00000001013c6559 libswiftCore.dylib`protocol witness for Swift.Collection.subscript.getter : (A.Index) -> A.Element in conformance Swift.Array<A> : Swift.Collection in Swift + 9
    frame #&#8203;8: 0x00000001010ec5ee libswiftCore.dylib`(extension in Swift):Swift.Collection.map<A>((A.Element) throws -> A1) throws -> Swift.Array<A1> + 494
  * frame #&#8203;9: 0x0000000100377e17 SwiftSyntax`SyntaxData.init(raw=SwiftSyntax.RawSyntax @ 0x00007000060306c0, indexInParent=0, parent=0x000060c0000e7000, self=0x000060c0000e7b00) at SyntaxData.swift:95
    frame #&#8203;10: 0x0000000100377b77 SwiftSyntax`SyntaxData.__allocating_init(raw:indexInParent:parent:) at SyntaxData.swift:0
    frame #&#8203;11: 0x000000010037886e SwiftSyntax`SyntaxData.realizeChild(index=0, self=0x000060c0000e7000) at SyntaxData.swift:232
    frame #&#8203;12: 0x0000000100378382 SwiftSyntax`closure #&#8203;1 in SyntaxData.cachedChild(self=0x000060c0000e7000, index=0) at SyntaxData.swift:120

[SR-8754] EXC_BAD_ACCESS visiting Swift stdlib interface

Previous ID SR-8754
Radar None
Original Reporter @mdiep
Type Bug

Attachment: Download

Environment

Xcode 10.0.0 beta 6
Apple Swift version 4.2 (swiftlang-1000.0.36 clang-1000.10.44)
Target: x86_64-apple-darwin17.7.0

SwiftSyntax 26b6ef6

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: cc35c21c959ded0f5ad3a888ff9377d7

Issue Description:

I created a bare-bones Visitor and fed it the generated interface that Xcode shows from the Swift stdlib. It crashes here on the last line:

  public func child(at index: Int) -> Syntax? {
    guard raw.layout.indices.contains(index) else { return nil }
    guard let childData = data.cachedChild(at: index) else { return nil }
    return makeSyntax(root: _root, data: childData)
  }

I've attached the generated interface that I'm trying to visit. Since it's the generated interface, it doesn't have definitions for any of the functions. That might be what's causing problems.

But I think this should still work and it definitely shouldn't crash.

[SR-9332] Stack overflow in SwiftSyntax due to deep recursion

Previous ID SR-9332
Radar None
Original Reporter @jpsim
Type Bug
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 46d095af8127f00fe7ff16b9a8489020

Issue Description:

Due to the recursion in SwiftSyntax's SyntaxVisitor, it's easy to trigger a stack overflow due to too much recursive calls. This is especially easy to trigger if you run visitors on multiple threads concurrently, if you compile with a debug configuration or if you run with tsan. For example:

ThreadSanitizer:DEADLYSIGNAL
==720==ERROR: ThreadSanitizer: stack-overflow on address 0x7e8000189b00 (pc 0x00010601afd1 bp 0x7e800018c790 sp 0x7e8000186e50 T10952)
ThreadSanitizer:DEADLYSIGNAL
    #&#8203;0 SyntaxVisitor.visit(_:) SyntaxRewriter.swift:1699 (libSwiftSyntax.dylib:x86_64+0x683fd0)

SUMMARY: ThreadSanitizer: stack-overflow SyntaxRewriter.swift:1699 in SyntaxVisitor.visit(_:)
==720==ABORTING
Received 'abort trap' signal

Example here: realm/SwiftLint#2480

If it would help, I can take some time to create a more focused repro case, just ask.

[SR-14553] Previously unknown syntax is now parsed as AttributedTypeSyntax; not sure if expected

Previous ID SR-14553
Radar rdar://problem/77378237
Original Reporter @allevato
Type Bug
Status Resolved
Resolution Won't Do

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: f6d34be3c638dad74afac4d3f62c9a33

Issue Description:

In swift-format, we were using the following code snippet to test how we handled syntax trees that contained Unknown*Syntax nodes:

{{ @unknown foo class Bar {}}}

At some point fairly recently in main (I'm using the 2021-04-26 development snapshot), the parser behavior changed and it now parses this as valid; the result is two CodeBlockItems:

  1. a TypeExpr containing the AttributedType @unknown foo

  2. the ClassDecl class Bar {}

Something similar happens with a malformed @unknown default:

{{ switch a {}}
{{ case x: break}}
{{ @unknown foo default: break}}
{{ }}}

This body of case x is parsed as two CodeBlockItems (break, then @unknown foo), and then the next SwitchCase starts at the default.

Are these changes expected?

To reproduce:

  1. Download the attached project.

  2. Use a development toolchain that is syntax-compatible with swift-syntax's main branch (at the time I'm writing this, 2021-04-26 worked).

  3. Run swift run UnknownAttr.

  4. Observe the tree output.

[SR-11287] memory leak in code completion

Previous ID SR-11287
Radar None
Original Reporter @marcrasi
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Source Tooling, SwiftSyntax
Labels Bug
Assignee @rintaro
Priority Medium

md5: c6d1c2bd64fda68f9aeb152794a9724e

Issue Description:

On Ubuntu 18.04, at commit c43eb9b (~noon Aug 9 HEAD), I'm getting memory leaks when doing code completion. To reproduce,

  1. swift/utils/build-script --release --enable-lsan --debug-swift-stdlib

  2. llvm/utils/lit/lit.py build/Ninja-ReleaseAssert+stdlib-DebugAssert/swift-linux-x86_64/test-linux-x86_64/IDE/complete_repl_identifier_prefix_1.swift -a

LSAN should print out leaks. Here's what I get: https://gist.github.com/marcrasi/7d1f5e5766833c605b92873687eb49ca

This does not occur at commit 482d062 and does occur at commit 1a211e6, so I suspect that swiftlang/swift#26403 caused it.

[SR-10024] Add new TokenKinds for contextual keyword in libSyntax/SwiftSyntax

Previous ID SR-10024
Radar None
Original Reporter kitasuke (JIRA User)
Type Improvement

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s Compiler, SwiftSyntax
Labels Improvement
Assignee None
Priority Medium

md5: f6a7999be8142907c0d76093517b06c8

Issue Description:

All contextual keyword's token kind is `identifier` for now, but I would like to have them as keyword kind instead.

For example, I was expecting to have `weakKeyword` for below variable declaration, but I got `identifier("weak")` in SwiftSyntax. In this context, it can tell keyword, not identifier.

Same thing happens to other contextual keywords as well.

@IBOutlet private weak var button: UIButton!

Sample code:

// sample.swift
class View {
 @IBOutlet private weak var button: UIButton!
}
 $swiftc -frontend -emit-syntax sample.swift  

Expected:

"tokenKind":{"kind":"kw_weak"} 

Actual:

"tokenKind":{"kind":"identifier","text":"weak"}

Environment:

Xcode 10.2 beta 3 (10P99q)

Apple Swift version 5.0 (swiftlang-1001.0.63.8 clang-1001.0.43)
Target: x86_64-apple-darwin18.2.0

[SR-10174] Childen of a MemberDeclListSyntax are no longer typed

Previous ID SR-10174
Radar None
Original Reporter @Jeehut
Type Bug
Environment

Xcode 10.2, macOS 10.14.3.

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 308b17bfa083679803f5f2d92c489f53

Issue Description:

In the Swift 4.2 release, childen of a `MemberDeclListSyntax` type were typed, thus the following code was working:

let enumCaseDeclarations: [EnumCaseDeclSyntax] = enumDeclaration.members.members.children.compactMap { $0 as? EnumCaseDeclSyntax }

But after updating to Xcode 10.2 today, which includes the Swift 5.0 release, all `children` members are of type `Syntax` and casting to `EnumCaseDeclSyntax` fails, although that's the type I'm expecting here. You can find an example Swift file being parsed here.

Why was this API changed to be less informative? And how am I supposed to cast it to the appropriate type going forward with the 5.0 release?

It would be great to get feedback soon, so I can make a Xcode 10.2 compatible release of my tool BartyCrouch. See also the appropriate line here.

Thank you for your help in advance!

[SR-9038] Swift Syntax requires the use of dynamic linking

Previous ID SR-9038
Radar None
Original Reporter tannernelson (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 4
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 9bbab7716cc05fa62a1f9472abf24ed4

Issue Description:

Currently Swift Syntax vends a dynamic product (https://github.com/apple/swift-syntax/blob/master/Package.swift#L8).

This creates issues when trying to link a static executable that uses Swift Syntax. Is there any way this could be changed to a normal product?

[SR-12972] SourceLocationConverter initializer that accepts a SourceFileSyntax is slower than the String version

Previous ID SR-12972
Radar rdar://problem/64230275
Original Reporter dylansturg (JIRA User)
Type Bug

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 4656fb002ec2b67ed48c8aa22d56eebf

Issue Description:

SourceLocationConverter has 2 initializers, one uses a String and the other uses a SourceFileSyntax. Based on my testing, the String based initializer is noticeably faster than using a SourceFileSyntax.

For a test case, I selected a relatively large file from swift-syntax (~ 10k LOC). The initializer that accepts a string takes ~ 2ms while the other initializer takes ~ 70 ms.

[SR-14564] "\(Self.self)" causes issue on Xcode 12.5 when Swift is optimized

Previous ID SR-14564
Radar rdar://problem/77465728
Original Reporter matteolongeri_ovolab (JIRA User)
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 1
Component/s Compiler, SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 4cc049e4929f10d973d6a2409610d84f

Issue Description:

Using Xcode 12.5 I have identified an issue with this instruction "(Self.self)" when it runs on a build created setting SWIFT_OPTIMIZATION_LEVEL to -O (Optimize for speed).

The instruction above is executed in a superclass (subclass of UIView) when it to load a NIB:

Bundle.main.loadNibNamed("\(Self.self)", owner: self, options: nil)

Instead of getting the right subclass name, it simply returns "Self" and this generate the following error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: '...' with name 'Self''

This never happens before with previous versions of Xcode, and it still does not happen when the build is generate without using optimization -Onone.

To fix it I have changed "(Self.self)" with "(type(of: self))". This way it works, but I think that it should be investigate why the original version causes that kind of issue when Swift is optimized.

Forcing optimization in Debug, I was able to reproduce the issue. I have also tried to insert a breakpoint before the crash, trying to execute the instruction in Console with po command, but it works as expected, printing the right class name.

[SR-10241] A way to get raw string without quotes from StringLiteralExprSyntax

Previous ID SR-10241
Radar None
Original Reporter kitasuke (JIRA User)
Type Improvement
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Improvement
Assignee kitasuke (JIRA)
Priority Medium

md5: 0345f8455f9bcaa284679f0dc943b32a

relates to:

  • SR-10469 Unknown syntax for interpolated string literal

Issue Description:

Background
I would like to have a better way to extract raw string without quotes from `StringLiteralExprSyntax`. `StringInterpolationExprSyntax` looks well-organized because its cursor has openQuote, segments and closeQuote to express strings and quotes separately.

My proposal

Can we have quotes in children of StringLiteralExpr like StringInterpolationExpr?
https://github.com/apple/swift/blob/c04a7dec9f739fbe53f3c305a32e8d426972bfd8/utils/gyb_syntax_support/ExprNodes.py#L266:L269

https://github.com/apple/swift/blob/c04a7dec9f739fbe53f3c305a32e8d426972bfd8/utils/gyb_syntax_support/ExprNodes.py#L468:L481

References

Data structures and examples are below.

public struct StringLiteralExprSyntax: ExprSyntax, _SyntaxBase, Hashable {
  enum Cursor: Int {
    case stringLiteral
  }
}
// let foo = "foo"
print(node.stringLiteral.text) // "\"foo\""
public struct StringInterpolationExprSyntax: ExprSyntax, _SyntaxBase, Hashable {
  enum Cursor: Int {
    case openQuote
    case segments
    case closeQuote
  }
}
// let foo = "foo \(bar)"
print((node.segments[0] as! StringSegmentSyntax).content.text) // "foo"

[SR-9797] Not implement function for SyntaxFactory.makeEllipsisToken.

Previous ID SR-9797
Radar None
Original Reporter bannzai (JIRA User)
Type Improvement
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Improvement
Assignee bannzai (JIRA)
Priority Medium

md5: 2a00ca60247bc485f93bc0c58cae863f

Issue Description:

I want to develop about function decleare syntax rewriter library and I found withEllipsis(_🙂 function under the FunctionParameterSyntax and I want to use this function.

But I can not find `SyntaxFactory.makeEllipsisToken` like `SyntaxFactory.makeCommaToken`. It means can not set new ellipsis token. I confirmed that generated of swift syntax code. . But I did not get that insntanciate token of ellipsis function.

Environment

SwiftSyntax Xcode swiftc
swift-4.2-RELEASE 0.40200.0 Version 10.1 (10B61) Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)

[SR-13619] Using SwiftSyntax to parse a definition file, results in unknown declarations

Previous ID SR-13619
Radar rdar://problem/69701608
Original Reporter swiftuilab (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 57f6cbe2a43f7ef6bb506bf778d15230

Issue Description:

Not sure if this is a bug, or a feature request, so I'm filing it as a bug for the moment.

I am using SwiftSyntax to parse a definition file (to be clear, I'm talking about the file generated by Xcode when you right click on a symbol and select "jump to definition").

For example, a stripped-down piece of the SwiftUI definition file looks like this:

public struct Binding<Value> {
  public var wrappedValue: Value { get nonmutating set }
  public var projectedValue: Binding<Value> { get }
}

The projectedValue variable is properly parsed as VariableDeclSyntax, but wrappedValue is parsed as UnknownDeclSyntax. The "set" part is what makes SwiftSyntax to not detect a variable.

This makes sense in a way, as that is not a valid syntax to use while writing code. However, in the context of the definition file it is ok. The color coding in Xcode also provides a hint, as the "nonmutating set" shows uncolored.

I tried to dig a little more, but I think the problem (if it is such), resides in the lib_InternalSwiftSyntaxParser.dylib library.

[SR-9710] Return `trailing comma` value when access to `FunctionParameterSyntax.ellipsis`.

Previous ID SR-9710
Radar rdar://problem/43690589
Original Reporter bannzai (JIRA User)
Type Bug
Status Resolved
Resolution Done
Environment
SwiftSyntax Xcode swiftc
swift-4.2-RELEASE 0.40200.0 Version 10.1 (10B61) Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Additional Detail from JIRA
Votes 1
Component/s SwiftSyntax
Labels Bug
Assignee bannzai (JIRA)
Priority Medium

md5: 6edd4f723170e810db835d1b3fdd1401

Issue Description:

When FunctionParameterSyntax.ellipsis property access, It returned wrong token about `tokenKind.kind == "comma"`.
You can check problem with after exec SwiftSyntax-issue-ellipsis.
And It can check result SwiftSyntax-issue-ellipsis repository's README.

SwiftSyntax-issue-ellipsis: https://github.com/omochi/SwiftSyntax-issue-ellipsis/blob/master/Sources/SwiftSyntax-issue-ellipsis/main.swift

Result

ccc: Int, 
---ellipsis---
TokenSyntax
, 
---
no trailing comma
Program ended with exit code: 0

So, I access `ellipsis`(...), But I got `comma`(,) token.

And I confirmed more case for $ swiftc -emit-syntax swift-syntax-source.swift result json.
It estimates in the specifity range in gist.

I guess that expected order of layout.

Cursor value
Attributes null
FirstName argument1
SecondName null
Colon :
Type Int
Ellipsis null
DefaultArgument null
TrailingComma ,

But I got

Cursor value
Attributes null
FirstName argument1
SecondName null
Colon :
Type Int
Ellipsis ,
DefaultArgument null
TrailingComma null

So, `Elilpsis=,` and `TrailingComma=null` are wrong result.

[SR-9616] SwiftSyntax is not following trivia rule

Previous ID SR-9616
Radar None
Original Reporter inamiy (JIRA User)
Type Bug

Attachment: Download

Environment
Additional Detail from JIRA
Votes 0
Component/s Compiler, SwiftSyntax
Labels Bug, Parser, Syntax
Assignee None
Priority Medium

md5: b19e5c1a45f2ad0872b99a66f9211c27

relates to:

  • SR-2373 Trailing doc comment should not be attached to the next declaration

Issue Description:

According to the libSyntax documentation:

1. A token owns all of its trailing trivia up to, but not including, the next newline character.
2. Looking backward in the text, a token owns all of the leading trivia up to and including the first contiguous sequence of newlines characters.

The following code should have leading / trailing trivias as follows:

let x = 1 // This should be "1"'s trailing trivia
/// This should be `var`'s leading trivia
var y = 2

But actually, both comments are bundled as `var`'s leading trivia.

You can test the code at https://swift-ast-explorer.kishikawakatsumi.com/ (screenshot attached).

By the way, in TypeScript, it seems to work as is:
https://github.com/basarat/typescript-book/blob/master/docs/compiler/ast-trivia.md

[SR-778] Forgetting the in keyword can sometimes lead to compiling code

Previous ID SR-778
Radar None
Original Reporter chriseidhof (JIRA User)
Type Bug
Status Reopened
Resolution
Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug
Assignee None
Priority Medium

md5: 0093a5f05b0f3ded251f13fdd054fe04

relates to:

  • SR-245 Missing @warn_unused_result attributes in Standard Library

Issue Description:

Try the following code:

var x = 0
let capture: () -> Int = { [x]
  return x
}
x++
capture()

Expected result: because there is a capture list [x] that should capture x by value, we expect the result of the final call to be 0. However, it is 1. This is because we forget the in keyword, and [x] gets parsed as an array literal.

A possible solution would be to warn about [x] being an unused expression.

[SR-9480] unknownTokenKind("pound_warning")

Previous ID SR-9480
Radar None
Original Reporter Leitch (JIRA User)
Type Bug
Status Resolved
Resolution Done
Environment

swift-syntax:

0.40200.0

swiftc:

Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Target: x86_64-apple-darwin18.2.0

Xcode:

10.1, Build version 10B61

macOS:

10.14.1

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 1fb2817825eb5bf607f749363dac28ef

Issue Description:

The 0.40200.0 release is unable to parse #warning("msg") and #error("msg") directives, despite being part of 4.2.

[SR-13584] Make convenience methods returning an the value of an integer literal as Int and of floating literal as Float return an optional

Previous ID SR-13584
Radar None
Original Reporter vermont42 (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee vermont42 (JIRA)
Priority Medium

md5: 14ad515b7c276d59a1dd762b567c3a4b

Issue Description:

After the PR for SR-11580 merged, there was consensus, based on feedback, that the new convenience methods floatingValue and integerValue, should be optional in order to prevent potential crashes. This story is for implementation of this change. There was additional feedback involving naming and genericity. Depending on PR-review feedback, this story may encompass implementation of these changes as well.

[SR-11627] Element type of SwitchCaseListSyntax

Previous ID SR-11627
Radar None
Original Reporter kitasuke (JIRA User)
Type Improvement
Status Closed
Resolution Won't Do
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Improvement
Assignee kitasuke (JIRA)
Priority Medium

md5: 588625fa8f50dbd5c455311c88deb9cd

Issue Description:

SwitchCaseList syntax node currently has Syntax type for element.

# switch-case-list -> switch-case switch-case-list?
Node('SwitchCaseList', kind='SyntaxCollection',
  element='Syntax', element_name='SwitchCase',
  element_choices=['SwitchCase', 'IfConfigDecl']),

However, I think we can make it SwitchCase instead of Syntax. Is there any case for SwitchCaseList to have multiple types of Syntax other than SwitchCase?

[SR-13573] Fix Spelling of CustomReflecatbleTests.swift

Previous ID SR-13573
Radar None
Original Reporter vermont42 (JIRA User)
Type Bug
Status Closed
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug, StarterBug
Assignee maldahleh (JIRA)
Priority Medium

md5: 5c5fbcce6fac68b0b37280cd0bede337

Issue Description:

While implementing SR-11580, I noticed that the filename CustomReflecatbleTests.swift is misspelled. This is a perfect starter bug. The only steps to fix it are to correct the filename and ensure that SwiftSyntax unit tests still pass.

I myself am a newcomer to compiler development, so the following build-script invocation may be suboptimal, but it should work to build Swift and SwiftSyntax (if necessary) and run the SwiftSyntax unit tests. Run this from the parent folder of swift and swift-syntax. Build-and-test output will go to ~/Desktop/allout.txt.

time swift/utils/build-script --swiftsyntax --swiftpm --llbuild -t --skip-test-cmark --skip-test-swift --skip-test-llbuild --skip-test-swiftpm --infer > ~/Desktop/allout.txt 2>&1

I got build errors before adding the --infer argument, and I am unclear why it is not the default.

[SR-11580] FloatLiteralExprSyntax and IntegerLiteralExprSyntax should have computed properties that return their integer/float value

Previous ID SR-11580
Radar None
Original Reporter @ahoppen
Type New Feature
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels New Feature, StarterBug
Assignee vermont42 (JIRA)
Priority Medium

md5: b8b8d3a1a602fe052d3a131ced13afd6

Issue Description:

Often, when dealing with FloatLiteralExprSyntax or IntegerLiteralExprSyntax, you want to get the value they represent. SwiftSyntax should provide computed properties that return these.

The catch with it is, that we need to support all kinds of literals that are supported in Swift. In addition to the obvious ones this includes:

  • Literals with underscores

  • Hexadecimal int literals

  • Octal int literals

  • Binary int literals

  • Exponential float literals (e.g. 5e+2)

  • Hexadecimal float literals with possible exponents (e.g. 0x5.fp+2)

#148 started implementing these but gave up on the less obvious literals.

[SR-14365] UnresolvedPatternExprSyntax for value bindings

Previous ID SR-14365
Radar rdar://problem/75536971
Original Reporter bagipro (JIRA User)
Type Bug
Status Closed
Resolution Invalid
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 5f059448c94000c1c21afffe354280b3

Issue Description:

Hi,

I tried to parse the following file Signal-iOS/ProfileFetcherJob.swift at master · signalapp/Signal-iOS · GitHub with SwiftSyntax and received multiple errors about unresolved syntax (especially in value bindings)

E.g. the highlighted snippet on the code was marked as UnresolvedPatternExprSyntax. It can be reproduced using code:

        let sourceSyntax: SourceFileSyntax = try SyntaxParser.parse(URL(fileURLWithPath: source))
        class UnresolvedSyntaxVisitor: SyntaxVisitor {
            override func visit(_ node: UnresolvedPatternExprSyntax) -> SyntaxVisitorContinueKind {
                print(node)
                return .skipChildren
            }
        }
        UnresolvedSyntaxVisitor().walk(sourceSyntax)

[SR-9617] Nested declaration becomes unknown when semicolon is attached

Previous ID SR-9617
Radar None
Original Reporter inamiy (JIRA User)
Type Bug
Status Resolved
Resolution Done

Attachment: Download

Environment
  • Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)

  • SwiftSyntax 0.40200.0

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: a81807304d8b2f0d8e94fa5de8ce131f

Issue Description:

For example, when `StructDecl`'s inner `VariableDecl` has semicolon, AST will have `UnknownDecl`.

struct Foo {
    let x = 1;
}

[SR-10620] Raw strings literal is eliminated in StringInterpolationExpr

Previous ID SR-10620
Radar rdar://problem/50492902
Original Reporter kitasuke (JIRA User)
Type Improvement
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Compiler, SwiftSyntax
Labels Improvement, Syntax
Assignee @jansvoboda11
Priority Medium

md5: 2bdc43d7872ae8b293a7b2cc41926345

Issue Description:

Overview

It seems like that `StringInterpolationExpr` doesn't have syntax info of raw strings literal(#). Is this expected behavior? If so, formatter/rewriter tools might have an issue because generated swift code from libSyntax/SwiftSyntax would be a bit different from input swift code.

Examples

As you can see below example, raw strings literal `#` is eliminated in syntax tree.

// sample.swift
#"foo \#(bar)"#
// swift -frontend -emit-syntax sample.swift
{"id":18,"kind":"SourceFile","layout":[{"id":17,"kind":"CodeBlockItemList","layout":[{"id":14,"kind":"CodeBlockItem","layout":[{"id":13,"kind":"StringInterpolationExpr","layout":[{"id":1,"tokenKind":{"kind":"string_quote"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"id":12,"kind":"StringInterpolationSegments","layout":[{"id":3,"kind":"StringSegment","layout":[{"id":2,"tokenKind":{"kind":"string_segment","text":"foo "},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"}],"presence":"Present"},{"id":9,"kind":"ExpressionSegment","layout":[{"id":4,"tokenKind":{"kind":"backslash"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"id":5,"tokenKind":{"kind":"l_paren"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"id":7,"kind":"IdentifierExpr","layout":[{"id":6,"tokenKind":{"kind":"identifier","text":"bar"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null],"presence":"Present"},{"id":8,"tokenKind":{"kind":"string_interpolation_anchor"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"}],"presence":"Present"},{"id":11,"kind":"StringSegment","layout":[{"id":10,"tokenKind":{"kind":"string_segment","text":""},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"}],"presence":"Present"}],"presence":"Present"},{"id":1,"tokenKind":{"kind":"string_quote"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"}],"presence":"Present"},null,null],"presence":"Present"}],"presence":"Present"},{"id":16,"tokenKind":{"kind":"eof","text":""},"leadingTrivia":[{"kind":"Newline","value":1}],"trailingTrivia":[],"presence":"Present"}],"presence":"Present"}

Qestions

Can we have the raw strings literal as token kind like pound in syntax tree? This can be eliminated in AST as it is.

[SR-10715] Throwing error in defer statement causes error.

Previous ID SR-10715
Radar None
Original Reporter @purpleblues
Type Bug
Status Closed
Resolution Invalid
Environment

Xcode 10.2.1 (10E1001), Swift 5.0.1

Additional Detail from JIRA
Votes 0
Component/s Compiler, SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 0fb6eeb45ceff944eb03fa01e6941e17

Issue Description:

Please checkout the code below.

import Foundation

func test(_ work: () throws -> Void) throws {
    try work()
}

do {
    try test {
        
/* Error is not handled because the enclosing function is not declared 'throws' */
        defer { throw NSError(domain: "", code: 0, userInfo: nil) }
        
        print("hello")
    }
    
} catch {
     print(error.localizedDescription)
}

This code emits error that says "Error is not handled because the enclosing function is not declared 'throws'" for throwing in defer statement.

[SR-14904] iOS Build Instructions do not work

Previous ID SR-14904
Radar rdar://problem/80383591
Original Reporter helge (JIRA User)
Type Bug
Status Resolved
Resolution Done
Environment

BS 11.4 M1 Mac Mini

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee @CodaFi
Priority Medium

md5: 26a25700ee470efd7e3fe2ce646b30e5

Issue Description:

I'm trying to build SwiftSyntax for iOS using the simple steps described in the README: https://github.com/apple/swift-syntax/blob/main/README.md

git clone https://github.com/apple/swift.git
./swift/utils/update-checkout --clone
./swift/utils/build-parser-lib --release --no-assertions --build-dir /tmp/parser-lib-build-ios --host iphoneos --architectures arm64

Unfortunately that fails pretty quickly in the CC detection:

-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc - broken
CMake Error at /usr/local/Cellar/cmake/3.20.3/share/cmake/Modules/CMakeTestCCompiler.cmake:66 (message):
  The C compiler

    "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: /tmp/parser-lib-build-ios/arm64/obj/CMakeFiles/CMakeTmp
    
    Run Build Command(s):/usr/local/bin/ninja cmTC_3a1e2 && [1/2] Building C object CMakeFiles/cmTC_3a1e2.dir/testCCompiler.c.o
    [2/2] Linking C executable cmTC_3a1e2
    FAILED: cmTC_3a1e2 
    : && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -arch arm64 -target arm64-apple-ios10.0  -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk -miphoneos-version-min=10.0 -Wl,-search_paths_first -Wl,-headerpad_max_install_names  CMakeFiles/cmTC_3a1e2.dir/testCCompiler.c.o -o cmTC_3a1e2   && :
    ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/lib/libSystem.tbd, missing required architecture x86_64 in file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/lib/libSystem.tbd (4 slices)
    ld: dynamic main executables must link with libSystem.dylib for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    ninja: build stopped: subcommand failed.

[SR-9370] UnknownSyntax found for syntax tree generated from sourcekitd but not from swiftc

Previous ID SR-9370
Radar rdar://problem/46143404
Original Reporter @nathawes
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Source Tooling, SwiftSyntax
Labels Bug, FoundByStressTester
Assignee @nkcsgexi
Priority Medium

md5: 88d0729daee0721795b20c9b896fc729

Issue Description:

For a file containing the following code:

#if swift(<4)
 print(1)
#endif

a Syntax tree produced using sourcekitd generates an UnknownSyntax node but with swiftc -emit-syntax it works fine.

[SR-8510] 'guard' is easy to misspell as 'gaurd', results in large number of follow-on errors, and could have a fixit.

Previous ID SR-8510
Radar rdar://problem/32419789
Original Reporter @huonw
Type Bug
Status In Progress
Resolution
Environment

Master at 2018-08-09

Additional Detail from JIRA
Votes 1
Component/s Compiler
Labels Bug, DiagnosticsQoI, Parser, StarterBug
Assignee mkita (JIRA)
Priority Medium

md5: 83854736e7d37441acce9e16b297a24a

Issue Description:

In the following code, the guard statement is misspelled, and it results in 6 errors, plus notes and warnings! It'd be neat if the compiler detected when the "consecutive statements" error starts with the identifier gaurd, and assumed that guard was what was meant (along with a fixit so the user swaps it). I think that only doing this when that error occurs is important, because someone could legitimately have var gaurd = 1; gaurd = 2; print(gaurd), and none of those should change to guard.

func foo() -> Int? { return 0 }
func bar() {
    gaurd let x = foo() else { return }
    print(x)
}
guard.swift:3:10: error: consecutive statements on a line must be separated by ';'
    gaurd let x = foo() else { return }
         ^
         ;
guard.swift:3:24: error: consecutive statements on a line must be separated by ';'
    gaurd let x = foo() else { return }
                       ^
                       ;
guard.swift:3:25: error: expected expression
    gaurd let x = foo() else { return }
                        ^
guard.swift:3:5: error: use of unresolved identifier 'gaurd'
    gaurd let x = foo() else { return }
    ^~~~~
guard.swift:3:30: error: closure expression is unused
    gaurd let x = foo() else { return }
                             ^
guard.swift:3:30: note: did you mean to use a 'do' statement?
    gaurd let x = foo() else { return }
                             ^
                             do 
guard.swift:4:11: warning: expression implicitly coerced from 'Int?' to 'Any'
    print(x)
          ^
guard.swift:4:11: note: provide a default value to avoid this warning
    print(x)
          ^
            ?? <#default value#>
guard.swift:4:11: note: force-unwrap the value to avoid this warning
    print(x)
          ^
           !
guard.swift:4:11: note: explicitly cast to 'Any' with 'as Any' to silence this warning
    print(x)
          ^
            as Any

Possible new version:

guard.swift:3:10: error: consecutive statements on a line must be separated by ';'; did you misspell 'guard'?
    gaurd let x = foo() else { return }
    ^~~~~
    guard

[SR-8910] Swift Syntax - Trouble Parsing # sign syntax

Previous ID SR-8910
Radar rdar://problem/45049365
Original Reporter loganwright (JIRA User)
Type Bug
Environment

Mac

Additional Detail from JIRA
Votes 1
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: be1d5a0a862ac57009440f63a00bba35

Issue Description:

I had seen it before on an `#if !os(macOS)` but I wasn't able to replicate.

Basically, SwiftSyntax crashes on pound syntax, notably `#file`

Version:
`.package(url: "https://github.com/apple/swift-syntax", from: "0.40200.0"),`

Repro:
```
func example() {
let _ = #file
}
```

Create a SyntaxVisitor that visits functions. It was crashing with a `bus 10` error.

[SR-13553] SwiftSyntax doesn't work in Xcode 12 with Swift 5.3.

Previous ID SR-13553
Radar rdar://problem/68993163
Original Reporter fdiaz (JIRA User)
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 2
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: b84a172e4242e4b9a5224069747cc885

Issue Description:

Xcode 12 just went GM today and iOS 14 is scheduled to be released tomorrow but we don't have a Swift 5.3 version available in SwiftSyntax to be able to update the libraries that use it in Xcode 12.

I've tried using the last available release to date https://github.com/apple/swift-syntax/releases/tag/swift-DEVELOPMENT-SNAPSHOT-2020-09-11-a and the last Xcode available (Version 12.0 (12A7208)) and I'm getting

> stderr: Error: The loaded '_InternalSwiftSyntaxParser' library is from a toolchain that is not compatible with this version of SwiftSyntax

when running SwiftSyntax.

[SR-8687] Unable to build SwiftSyntax with SwiftPM

Previous ID SR-8687
Radar None
Original Reporter @mdiep
Type Bug
Status Closed
Resolution Done

Attachment: Download

Environment

Xcode 10.0.0 beta 6
Apple Swift version 4.2 (swiftlang-1000.0.36 clang-1000.10.44)
Target: x86_64-apple-darwin17.7.0

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 9187e958c9ce3827061a6dfc70b8670c

Issue Description:

I've more-or-less copied the Package.swift from the SwiftSyntax README, but it fails to build with Xcode 10 beta 6. From what I understand from the README, this should work. I'm not sure what I'm doing wrong.

I've attached the project I'm using and with the log (it's quite long).

[SR-14552] SwiftSyntax crashes when parsing a malformed function type

Previous ID SR-14552
Radar rdar://problem/77391988
Original Reporter @allevato
Type Bug
Status Resolved
Resolution Done

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee @ahoppen
Priority Medium

md5: 103052cad603311e83a1a277c4a8f594

Issue Description:

This is a repro of a case that recently started failing in one of swift-format's tests against the main branch (I'm using the 2021-04-26 development snapshot as my current environment).

When parsing the following source code:

{{ let x: (A -> B)}}

(Note that "A" should have its own parentheses surrounding it for this to be valid.)

The parser crashes with the following message:

Assertion failed: (isValid() && "length does not make sense for an invalid range"), function getByteLength, file /Users/buildnode/jenkins/workspace/oss-swift-package-macos/swift/include/swift/Basic/SourceLoc.h, line 218.

I would expect this to fail in some other, non-crashing fashion, such as expressing the syntax using Unknown* nodes.

To reproduce:

  1. Download the attached project.

  2. Use a development toolchain that is syntax-compatible with swift-syntax's main branch (at the time I'm writing this, 2021-04-26 worked).

  3. Run swift run TriviaCrash.

[SR-12857] Instructions for building swift-syntax don't work

Previous ID SR-12857
Radar None
Original Reporter @xwu
Type Bug
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 78e02ca7c4cf672690f66c5a4d6d5235

Issue Description:

Invoking swift-syntax/build-script.py as per instructions in the README plainly doesn't work. Instead, it produces an error: argument --toolchain is required. Providing a path to the toolchain doesn't work either. The instructions must be updated to show something that can actually be invoked.

[SR-15163] Failed to produce diagnostic for expression

Previous ID SR-15163
Radar rdar://problem/82938937
Original Reporter Knowledgeink (JIRA User)
Type Bug
Status Resolved
Resolution Done

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug, CompilerCrash, DiagnosticsQoI
Assignee Knowledgeink (JIRA)
Priority Medium

md5: 4c7cb6fb60d466ffc893961c48019150

Issue Description:

Attempting to make an api call, unable to identify why I am getting the below message.

Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project

// code placeholder
    var body: some View{
        //Nationgation View..
        
        NavigationView{
           
            ScrollView(.vertical, showsIndicators: true, content:{
                VStack(spacing: 15){
                    
                    //Search Bar...
                    HStack(spacing: 10) {
                       
                        Image( systemName: "magnifyingglass")
                            .foregroundColor(.gray)
                        
                        TextField("Search Character", text: $homeData.searchQuery)
                            .autocapitalization(.none)
                            .disableAutocorrection(true)
                    }
                    .padding(.vertical,10)
                    .padding(.horizontal)
                    .background(Color.white)
                    
                    //Shadows...
                    .shadow(color: Color.black.opacity(0.06), radius: 5, x: 5, y:5)
                    .shadow(color: Color.black.opacity(0.06), radius: 5, x: -5, y: -5)
                }
                .padding()
                if let characters = homeData.fetchedPorn{
                    
                    if characters.isEmpty{
                        
                        //No Results
                        Text("No Result Found")
                            .padding(.top,20)
                    }
                    else{
                        
                        // Displaying results
                        ForEach(characters){data in
                            
                           CharacterRowView(character: data)
                            
                            
                        }
                    }
                }
                else{
                    if homeData.searchQuery != ""{
                    //Lokading Screem
                    ProgressView()
                        .padding(.top,20)
                    }
                }
            })
            .navigationTitle("Marvel Characters")
        }
    }

[SR-9798] Build swift-syntax with a downloaded Swift toolchain

Previous ID SR-9798
Radar None
Original Reporter @krzyzanowskim
Type Bug
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 44b16a21d179e4e21b4cf2bec9883903

Issue Description:

It's not possible to build swift-syntax with a downloaded Swift snapshot toolchain - it requires to clone the swift repository to use the gyb dependencies.

see discussion: #69 (comment)

[SR-9337] SwiftSyntax not getting code generation releases automatically

Previous ID SR-9337
Radar None
Original Reporter @jpsim
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Project Infrastructure, SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: d409dea74a1d59a0249fbbe7888bf988

Issue Description:

From the SwiftSyntax README:

Swift-CI will automatically run the code generation step whenever a new toolchain (development snapshot or release) is published. It should thus almost never be necessary to perform the above build yourself.

However, this appears to have only worked once:

$ git tag --list
0.40200.0
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-08-25-a
swift-DEVELOPMENT-SNAPSHOT-2018-08-25-a

This makes it hard to use SwiftSyntax using the Swift Package Manager with any changes that have been merged in the last 3 months.

[SR-9850] There's no obvious way to get content of a syntax node

Previous ID SR-9850
Radar None
Original Reporter @dduan
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Improvement
Assignee @nkcsgexi
Priority Medium

md5: 7a905c33db7bd997093527302f0f11ec

Issue Description:

Each syntax node has a contentLength property, which does not count the length of trivia. It would be great to have a way to get the text corresponding to this content. Currently, achieving this task is not super easy.

@harlanhaskins @akyrtzi

[SR-11591] SyntaxVisitor not visiting nodes as expected

Previous ID SR-11591
Radar None
Original Reporter fdiaz (JIRA User)
Type Bug

Attachment: Download

Environment

MacOS 10.14.6, Xcode 10.3

Additional Detail from JIRA
Votes 1
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 6740206789e6a4fdbe77197f956dbdb8

Issue Description:

The expectation is that SwiftRewriter and SwiftVisitor would behave exactly the same when visiting noted.

This doesn't seem to be the case, since in the attached code SwiftRewriter is triggered, while SwiftVisitor is not.

Confirmed this is a bug here

Small repro attached.

[SR-9306] FunctionParameterSyntax line position incorrect for multi-line function declaration.

Previous ID SR-9306
Radar None
Original Reporter Leitch (JIRA User)
Type Bug
Status Closed
Resolution Done
Environment

swift-syntax:

0.40200.0

swiftc:

Apple Swift version 4.2.1 (swiftlang-1000.11.42 clang-1000.11.45.1)
Target: x86_64-apple-darwin18.2.0

Xcode:

10.1, Build version 10B61

macOS:

10.14.1

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 50ea8a173ef8e58008a21dc3cd1a867b

Issue Description:

Given the following code:

class MyClass {
    func myFunc(param1: String,
                param2: String) {}
}

The line position of the FunctionParameterSyntax for param2 is incorrectly identified as 2, it should be 3. The line for param1 is correctly identified as 2.

[SR-11625] SyntaxRewriter crashes when called from a thread other than main

Previous ID SR-11625
Radar None
Original Reporter benpious (JIRA User)
Type Bug
Environment

SwiftSyntax 0.50100.0, Xcode 11.1. Made a simple SwiftPM project, used generate-xcodeproj to make a project to open (double-clicking the Package.swift file did not produce a buildable project).

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 9e3f668e7cbc4a6d8fd8813e5c6f08ad

Issue Description:

I'm trying to create and use a SyntaxRewriter subclass from a thread other than main. I'm not sharing between threads, so it seems like it should be fine. However, I get an EXEC_BAD_ACCESS inside of SwiftSyntax. Here's some sample code that demonstrates the problem, which is adapted from the SwiftSyntax README's sample code:

let string = """

protocol P {
    var x: Int? { get set }
}


"""

let queue = DispatchQueue.global()
let sourceFile = try! SyntaxParser.parse(source: string)
let semaphore = DispatchSemaphore(value: 0)
queue.async {
    _ = Renamer().visit(sourceFile)
    semaphore.signal()
}
semaphore.wait()
print("done")

It crashes with an EXEC_BAD_ACCESS, typically in `SyntaxRewriter.visitChildren()`. Trying to print any variables in the debugger outputs "Trying to put the stack in unreadable memory at <some memory address>".

I can't reproduce this in an optimized build.

[SR-13126] `deinit` without braces results in 'unknown' node (shows up when parsing .swiftinterface files)

Previous ID SR-13126
Radar rdar://problem/65192354
Original Reporter schwa (JIRA User)
Type Bug

Attachment: Download

Environment

Tested against release/5.3 of swift-syntax

Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: af87e62f21e27dd8333ceb97a0b8d3a2

Issue Description:

I have a test project using swift-syntax. Project can parse and dump a .swift file successfully. Same project cannot parse and dump a .swiftinterface file.

It would be super-useful to be able to parse .swiftinterface files too.

[SR-13605] Build script ‘swift/utils/build-parser-lib’ fails with undefined symbols

Previous ID SR-13605
Radar None
Original Reporter TikiMcFee (JIRA User)
Type Bug
Status Reopened
Resolution

Attachment: Download

Environment
  • macOS 10.15.6 (19G2021)

  • XCode Version 12.0 (12A7209)

  • Toolchain: Swift Development Snapshot 2020-09-23 (a)

  • /Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2020-09-23-a.xctoolchain
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee @akyrtzi
Priority Medium

md5: 2b3cfd0512fa4210543251067beeaf09

Issue Description:

Hey there folks. I greatly appreciate your time. If there's anything at all I can supply to help solve this - or to help produce a better bug/support ticket - please let me know!

The context

I am attempting to build a custom version of `lib_InternalSwiftSyntaxParser.dylib` to embed in iOS as described in the repositories below:

https://github.com/apple/swift-syntax
https://github.com/apple/swift

My configuration is:

# swift-DEVELOPMENT-SNAPSHOT-2020-09-23-a installed at /Library/Developer/Toolchains
$ echo $TOOLCHAINS
swift

$ xcrun --find swift
/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2020-09-23-a.xctoolchain/usr/bin/swift

$ xcrun --toolchain default --find swift
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

$ xcrun --toolchain swift --find swift
/Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2020-09-23-a.xctoolchain/usr/bin/swift

# showing that --toolchain with bad input goes back to default
$ xcrun --toolchain random_string_that_shouldnt_do_anything --find swift
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

So far, I have successfully built the main swift repository with

$ ./swift/utils/build-script --clean

... and I am using the built `.dylib` from that effectively in a macOS application.

The crash

$ ./swift/utils/build-parser-lib --release --no-assertions --build-dir /tmp/parser-lib-build-ios --host iphoneos --architectures arm64

[ ... many many lines of build information later ...]

[1/2] Linking CXX shared library lib/lib_InternalSwiftSyntaxParser.dylib
FAILED: lib/lib_InternalSwiftSyntaxParser.dylib
: && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -arch arm64 -miphoneos-version-min=10.0 -fPIC -fvisibility-inlines-hidden -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wstring-conversion -fdiagnostics-color -Wno-nested-anon-types -Werror=switch -Wdocumentation -Wimplicit-fallthrough -Wunreachable-code -Woverloaded-virtual -DOBJC_OLD_DISPATCH_PROTOTYPES=0 -O2 -g -DNDEBUG -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk -dynamiclib -Wl,-headerpad_max_install_names -Wl,-exported_symbols_list,"/tmp/parser-lib-build-ios/arm64/obj/tools/swift/tools/libSwiftSyntaxParser/libSwiftSyntaxParser.exports" -Wl,-dead_strip -target arm64-apple-ios10.0 -Xlinker -dead_strip -Xlinker -compatibility_version -Xlinker 1 -o lib/lib_InternalSwiftSyntaxParser.dylib -install_name @rpath/lib_InternalSwiftSyntaxParser.dylib tools/swift/tools/libSwiftSyntaxParser/CMakeFiles/libSwiftSyntaxParser.dir/c-include-check.c.o tools/swift/tools/libSwiftSyntaxParser/CMakeFiles/libSwiftSyntaxParser.dir/libSwiftSyntaxParser.cpp.o lib/libswiftParse.a lib/libswiftSyntaxParse.a lib/libswiftParse.a lib/libswiftSyntaxParse.a lib/libswiftAST.a lib/libswiftBasic.a lib/libLLVMSupport.a -lm lib/libLLVMDemangle.a lib/libswiftDemangling.a ./lib/libclangBasic.a lib/libswiftSyntax.a && :
Undefined symbols for architecture arm64:
 "clang::MacroInfo::dump() const", referenced from:
 swift::ClangNode::dump() const in libswiftAST.a(Decl.cpp.o)
 "clang::Type::dump() const", referenced from:
 swift::UnexpectedClangTypeError::dump() in libswiftAST.a(ExtInfo.cpp.o)
 "clang::Decl::dump() const", referenced from:
 swift::ClangNode::dump() const in libswiftAST.a(Decl.cpp.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
ERROR: command terminated with a non-zero exit status 1, aborting

(You can find the full, gorey, exciting log at https://gist.github.com/tikimcfee/75c24cdce8cc352645da78da4b015daf)

There are a couple of things I noticed in the build log that have me questioning some kind of cache or local configuration. Specifically, lines that mention build tools from a different toolchain:

-- Found libtool - /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool
[...]
-- CMake (/usr/local/Cellar/cmake/3.18.2/bin/cmake) Version: 3.18.2
-- CMake Make Program (/usr/local/bin/ninja) Version: 1.10.1
-- C Compiler (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc) Version: 12.0.0.12000032
-- C++ Compiler (/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++) Version: 12.0.0.12000032

I'm guessing I'm doing something wrong with the invoking of this script, but I've also tried a number of path hacks within the actual build script to try to point to a different toolchain or compiler - all of which are things I am completely unfamiliar with and am stabbing at in the dark with print debugging.

[SR-13541] Incorrect parsing of TernarySyntax

Previous ID SR-13541
Radar rdar://problem/68728159
Original Reporter mkruber (JIRA User)
Type Bug
Status Resolved
Resolution Invalid
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: 6f8e53a86a4d051eb4c976739f568e96

Issue Description:

It appears that TernarySyntax is not being parsed correctly. For instance, the following statement is parsed as a SequenceExprSyntax.

helper_func() == p1 ? true : false

However, the following is parsed correctly as a TernarySyntax.

p1 ? true : false

This problem is observed with SwiftSyntax 5.2

[SR-10074] Missing token classifications

Previous ID SR-10074
Radar None
Original Reporter @krzyzanowskim
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Bug
Assignee None
Priority Medium

md5: fbabfbd422b18a4cb610bf491fdb56a8

Issue Description:

Looks like depends on how the classification is checked, the result may be different. Let's consider this sample:

  public func testClassification1() {
    let source = """
public final class Foo {}
"""
    let tree = try! SyntaxParser.parse(source: source)
    for token in tree.tokens {
        for classification in token.classifications {
            print("\(token.text) - \(classification.kind)")
        }
    }
  }

output:

public - keyword
class - keyword

Missing:

final - attribute

Now let's try this sample:

    public func testClassification2() {
        let source = """
public final class Foo {}
"""
        let tree = try! SyntaxParser.parse(source: source)
        for classification in tree.classifications {
            print("\(classification.kind)")
        }
    }

output:

keyword
attribute
keyword

[SR-8800] Enhancing swift-syntax to allow #sourcelocation to appear in any location

Previous ID SR-8800
Radar None
Original Reporter @johnno1962
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler, SwiftSyntax
Labels Bug, LanguageFeatureRequest
Assignee None
Priority Medium

md5: 1857afa8697bcd58bd807f0a45bdf324

Issue Description:

This arose out of the discussion on swiftlang/swift#19347 which allows #sourceLocation directives to occur in collections. Rather than have Syntax accept #sourceLocation as an alternative for an array/dictionary element it was suggested perhaps Syntax should treat #sourceLocation as trivia going forward.
See swiftlang/swift#19347 (comment)

[SR-8670] Make SwiftSyntax available on Linux

Previous ID SR-8670
Radar None
Original Reporter @akyrtzi
Type Task
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s SwiftSyntax
Labels Task
Assignee @spevans
Priority Medium

md5: e7e04b596cc8904fe80c0bfdf1f911b3

Issue Description:

SwiftSyntax is currently only supported on Darwin, we should make the necessary changes to make it available for linux as well. For example SwiftSyntax depends on Foundation, for the linux build it can depend on swift-corelibs-foundation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.