The Swift Programming Language

Swift logo

Swift Programming Language

Architecture main Package
macOS x86_64 Build Status Build Status
Ubuntu 16.04 x86_64 Build Status Build Status
Ubuntu 18.04 x86_64 Build Status Build Status
Ubuntu 20.04 x86_64 Build Status Build Status
CentOS 8 x86_64 Build Status Build Status
CentOS 7 x86_64 Build Status Build Status
Amazon Linux 2 x86_64 Build Status Build Status

Swift Community-Hosted CI Platforms

OS Architecture Build
Ubuntu 16.04 PPC64LE Build Status
Ubuntu 18.04 AArch64 Build Status
Ubuntu 20.04 AArch64 Build Status
Ubuntu 20.04 wasm32 Build Status
Android ARMv7 Build Status
Android AArch64 Build Status
Windows 2019 (VS 2017) x86_64 Build Status
Windows 2019 (VS 2019) x86_64 Build Status

Welcome to Swift

Swift is a high-performance system programming language. It has a clean and modern syntax, offers seamless access to existing C and Objective-C code and frameworks, and is memory safe by default.

Although inspired by Objective-C and many other languages, Swift is not itself a C-derived language. As a complete and independent language, Swift packages core features like flow control, data structures, and functions, with high-level constructs like objects, protocols, closures, and generics. Swift embraces modules, eliminating the need for headers and the code duplication they entail.

To learn more about the programming language, visit swift.org.

Contributing to Swift

Contributions to Swift are welcomed and encouraged! Please see the Contributing to Swift guide.

To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone.

To give clarity of what is expected of our members, Swift has adopted the code of conduct defined by the Contributor Covenant. This document is used across many open source communities, and we think it articulates our values well. For more, see the Code of Conduct.

Getting Started

If you are interested in:

We also have an FAQ that answers common questions.

Swift Toolchains

Building

Swift toolchains are created using the script build-toolchain. This script is used by swift.org's CI to produce snapshots and can allow for one to locally reproduce such builds for development or distribution purposes. A typical invocation looks like the following:

  $ ./swift/utils/build-toolchain $BUNDLE_PREFIX

where $BUNDLE_PREFIX is a string that will be prepended to the build date to give the bundle identifier of the toolchain's Info.plist. For instance, if $BUNDLE_PREFIX was com.example, the toolchain produced will have the bundle identifier com.example.YYYYMMDD. It will be created in the directory you run the script with a filename of the form: swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz.

Beyond building the toolchain, build-toolchain also supports the following (non-exhaustive) set of useful options::

  • --dry-run: Perform a dry run build. This is off by default.
  • --test: Test the toolchain after it has been compiled. This is off by default.
  • --distcc: Use distcc to speed up the build by distributing the c++ part of the swift build. This is off by default.
  • --sccache: Use sccache to speed up subsequent builds of the compiler by caching more c++ build artifacts. This is off by default.

More options may be added over time. Please pass --help to build-toolchain to see the full set of options.

Installing into Xcode

On macOS if one wants to install such a toolchain into Xcode:

  1. Untar and copy the toolchain to one of /Library/Developer/Toolchains/ or ~/Library/Developer/Toolchains/. E.x.:
  $ sudo tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz -C /
  $ tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz -C ~/

The script also generates an archive containing debug symbols which can be installed over the main archive allowing symbolication of any compiler crashes.

  $ sudo tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx-symbols.tar.gz -C /
  $ tar -xzf swift-LOCAL-YYYY-MM-DD-a-osx-symbols.tar.gz -C ~/
  1. Specify the local toolchain for Xcode's use via Xcode->Toolchains.

Build Failures

Try the suggestions in Troubleshooting build issues.

Make sure you are using the correct release of Xcode.

If you have changed Xcode versions but still encounter errors that appear to be related to the Xcode version, try passing --clean to build-script.

When a new version of Xcode is released, you can update your build without recompiling the entire project by passing --reconfigure to build-script.

Learning More

Be sure to look at the documentation index for a bird's eye view of the available documentation. In particular, the documents titled Debugging the Swift Compiler and Continuous Integration for Swift are very helpful to understand before submitting your first PR.

