### Swift Parameter Pack Soup Example Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt An example function utilizing multiple parameter packs for arguments and return types, creating pairs. ```swift func makePairs( firsts first: repeat each First, seconds second: repeat each Second ) -> (repeat Pair) { return (repeat Pair(each first, each second)) } ``` -------------------------------- ### Function Calls Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Provides examples of various function call syntaxes, including standard calls, calls with multiple arguments, and optional chained calls. ```swift print("Hello World!") sum(1, 2) something.hello?("world") ``` -------------------------------- ### Custom String Interpolation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Shows an example of custom string interpolation with a format specifier. ```swift "Hi, I'm \(format: age)" ``` -------------------------------- ### Concise Swift Class Declarations Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Provides examples of Swift classes declared concisely on a single line, suitable for simple data structures. ```swift class Dog { let noise: String = "bark" } ``` ```swift class Cat { let noise: String = "meow"; let claws: String = "retractable" } ``` -------------------------------- ### Integer Literals Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Provides examples of various integer literal formats, including decimal, hexadecimal, octal, and binary. ```swift 0 8 23 9847 0xf00 0o774 0b01 ``` -------------------------------- ### Swift Macro Declaration Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Example of a Swift macro declaration with external macro definition. ```swift @attached( member, names: named(apply) ) public macro AutoApply() = #externalMacro( module: "SwiftLintCoreMacros", type: "AutoApply" ) ``` -------------------------------- ### Swift Regex Literal Examples Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Illustrates Swift code where ambiguous expressions are parsed as regex literals. ```swift foo(/a, b/) // Will become regex literal '/a, b/' ``` ```swift qux(/, !/) // Will become regex literal '/, !/' ``` ```swift qux(/,/) // Will become regex literal '/,/' ``` -------------------------------- ### Swift Special Constructors Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Illustrates various types of initializers in Swift, including designated, convenience, override, and required initializers. These are used for object instantiation and setup. ```swift class Test { let a: Int let b: Int init(_ a: Int, _ b: Int) { self.a = a self.b = b } convenience override init() { self.init(0, 0) } required init?(from: String) { self.init(1, 2) } required init!(from value: Int) { self.init(value, value) } } ``` -------------------------------- ### Simple Identifier Example Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates a basic identifier, which is a name given to a variable, function, or other entity. ```swift helloWorld ``` -------------------------------- ### willSet Property Observer in Swift Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Shows how to use the `willSet` observer to execute code just before a property's value is stored. This example is within a class. ```swift class AnimationLayer { var forceUpdate = false { didSet { print("Forcing updates on each frame.") } } } ``` -------------------------------- ### Swift Key-Path Observation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Example of observing changes to a specific property using its key-path. The closure receives the object and change details. ```swift c.observe(\.someProperty) { object, change in // ... } ``` -------------------------------- ### Incomplete Raw String Handling Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Shows how Swift handles incomplete raw strings, preventing parsing hangs. This example highlights an unexpected '#' character within a raw string context. ```swift let _ = #"Foo" ``` -------------------------------- ### Swift Custom Unapplied Operators Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Shows examples of unapplied custom operators used in expressions. ```swift baz(!/, 1) / 2 ``` ```swift qux(/, /) ``` ```swift qux(/^, /) ``` ```swift qux(!/, /) ``` -------------------------------- ### Availability Condition with macOS Target Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Use `#available` to conditionally execute code based on the macOS version. This example returns 3 for macOS 10.12.0+ and 0 otherwise. ```swift if #available(macOS 10.12.0, *) { return 3 } else { return 0 } ``` -------------------------------- ### Single-line regex on multiple lines Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates a single-line regex pattern used across multiple lines in a comment. This example shows a call expression with a comment. ```swift doOperation(on: a, /) /// That was fun! We ran `/` ``` -------------------------------- ### Metatype Casting Example Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/types.txt Demonstrates casting a type to its metatype (`.Type`). This is used when you need to refer to the type itself, rather than an instance of the type, such as in protocol conformance checks or factory methods. ```swift _ = foo as [String].Type protocol GetType { func getType() -> AnyObject.Type } ``` ```tree-sitter-swift (source_file (assignment (right_expression (type_cast_expression (type_erasure (array_type (user_type (type_identifier)))) (type)) (type_identifier)))) (protocol_declaration (type_identifier) (method_declaration (function_signature (return_type (user_type (type_identifier) (type_arguments (any_object_type)))))))) ``` -------------------------------- ### Swift Variadic Function Declaration Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Example of a Swift variadic function declaration that accepts a variable number of String arguments and returns an array of Strings. ```swift func toUpperCaseAll(strings: String ...) -> [String] { } ``` ```tree-sitter grammar (source_file (function_declaration (simple_identifier) (parameter (simple_identifier) (user_type (type_identifier))) (array_type (user_type (type_identifier))) (function_body))) ``` -------------------------------- ### Distributed Actor and Function Declaration in Swift Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Example of declaring a distributed actor and a distributed function in Swift. Distributed actors enable remote communication. ```swift distributed actor A { distributed func doit() {} } ``` -------------------------------- ### If Let with Statement Label Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Use a statement label with `if let` to allow branching or breaking from nested control flow structures. This example also includes multiple conditions. ```swift someLabel: if a.isEmpty, let b = getB() { } ``` -------------------------------- ### Swift Extension on Array Type Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt An example of extending a specific type, in this case, an array of 'SpecialItem'. This allows adding custom functionality to arrays of that specific element type. ```swift extension [SpecialItem] { } ``` -------------------------------- ### Constructor Calls Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates initializing collections like Sets and Dictionaries using their respective constructors. ```swift var result = Set() var result2 = [String: [Complex<[String: Any]>]]() ``` -------------------------------- ### Swift Custom Infix Operator Declaration Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Defines and uses a custom infix operator '/^/'. This example also highlights potential parsing ambiguities with regex literals. ```swift infix operator /^/ func /^/ (lhs: Int, rhs: Int) -> Int { 0 } let b = 0 /^/ 1 ``` -------------------------------- ### Raw String with Interpolation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt An example of using raw strings with string interpolation in Swift. Interpolated expressions are enclosed in parentheses and preceded by a backslash within the raw string. ```swift extension URL { func html(withTitle title: String) -> String { return #"\#(title)"# } } ``` -------------------------------- ### Array and Dictionary Literals Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Shows how to declare and initialize array and dictionary literals in Swift. ```swift let numbers = [1, 2, 3] let numerals = [1: "I", 4: "IV", 5: "V", 10: "X"] ``` -------------------------------- ### Swift Switch Statement with Optional Binding and String Interpolation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Demonstrates 'switch' cases using optional binding with 'let' and string interpolation for formatted output. ```swift switch self { case .notExecutable(let path?): return "File not executable: \(path)" case let .isExecutable(path?): return "File is executable: \(path)" } ``` -------------------------------- ### Initialize and Use tree-sitter WASM Parser in Javascript Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/README.md Initialize the web-tree-sitter library and load the Swift WASM module. Then, create a parser instance and parse Swift code. ```javascript const Parser = require("web-tree-sitter"); async function run() { //needs to happen first await Parser.init(); //wait for the load of swift const Swift = await Parser.Language.load("./tree-sitter-swift.wasm"); const parser = new Parser(); parser.setLanguage(Swift); //Parse your swift code here. const tree = parser.parse('print("Hello, World!")'); } //if you want to run this run().then(console.log, console.error); ``` -------------------------------- ### Defining and Using a Prefix Operator Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates how to declare a custom prefix operator and define its behavior. ```swift /!5; ``` ```swift prefix operator /!; ``` ```swift prefix func /!(x: Int) { print(x) } ``` -------------------------------- ### Swift Range Expression in Loop Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Defines a sequence of values over which a loop iterates. This example uses a half-open range. ```swift for i in 0 ..< something.count { // Do something } ``` -------------------------------- ### Array and Dictionary Indexing Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Illustrates various forms of indexing, including optional chaining for potentially nil collections, standard indexing, and custom subscripting with labels. ```swift let b = maybeNil?[2] ``` ```swift a[2] = b ``` ```swift let c = array[safe: index] ``` ```swift let d = weirdType[indexesByField, and: anotherField] ``` ```swift let e = array[...] ``` -------------------------------- ### Simple Try Expression Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates the basic usage of the 'try' keyword to call a throwing function. ```tree-sitter-swift (source_file (try_expression (try_operator) (call_expression (simple_identifier) (call_suffix (value_arguments))))) ``` -------------------------------- ### Swift Range Expression in Indexing Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Used to specify a sub-sequence of elements. This example shows an open-ended range used for string indexing. ```swift string[..(_ sequence: repeat each S) where repeat each S: Sequence { } ``` ```swift func variadic(_: repeat each S) where repeat (each S).Element == T {} ``` ```swift func variadic(_: repeat each S) where repeat (each S).Element == Array {} ``` -------------------------------- ### Swift Property Declaration with Call Expressions Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Illustrates property declarations using nested call expressions and navigation. ```swift let z = some.method(1)(2) ``` -------------------------------- ### Class Inheritance Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates basic class inheritance in Swift, showing a class 'A' inheriting from 'B'. ```swift class A : B {} ``` -------------------------------- ### Conditional Compilation with Error Directive Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Use `#error` to halt compilation with a specific message if a certain preprocessor flag is defined. This example triggers an error if `SOME_FLAG` is enabled. ```swift #if SOME_FLAG #error("SOME_FLAG must not be enabled!") #elseif OTHER_FLAG ``` -------------------------------- ### Swift Switch Statement with Various Cases Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Illustrates a 'switch' statement with cases for patterns, expressions, literals, and a default case. ```swift switch something { case .pattern: return "Hello" case expression: return "and" case "Literal": return "Goodbye" default: return ":)" } ``` -------------------------------- ### Named SwiftUI Preview Macro Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/macros.txt Demonstrates a named SwiftUI preview macro, allowing multiple previews with distinct identifiers. The first argument is a string literal for the preview's name. ```swift #Preview("other") { Text("Hello, world!") } ``` ```tree-sitter-swift (source_file (macro_invocation (simple_identifier) (call_suffix (value_arguments (value_argument (line_string_literal (line_str_text)))) (lambda_literal (statements (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (line_string_literal (line_str_text))))))))))) ``` -------------------------------- ### Implicit Member Expression Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Shows how to use an implicit member expression to initialize a property. ```swift let a: SomeClass = .someInstance ``` -------------------------------- ### Import Declarations Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Shows different ways to import modules and specific types or classes from modules. Imports can be unqualified or qualified. ```swift import Foundation import class SomeModule.SomeClass class Foo { } import SomethingElse ``` -------------------------------- ### Swift Class Deinitializer Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates the deinit keyword for class deinitialization. Ensure cleanup logic is placed within the deinit block. ```swift class Expensive { deinit { cleanUp(self) } } ``` -------------------------------- ### Platform Conditional Compilation in Swift Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Shows how to conditionally compile code based on the operating system using preprocessor directives. ```swift #if os(OSX) || os(Linux) print("yes") #else print("no") #endif ``` -------------------------------- ### Simple await expression Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates a basic await expression used for asynchronous function calls. ```swift await foo() ``` ```tree-sitter (source_file (await_expression (call_expression (simple_identifier) (call_suffix (value_arguments))))) ``` -------------------------------- ### Swift class with Objective-C and custom annotations Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Illustrates a Swift class using Objective-C interoperability annotations like '@objc' and custom annotations for documentation and function parameters. ```swift @objc(Test) class Test : Protocol { @objc(someArgument:) dynamic func someFunction(with argument: Int) { } @DocumentationAnnotation(help: "Calls this function nicely.") func someFunction(nice argument: Int) { } } ``` ```tree-sitter-swift (source_file (class_declaration (modifiers (attribute (user_type (type_identifier)) (simple_identifier))) (type_identifier) (inheritance_specifier (user_type (type_identifier))) (class_body (function_declaration (modifiers (attribute (user_type (type_identifier)) (simple_identifier)) (property_modifier)) (simple_identifier) (parameter (simple_identifier) (simple_identifier) (user_type)))))) ``` -------------------------------- ### SwiftUI Preview Macro Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/macros.txt Shows a standard SwiftUI preview macro used for live previews in Xcode. It requires a closure containing SwiftUI view definitions. ```swift #Preview { VStack { Text("Hello, world!") } .padding() } ``` ```tree-sitter-swift (source_file (macro_invocation (simple_identifier) (call_suffix (lambda_literal (statements (call_expression (navigation_expression (call_expression (simple_identifier) (call_suffix (lambda_literal (statements (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (line_string_literal (line_str_text))))))) (navigation_suffix (simple_identifier))) (call_suffix (value_arguments)))))))))) ``` -------------------------------- ### Tuple Expressions Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Illustrates the creation and return of tuple expressions with named and unnamed elements. ```swift let a: (Int, Int) = (1, 2) return (lhs: 3, rhs: 4) ``` -------------------------------- ### Function Types Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/types.txt Shows how to reference function types with no parameters, single parameters, and 'inout' parameters. ```swift unitFunction as () -> Unit consumer as (Int) -> Unit configurator as (inout Config) -> Unit ``` ```tree-sitter-swift (source_file (as_expression (simple_identifier) (as_operator) (function_type (tuple_type) (user_type (type_identifier)))) (as_expression (simple_identifier) (as_operator) (function_type (tuple_type (tuple_type_item (user_type (type_identifier)))) (user_type (type_identifier)))) (as_expression (simple_identifier) (as_operator) (function_type (tuple_type (tuple_type_item (parameter_modifiers (parameter_modifier)) (user_type (type_identifier)))) (user_type (type_identifier))))) ``` -------------------------------- ### Use 'if' and 'switch' as Value Argument Labels Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates using Swift keywords 'if' and 'switch' as labels for value arguments in function calls. This is useful when a keyword's meaning aligns with the argument's purpose. ```swift atomicValue.set(to: "value + 1", if: "value <= 100") atomicValue.replace(from: otherValue, switch: true) ``` ```tree-sitter-swift (source_file (call_expression (navigation_expression (simple_identifier) (navigation_suffix (simple_identifier))) (call_suffix (value_arguments (value_argument (value_argument_label (simple_identifier)) (line_string_literal (line_str_text))) (value_argument (value_argument_label (simple_identifier)) (line_string_literal (line_str_text)))))) (call_expression (navigation_expression (simple_identifier) (navigation_suffix (simple_identifier))) (call_suffix (value_arguments (value_argument (value_argument_label (simple_identifier)) (simple_identifier)) (value_argument (value_argument_label (simple_identifier)) (boolean_literal)))))) ``` -------------------------------- ### Async Let Declaration in Swift Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Illustrates the declaration and usage of 'async let' for concurrent operations. ```swift async let foo = 64 async let bar = 66 ``` -------------------------------- ### Protocol Composition in Where Clauses Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates how to use protocol composition with a `where` clause in a function signature. This requires the generic type `S` to conform to both `Sequence` and have elements that are of type `P1 & P2`. ```swift func iterate(h: S) where S : Sequence, S.Element == P1 & P2 { } ``` ```tree-sitter-swift (source_file (function_declaration (simple_identifier) (type_parameters (type_parameter (type_identifier))) (parameter (simple_identifier) (user_type (type_identifier))) (type_constraints (where_keyword) (type_constraint (inheritance_constraint (identifier (simple_identifier)) (user_type (type_identifier)))) (type_constraint (equality_constraint (identifier (simple_identifier) (simple_identifier)) (protocol_composition_type (user_type (type_identifier)) (user_type (type_identifier)))))) (function_body))) ``` -------------------------------- ### Initialize tree-sitter Parser in Javascript Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/README.md Load the Swift language and initialize a tree-sitter parser in Javascript. This sets up the parser for processing Swift code. ```javascript const Parser = require("tree-sitter"); const Swift = require("tree-sitter-swift"); const parser = new Parser(); parser.setLanguage(Swift); // ... const tree = parser.parse(mySourceCode); ``` -------------------------------- ### Swift for-await Loop Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Demonstrates the 'for await' loop for asynchronous iteration over a driver's values. Requires an asynchronous context. ```swift for await _ in await driver.values { // } ``` -------------------------------- ### Function with Renamed Parameters and Call Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Demonstrates a Swift function with external and internal parameter names, and a corresponding function call. ```swift func sum(_ a: Int, with b: Int) { return a + b } ``` ```swift sum(1, with: 2) ``` ```tree-sitter-swift (source_file (function_declaration (simple_identifier) (parameter (simple_identifier) (simple_identifier) (user_type (type_identifier))) (parameter (simple_identifier) (simple_identifier) (user_type (type_identifier))) (function_body (statements (control_transfer_statement (additive_expression (simple_identifier) (simple_identifier)))))) (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (integer_literal)) (value_argument (value_argument_label (simple_identifier)) (integer_literal)))))) ``` -------------------------------- ### For loop with try await Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates a for loop that uses 'try await' to iterate over asynchronous sequences. ```swift for try await value in values { print(value) } ``` ```tree-sitter (source_file (for_statement (try_operator) (pattern (simple_identifier)) (simple_identifier) (statements (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (simple_identifier)))))))) ``` -------------------------------- ### Assigning to Self Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Shows how to assign a value to the `self` keyword, typically used within initializers or methods to set instance properties. ```swift self = .enumCase ``` -------------------------------- ### Swift Playground Image Literal Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Shows how to use playground literals for embedding resources like images. ```swift let playgroundLiteral = #imageLiteral(resourceName: "heart") ``` -------------------------------- ### String Literals Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Illustrates single-line and multi-line string literals, including handling of quotes and comments within strings. ```swift "Hello World!" """ This is a "multiline" string. """ "This string has a // comment (except not!)" ``` -------------------------------- ### Swift Repeat-While Loop Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Demonstrates the 'repeat-while' loop structure, which executes the block at least once before checking the condition. ```swift repeat { // ... } while something() ``` -------------------------------- ### Swift Typealias for Protocol Composition Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates how to create a typealias for a composition of multiple protocols. This simplifies referencing complex protocol types. ```swift class SomeClassWithAlias: NSObject { typealias ProtocolComposition = Protocol1 & Protocol2 } ``` -------------------------------- ### Swift Multiline Regex Literal Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates the syntax for multiline regular expression literals in Swift, including comments within the regex. ```swift let regex = #/ \ # Match a line of the format e.g "DEBIT 03/03/2022 Totally Legit Shell Corp $2,000,000.00" \ (? \\w+) \\s\\s+ \ (? \\S+) \\s\\s+ \ (? (?: (?!\\s\\s) . )+) \\s\\s+ # Note that account names may contain spaces. \ (? .*) \ /# ``` -------------------------------- ### Swift Class Declaration with Type Constraints Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates class declarations with type constraints, including inheritance and equality constraints. ```swift (type_annotation (user_type (type_identifier))) (line_string_literal (line_str_text))))) (class_declaration (user_type (type_identifier)) (type_constraints (where_keyword) (type_constraint (inheritance_constraint (identifier (simple_identifier)) (user_type (type_identifier)))) (type_constraint (equality_constraint (identifier (simple_identifier) (simple_identifier)) (user_type (type_identifier))))) ``` ```swift (class_declaration (modifiers (visibility_modifier)) (user_type (type_identifier)) (type_constraints (where_keyword) (type_constraint (equality_constraint (identifier (simple_identifier)) (tuple_type (tuple_type_item (simple_identifier) (user_type (type_identifier))) ``` ```swift (tuple_type_item (simple_identifier) (user_type (type_identifier))))))) (class_body)) ``` ```swift (class_declaration (array_type (user_type (type_identifier))) (class_body))) ``` -------------------------------- ### Basic Raw String Literal Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Illustrates the creation of a basic raw string literal using pound signs. Raw strings preserve the literal content without interpreting escape sequences. ```swift let _ = #"Hello, world!"# ``` -------------------------------- ### Swift Unicode Escape Sequences Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates the use of Unicode escape sequences in Swift strings for special characters. ```swift let unicodeEscaping = "\u{8}" let anotherUnicode = "…\u{2060}" let infinity = "\u{221E}" ``` -------------------------------- ### Define a Swift class with methods Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt A Swift class containing two simple methods. Each method is defined with a name and an empty body. ```swift class HelloWorld { func a() {} func b() {} } ``` ```tree-sitter-swift (source_file (class_declaration (type_identifier) (class_body (function_declaration (simple_identifier) (function_body)) (function_declaration (simple_identifier) (function_body))))) ``` -------------------------------- ### Add tree-sitter-swift to Javascript Project Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/README.md Include tree-sitter-swift and tree-sitter as dependencies in your project's package.json file for Javascript usage. ```json "dependencies: { "tree-sitter-swift": "0.7.3", "tree-sitter": "^0.22.1" } ``` -------------------------------- ### Navigation with Explicit Type Parameters Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates a navigation expression involving a type with explicit type parameters, including tuple types. ```tree-sitter-swift (source_file (navigation_expression (user_type (type_identifier) (type_arguments (tuple_type) (user_type (type_identifier)))) (navigation_suffix (simple_identifier)))) ``` -------------------------------- ### Swift Extension with Constraints Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates an extension with a 'where' clause to constrain the types that can conform to the extension. This allows for more specific implementations. ```swift extension SpecialDecorator where Self: Decorator, Self.DecoratedType == SpecialType { } ``` -------------------------------- ### Calling a Function with a Closure Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Demonstrates calling the 'test' function using trailing closure syntax. The closure takes an 'Int' value and contains a multiline comment. ```swift test { value in /* does nothing */ } ``` -------------------------------- ### String Interpolation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates how to embed expressions within string literals using string interpolation. ```swift "Sample \("string.interpolation") literal" """ Multiline \("""string interpolation"")" literal """ "This is a string with // a comment in it" """ And so is this! /* #if qwertyuiop And yet neither of those comments should register """ // This comment is valid ``` -------------------------------- ### Function Types with Multiple Parameters Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/types.txt Illustrates function types with multiple parameters, including tuples and nested function types. ```swift a as (Int, Generic, Boolean) -> Unit b as (Nested.Type, (Int)) -> Unit ``` ```tree-sitter-swift (source_file (as_expression (simple_identifier) (as_operator) (function_type (tuple_type (tuple_type_item (user_type (type_identifier))) (tuple_type_item (user_type (type_identifier) (type_arguments (user_type (type_identifier))))) (tuple_type_item (user_type (type_identifier)))) (user_type (type_identifier)))) (as_expression (simple_identifier) (as_operator) (function_type (tuple_type (tuple_type_item (user_type (type_identifier) (type_identifier))) (tuple_type_item (tuple_type (tuple_type_item (user_type (type_identifier))))))) (user_type (type_identifier))))) ``` -------------------------------- ### Swift Property Declaration with Integer Literals Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates property declarations involving integer literals and call expressions. ```swift let x = 1 * 2 let y = 3 + 4 ``` -------------------------------- ### Bitwise Operations Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Illustrates various bitwise operations: AND (&), OR (|), left shift (<<), and right shift (>>). ```swift a & b a | b a << b a >> b ``` ```tree-sitter grammar (source_file (bitwise_operation (simple_identifier) (simple_identifier)) (bitwise_operation (simple_identifier) (simple_identifier)) (bitwise_operation (simple_identifier) (simple_identifier)) (bitwise_operation (simple_identifier) (simple_identifier))) ``` -------------------------------- ### Contextual Keywords as Identifiers Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Demonstrates using contextual keywords like `prefix`, `weak`, and `final` as identifiers in Swift. This code shows valid assignments and declarations. ```swift public init() { // `prefix` doesn't work as a function modifier here, so it's legal as an identifier prefix = prefixToJSON // But some modifiers are legal! weak var weakPrefix = prefix final class LocalClass { } // Annotations are legal too! @someAnnotation func innerFunc() { } } ``` -------------------------------- ### Swift AST for Closure with Parameter and Void Return Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Abstract syntax tree for a Swift closure with a single parameter and a Void return type. ```tree-sitter (source_file (call_expression (simple_identifier) (call_suffix (lambda_literal (lambda_function_type (lambda_function_type_parameters (lambda_parameter (simple_identifier))) (user_type (type_identifier))))))) ``` -------------------------------- ### Class Inheritance with Protocols Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Shows a class 'D' inheriting from multiple protocols ('Protocol1' and 'Protocol2'). ```swift class D : Protocol1 & Protocol2 { } ``` -------------------------------- ### Add tree-sitter-swift to Rust Project Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/README.md Add the tree-sitter and tree-sitter-swift crates to your Cargo.toml file to use the Swift parser in a Rust project. ```toml tree-sitter = "0.23.0" tree-sitter-swift = "=0.7.3" ``` -------------------------------- ### Swift Class Declaration with Generic Type Parameters Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Illustrates a Swift class declaration with generic type parameters and associated attributes. ```swift (source_file (class_declaration (type_identifier) (type_parameters (type_parameter (type_identifier))) (class_body (function_declaration (modifiers (attribute (user_type (type_identifier)) (simple_identifier) (simple_identifier) (line_string_literal (line_str_text)))) (simple_identifier) (function_body)) (property_declaration (modifiers (attribute (user_type (type_identifier)) (simple_identifier) (simple_identifier) (line_string_literal (line_str_text)))) (value_binding_pattern) (pattern (simple_identifier)) (type_annotation (user_type (type_identifier)))) (function_declaration (modifiers (attribute (user_type (type_identifier)) (simple_identifier) (integer_literal) (integer_literal) (integer_literal)) (attribute (user_type (type_identifier)) (simple_identifier) (integer_literal) (integer_literal) (simple_identifier) (integer_literal) (integer_literal))) (simple_identifier) (function_body)))) ``` ```swift (class_declaration (type_identifier) (enum_class_body (enum_entry (simple_identifier)) (enum_entry (modifiers (attribute (user_type (type_identifier)) (simple_identifier) (simple_identifier) (line_string_literal (line_str_text)))) (simple_identifier))))) ``` -------------------------------- ### Swift While Loop with Multiple Conditions Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Illustrates a 'while' loop with two conditions connected by a comma, checking index and input count. ```swift while idx > 0, input.count > 0 { // ... } ``` -------------------------------- ### Swift Class with Various Property Types Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates a Swift class with properties of different types: stored properties with initial values, optional stored properties, lazy stored properties, computed properties with getters, and computed properties with both getters and setters. ```swift class Something { let u: Int = 4 var v: Int? lazy var w: Int = x var x: Int { w } var y: Int { get { v } set(newValue) { } } var z: Int { get { v } set { return v = newValue } } } ``` -------------------------------- ### Tuple Access Operator Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Demonstrates accessing elements of a tuple using dot notation, including optional chaining. ```swift event.0 possibleEvent?.0 ``` ```tree-sitter grammar (source_file (navigation_expression (simple_identifier) (navigation_suffix (integer_literal))) (navigation_expression (simple_identifier) (navigation_suffix (integer_literal)))) ``` -------------------------------- ### Protocol Composition in As Expressions Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Illustrates using protocol composition within an `as` expression for type casting. The variable `result` is assigned the result of calling `greet("me")` and then casting it to the type `P1 & P2`. ```swift let result = greet("me") as P1 & P2 ``` ```tree-sitter-swift (source_file (property_declaration (value_binding_pattern) (pattern (simple_identifier)) (as_expression (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (line_string_literal (line_str_text)))))) (as_operator) (protocol_composition_type (user_type (type_identifier)) (user_type (type_identifier)))))) ``` -------------------------------- ### Swift class with access modifiers and final keyword Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates a Swift class with various access control modifiers (internal, open, private) and the 'final' keyword for methods. Properties also show access control for setting. ```swift internal open class Test { private(set) var isRunning: Bool internal(set) var isFailed: Bool /* some comment */ private final func test() { } } ``` ```tree-sitter-swift (source_file (class_declaration (modifiers (visibility_modifier) (visibility_modifier)) (type_identifier) (class_body (property_declaration (modifiers (visibility_modifier)) (value_binding_pattern) (pattern (simple_identifier)) (type_annotation (user_type (type_identifier)))) (property_declaration (modifiers (visibility_modifier)) (value_binding_pattern) (pattern (simple_identifier)) (type_annotation (user_type (type_identifier)))) (multiline_comment) (function_declaration (modifiers (visibility_modifier) (inheritance_modifier)) (simple_identifier) (function_body))))) ``` -------------------------------- ### Swift Protocol Definition with Property Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Defines a public protocol 'FooProvider' with a non-mutating getter for a 'foo' string property. ```swift public protocol FooProvider { var foo: String { nonmutating get } } ``` -------------------------------- ### Try with Prefix Operation Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Shows the 'try' keyword used with a prefix operation, specifically a negation operator (!), applied to a disjunction of function calls. This pattern is used for handling potential errors in complex conditional logic. ```swift let result = try !(inner1() || inner2()) ``` ```tree-sitter-swift (source_file (property_declaration (value_binding_pattern) (pattern (simple_identifier)) (try_expression (try_operator) (call_expression (bang) (call_suffix (value_arguments (value_argument (disjunction_expression (call_expression (simple_identifier) (call_suffix (value_arguments))) (call_expression (simple_identifier) (call_suffix (value_arguments))))))))))) ``` -------------------------------- ### Swift Protocol Composition with Generic Type Specifiers Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates the use of protocol composition within generic type specifiers in Swift variable declarations. ```swift let result: HasGeneric = HasGeneric(t: "Hello") ``` ```swift (source_file (property_declaration (value_binding_pattern) (pattern (simple_identifier)) (type_annotation (user_type (type_identifier) (type_arguments (protocol_composition_type (user_type (type_identifier)) (user_type (type_identifier)))))) (constructor_expression (user_type (type_identifier) (type_arguments (protocol_composition_type (user_type (type_identifier)) (user_type (type_identifier))))) ``` ```swift (constructor_suffix (value_arguments (value_argument (value_argument_label (simple_identifier)) (line_string_literal (line_str_text)))))))) ``` -------------------------------- ### Swift Class with Nonisolated Property Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates a class 'Registry' with a static, nonisolated(unsafe) property for instance management. ```swift class Registry { nonisolated(unsafe) static var instance = Registry() } ``` -------------------------------- ### Calling async function with keyword arguments Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Illustrates calling an asynchronous function where argument labels might conflict with keywords. ```swift async(async: async, qos: qos, flags: flags) { work() } ``` ```tree-sitter (source_file (call_expression (simple_identifier) (call_suffix (value_arguments (value_argument (value_argument_label (simple_identifier)) (simple_identifier)) (value_argument (value_argument_label (simple_identifier)) (simple_identifier)) (value_argument (value_argument_label (simple_identifier)) (simple_identifier))) (lambda_literal (statements (call_expression (simple_identifier) (call_suffix (value_arguments)))))))) ``` -------------------------------- ### Custom Operator Usage Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Demonstrates the use of a custom operator '???' with a string literal as a fallback value. ```swift let messageCoerced = error ??? "nil" ``` -------------------------------- ### Swift: Emoji Function with Complex Parameters Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/emojis.txt Demonstrates defining and calling a Swift function that uses a complex emoji as its name and accepts parameters with emoji labels. ```swift func πŸ‘¨β€β€οΈβ€πŸ’‹β€πŸ‘¨(πŸ™‹πŸΌβ€β™‚οΈ πŸ™‹β€β™‚οΈ: Man, πŸ™‹πŸ»β€β™‚οΈ πŸ™‹β€β™‚οΈ2: Man) { } πŸ‘¨β€β€οΈβ€πŸ’‹β€πŸ‘¨(πŸ™‹πŸΌβ€β™‚οΈ: a, πŸ™‹πŸ»β€β™‚οΈ: b) ``` -------------------------------- ### Swift Property Wrapper Projection for State Binding Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/expressions.txt Shows how to use property wrapper projections with the '$' prefix to access the underlying wrapped value, often used for binding state in UI frameworks. ```swift Image.url(url, isLoaded: $done) ``` -------------------------------- ### Swift Raw Identifiers with Spaces Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/statements.txt Shows how to use raw identifiers, including those with spaces, for variables and function names as per SE-0451. ```swift let `my value` = 5 func `my function`() {} ``` -------------------------------- ### Swift Protocol Composition Type Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/classes.txt Demonstrates a property declaration using protocol composition, combining multiple protocols. ```swift var propertyMap: NodePropertyMap & KeypathSearchable { return transformProperties } ``` -------------------------------- ### Swift AST for Closure with Optional Parameter and Call Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/functions.txt Abstract syntax tree for a Swift closure with an optional parameter and a subsequent function call. ```tree-sitter (source_file (call_expression (simple_identifier) (call_suffix (lambda_literal (lambda_function_type (lambda_function_type_parameters (lambda_parameter (simple_identifier) (optional_type (user_type (type_identifier)))))) ``` -------------------------------- ### Real Literals Source: https://github.com/alex-pinkus/tree-sitter-swift/blob/main/test/corpus/literals.txt Demonstrates different ways to represent floating-point numbers, including decimal and scientific notation, and hexadecimal floating-point literals. ```swift 0.0 -23.434 1e-10 4.3 +53.9e-3 0x1.921F_B600p1 ```