Comments
  • +0 Guaranteed Arguments

    +0 Guaranteed Arguments

    This PR contains the final work to convert the compiler to +0. There are still some tests failing, but I would like to get start performing PR testing of the branch.

  • test: migrate tests to Python3 by default

    test: migrate tests to Python3 by default

    This changes the python interpreter used to invoke the tests to Python3. Python2 has been EOL'ed by the Python Software Foundation. This migration enables the Swift test suite to run with Python 3 instead.

    Replace this paragraph with a description of your changes and rationale. Provide links to external references/discussions if appropriate.

    Resolves SR-NNNN.

  • [DO NOT MERGE] [WIP] StringGuts

    [DO NOT MERGE] [WIP] StringGuts

    An initial implementation of a more resilient 2-word representation for String. It uses BridgeObject (for now) to achieve a high degree of resilience. In the future, we'll add more small string forms, establish UnsafeString, and generally rejigger String's views to be properly layered on top.

    Notes:

    • Self slices are currently implemented by forming _NSContiguousStrings to hold the sliced up _StringCore. This incurs overhead. Long term, we could support owned self slices, but for now it would be fruitful to try to eliminate all uses of self-slicing _StringCore from the stdlib. The most common occurrence (but by no means the only) is through _ephemeralString. Instead, for anything that can't possibly escape, we should convert to an UnsafeString, guarantee the lifetime, and slice that up.

    • We cannot utilize small representations effectively until we start to wean ourselves off of _LegacyStringCore. Ideally (depending on project planning needs) we would be fully weaned off before adding small representations. We'd also like to get close to performance parity where it matters prior, to better gauge the impact of such optimizations.

    • The spiritual predecessor to this effort is at https://github.com/dabrahams/swift/commits/string-recore, and while the physical implementation differs, that's a great demonstration of what we're trying to accomplish.

  • Change diagnostic error thrown for when string interpolations aren't closed by a parenthesis

    Change diagnostic error thrown for when string interpolations aren't closed by a parenthesis

    This pull request changes the diagnostic error thrown when a string interpolation isn't closed by a parenthesis properly (ie: let x = "g \(")

    Previously, it would blurt out unterminated string literal, with these changes it'll instead throw expected ')' at end of string interpolation

  • [metadata prespecialization] Support for classes.

    [metadata prespecialization] Support for classes.

    When generic metadata for a class is requested in the same module where the class is defined, rather than a call to the generic metadata accessor or to a variant of typeForMangledNode, a call to a new accessor--a canonical specialized generic metadata accessor--is emitted. The new function is defined schematically as follows:

        MetadataResponse `canonical specialized metadata accessor for C<K>`(MetadataRequest request) {
          (void)`canonical specialized metadata accessor for superclass(C<K>)`(::Complete)
          (void)`canonical specialized metadata accessor for generic_argument_class(C<K>, 1)`(::Complete)
          ...
          (void)`canonical specialized metadata accessor for generic_argument_class(C<K>, count)`(::Complete)
          auto *metadata = objc_opt_self(`canonical specialized metadata for C<K>`);
          return {metadata, MetadataState::Complete};
        }
    

    To enable these new canonical specialized generic metadata accessors, metadata for generic classes is prespecialized as needed. So are the metaclasses and the corresponding rodata.

    Previously, the lazy objc naming hook was registered during process execution when the first generic class metadata was instantiated. Since that instantiation may occur "before process launch" (i.e. if the generic metadata is prespecialized), the lazy naming hook is now installed at process launch.

  • Add support for calling C++ constructors

    Add support for calling C++ constructors

    A problem that we have to deal with when calling C++ constructors is that the ABI of a C++ constructor depends not only on the signature of the constructor but on the class on which it is defined. For example, it can be necessary to pass additional “implicit” arguments to constructors of virtual base classes.

    It is therefore fundamentally not possible for SignatureExpansion (which doesn’t have access to the CXXConstructorDecl) to reliably produce the correct LLVM signature from only the type of the constructor. The approach we take is to try to get most of the way in SignatureExpansion by marking the SIL function return type with the @out attribute, representing the fact that C++ constructors take a this points to the object to be initialized.

    This produces an “assumed” constructor ABI in SignatureExpansion that assumes there are no implicit arguments and that the return type of the constructor ABI is void (and indeed there is no way to represent anything else in the SIL type). If this assumed ABI doesn’t match the actual ABI, we insert a thunk in IRGen.

    The thunk is marked alwaysinline, so it doesn’t incur any runtime overhead, but some compile-time overhead is required for LLVM to inline the thunk. If this turns out to be excessive, we can introduce what is essentially a peephole optimization for a full apply of a function_refthat refers to a C++ constructor and directly emit the constructor call in this case (along with any required implicit arguments) instead of calling the thunk. I’ve chosen not to tackle that in this PR though as it’s already large enough.

    On some ABIs (e.g. Itanium x64), we get lucky and the ABI for a complete constructor call always matches the assumed ABI.

    In addition to the core C++ constructor functionality, this PR adds some a couple of small required features:

    • Conversion of thin to a Clang void type
    • Handling of formal indirect results in SignatureExpansion::expandExternalSignatureTypes()
  • Smol String

    Smol String

    Add in small strings, plumb all APIs through, etc. There's some current performance issues, namely that small string support introduces branching and our default implementation technique involves spilling to the stack and calling _UnmanagedString methods. The first is unavoidable (although we're planning a better overall branching strategy to reduce this impact), the second is TODO.

  • [CS] Use fixes to diagnose instance member on type (or vice versa) access

    [CS] Use fixes to diagnose instance member on type (or vice versa) access

    This PR migrates instance member on type and type member on instance diagnostics handling to use the new diagnostics framework (fixes) and create more reliable and accurate diagnostics in such scenarios.

  • [SE-0283] Implement Equatable, Comparable, and Hashable conformance for Tuples

    [SE-0283] Implement Equatable, Comparable, and Hashable conformance for Tuples

    From: https://forums.swift.org/t/hacking-equatable-conformance-on-void/25975

    The tests right now are kind of lackluster, what else can I be testing with this? What else can be improved upon in this implementation? Is there an edge case that I hadn't thought about?

    cc: @jckarter @rjmccall

  • [SR-381] API to lookup a Type given a top-level class name

    [SR-381] API to lookup a Type given a top-level class name

    | | | |------------------|-----------------| |Previous ID | SR-381 | |Radar | None | |Original Reporter | @lhoward | |Type | New Feature | |Status | Closed | |Resolution | Done |

    Additional Detail from JIRA

    | | | |------------------|-----------------| |Votes | 1 | |Component/s | Standard Library | |Labels | New Feature, AffectsABI, Runtime | |Assignee | @jckarter | |Priority | Medium |

    md5: 13f1c2ae7174aab8983f1dde3a976c53

    blocks:

    • SR-377 Implement NSKeyed[Un]Archiver

    relates to:

    • SR-412 Linux: Cannot define C function pointer that returns metaclass

    Issue Description:

    This may be useful to implement NSStringFromClass()-compatible behaviour which is necessary in order to implement NSKeyedArchiver. I am using the attached workaround at the moment but obviously it is very fragile.

  • [DNM] String interpolation rework

    [DNM] String interpolation rework

    Implements apple/swift-evolution#904.

    This is the implementation of the string interpolation rework. It is now feature-complete, but there are still a few things on my to-do list:

    • ~~It's performing similarly to the current design overall, although individual benchmarks vary wildly—from 1.80x for StringInterpolationSmall to 0.59x for FloatingPointPrinting_Float_interpolated. (Some of the improvements in tests which have little to do with string interpolation are probably thanks to new overloads of String.init(describing:) I added to preserve source compatibility.) We want it to be faster than the status quo. I haven't dug deeply into this yet, and I'd like a second opinion from the CI.~~

    • I'm wondering if it would be useful for DefaultStringInterpolation to become moveonly in the future, and if so, if that could be done without breaking ABI compatibility. @rjmccall, what do you think?

    • There are a couple of test failures I'm not sure what to do with:

      • ~~Constraints/rdar42678836.swift was apparently added three days ago and has already had its message change twice. @slavapestov, @xedin, can we pin down what this test ought to do?~~

      • IDE/complete_at_top_level.swift fails because we don't suggest a Void function in a string interpolation. I think that comes from this line, which looks like it's intended to prevent you from completing a Void function where a value is expected, but I'm just guessing at its purpose. Can anyone clear up my confusion and help me figure out what this should be doing? (@nkcsgexi wrote this, but it was years ago.)

    @swift-ci Please benchmark

    cc @milseman

  • Disable SROA debug info for variables with expressions

    Disable SROA debug info for variables with expressions

    Currently the SROA just overwrites already-existing expressions on variables. When SROA is recursively run on a data structure this leads to nonsensical expressions such as

    type $*Outer, expr op_fragment:#Inner.x

    instead of

    type $*Outer, expr op_fragment:#Outer.inner op_fragment:#Inner.x

    The (nonsensical) LLVM IR generated from this violates some assumptions in LLVM for example, if a struct has multiple members of the same type, you can end up with multiple dbg.declare intrinsics claiming to describe the same variable). As a quick fix, this patch detects this situation and drops the debug info. A proper fix shouldn't be too difficult to implement though.

    rdar://99874371

  • [Sanitizer] Deflake TSan test

    [Sanitizer] Deflake TSan test

    This test does:

    race()
    print("Done!")
    
    // CHECK: ThreadSanitizer: data race
    // CHECK: Done!
    

    We see some recent cases where the output of the test binary on iOS devices was:

    Done!
    ==================
    WARNING: ThreadSanitizer: data race
    …
    

    So apparently the TSan report output is not guaranteed to be printed before "Done!". Maybe this is because we print "Done!" on stdout and the sanitizer report on stderr?

    The remaining question is: what changed that we are seeing this issue now, but not previously?

    rdar://99713724

  • [Sanitizer] Deflake test tsan libdispatch

    [Sanitizer] Deflake test tsan libdispatch

    This test does:

    race()
    print("Done!")
    
    // CHECK: ThreadSanitizer: data race
    // CHECK: Done!
    

    We see some recent cases where the output of the test binary on iOS devices was:

    Done!
    ==================
    WARNING: ThreadSanitizer: data race
    …
    

    So apparently the TSan report output is not guaranteed to be printed before "Done!". Maybe this is because we print "Done!" on stdout and the sanitizer report on stderr?

    The remaining question is: what changed that we are seeing this issue now, but not previously?

    rdar://99713724 (cherry picked from commit 35c7c4185ccc78edfcc6cc61f42361eaab25dd53)

  • Missing isolation check within closure passed as event handler

    Missing isolation check within closure passed as event handler

    Describe the bug Isolation checker does not raise error when actor isolated state is accesses from event handler closures.

    Steps To Reproduce Steps to reproduce the behavior:

    1. Compile snipped of code below:
    import Foundation
    import Combine
    
    actor MyActor {
      private var state = 0
      private var subscribtion: AnyCancellable?
    
      func subscribe() {
        subscribtion = NotificationCenter.default.publisher(for: .NSCalendarDayChanged).sink { [self] _ in
          self.state += 1
        }
      }
    }
    
    actor MyActor2 {
      private var state = 0
      private var subscribtion: Any?
    
      func subscribe() {
        subscribtion = NotificationCenter.default.addObserver(forName: .NSCalendarDayChanged, object: nil, queue: nil) { [self] _ in
          self.state += 1
        }
      }
    }
    

    ...

    Expected behavior An closure can not be directly executed within actor context, so compiler should raise an error accessing isolated state from closure.

    Screenshots If applicable, add screenshots to help explain your problem.

    Environment (please fill out the following information)

    • OS: MacOS 12.6
    • Xcode 14.0 (14A309):

    Additional context It might be due to the fact that closures in signatures are not currently marked as @Sendable and compiler assumes no context change happen compared to event subscription side which is inside actor. Maybe compiler should be less optimistic regarding @escaping closures by default or maybe there should be another compiler setting which will turn on pessimistic mode for @escaping closures treating them as @Sendable automatically.

  • [Sema] Skip adding solutions to completion callback if needed

    [Sema] Skip adding solutions to completion callback if needed

    If CompletionContextFinder fails to find a CompletionNode, skip trying to filter and add solutions to the completion callback. This prevents an assertion/crash in filterSolutionsForCodeCompletion which assumes CompletionNode is non-null (either an expression or keypath).

    Resolves rdar://99966094.

Related tags
Swift Framework for Apple Health Integration with Terra Enabling Developers LTD.

TerraSwift This library allows developers to connect to TERRA ENABLING DEVELOPERS LTD. through Swift (implemented with Swift5.0). This library uses He

Mar 18, 2022
PoC of Swift for [email protected]

FastlyEdgeExample An example project to deploy Swift code to Fastly's [email protected] Requirements SwiftWasm toolchain fastly CLI How to deploy $ fastly

May 21, 2022
PLP Project Programming Language | Programming for projects and computer science and research on computer and programming.
PLP Project Programming Language | Programming for projects and computer science and research on computer and programming.

PLPv2b PLP Project Programming Language Programming Language for projects and computer science and research on computer and programming. What is PLP L

Aug 20, 2022
StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that of JavaScript's and TypeScript's

StarkScript StarkScript - or the Stark programming language - is a compiled C-based programming language that aims to offer the same usability as that

May 10, 2022
frost is a programming language with a focus on low-friction systems programming.

❄️ frost frost programming language About frost is a programming language with a focus on low-friction systems programming.

Nov 12, 2021
The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.

Wren is a small, fast, class-based concurrent scripting language Think Smalltalk in a Lua-sized package with a dash of Erlang and wrapped up in a fami

Sep 21, 2022
Competitive Programming - Programming👨‍💻 Questions on BinarySearch💻, LeetCode💻, CodeChef💻, Codeforces💻,DSA 450
Competitive Programming - Programming👨‍💻  Questions on BinarySearch💻, LeetCode💻, CodeChef💻, Codeforces💻,DSA 450

?? Hacktoberfest2021 ?? This repository is open to all members of the GitHub community. Any member can contribute. Contribute according to the steps g

Sep 6, 2022
J is an array programming language

J: From C to C++20 J is an array programming language created by Ken Iverson and Roger Hui (see image below).

Aug 20, 2022
A minimal viable programming language on top of liblgpp

This project aims to implement a minimal viable programming language on top of liblgpp. setup The project requires a C++17 compiler, CMake and liblgpp

Jun 28, 2021
A perfect blend of C, Java, and Python tailored for those who desire a simple yet powerful programming language.

Fastcode A perfect blend of C, Java, and Python tailored for those who desire a simple yet powerful programming language. FastCode is a procedural/str

Aug 19, 2022
Loop is an object oriented programming language
Loop is an object oriented programming language

Loop Loop is an object oriented programming language. How do I build and run loop? Make sure, you installed the requirements for clang and make: Debia

Aug 9, 2021
C implementation of the Monkey programming language.
C implementation of the Monkey programming language.

Development of this interpreter continues here: dannyvankooten/pepper-lang C implementation of the Monkey programming language. Bytecode compiler and

Aug 30, 2022
A programming language made in C

1. Fang A programming language made in C 1.1. Meaning Fang stands for "Feline Language". In hopes of it being cool like a cat! On top of it, you can b

Apr 8, 2021
AHHH: a programming language for the dreadful
AHHH: a programming language for the dreadful

AHHH: a programming language for the dreadful Screaming into the Void but make it Turing Complete AHHH is an esoteric programming language inspired by

Aug 12, 2022
Pandex is a light but FAST programming language written in C . Pandex goal is that be hard & it's good for eductional goals

The Pandex programming language version 1.0.0.3 Pandex versions release type The Pandex version has four numbers. the first number holds 1 ( or 0 in s

May 23, 2022
Arobase is a simple programming language with a c-like syntax.
Arobase is a simple programming language with a c-like syntax.

Arobase Arobase is a simple programming language with a c-like syntax. Requirements gcc gas (gnu as) ld A 64 bits linux distribution (generated assemb

Aug 29, 2022
C+- is a personal project trying to make a programming language.
C+- is a personal project trying to make a programming language.

C+- A personal project trying to be a programming language with close resemblence to C/C++ (probably gonna fail at that).

Mar 26, 2022
Simple String_View implementation for C programming language.

Simple String_View implementation for C programming language.

Sep 5, 2022