Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does type inference (automatic type detection) works in swift?

Tags:

xcode

ios

swift

var str = "string"

How does the LLVM detect the variable is a string?

like image 825
riyaz Avatar asked Feb 28 '15 08:02

riyaz


People also ask

Does Swift allow type inference?

However, that's often not something that needs to be done manually, instead the compiler is able to figure out a wide range of type information on its own — thanks to the fact that Swift supports type inference.

What is meant by type inference?

Type inference is the ability to automatically deduce, either partially or fully, the type of an expression at compile time. The compiler is often able to infer the type of a variable or the type signature of a function, without explicit type annotations having been given.

What is type annotation in Swift?

In Swift Programming Language guide, it has this definition for Type Annotation: "A type annotation explicitly specifies the type of a variable or expression." We all know how to specify the type of a variable, but how exactly do you specify the type of an expression?


1 Answers

The compiler does its job in steps and type inference is one step in this process.

Step 1: Lexical analysis

Typically, as a first step, the compiler does a lexical analysis in which it splits input file bytes to units like numbers and strings (note: not yet string in the same meaning that you are referring) and throws away whitespace and comments.

For example, it splits the input stream in the example to var, str, =, ", string, ".

Step 2: Syntax analysis

The second step is a syntax analysis or parsing, in which compiler constructs and verifies an abstract syntax tree based on the grammar of the language.

In this case it would construct an abstract syntax tree representing a variable declaration statement (see Declaration statements in the language reference) of the form:

var variable_name = expression

in which expression is a string literal:

var variable_name = string_literal

Step 3: Semantic analysis (with type inference)

The third step is semantic analysis and type inference happens in this step. In this case, type inference infers that the type of string literal is String and because there is no other information about the variable str, it will infer that str must be a String, because the expression, the right hand side of the variable declaration, is of type String.

There are more steps after this step. As next steps, the compiler typically generates intermediate code, then optimizes the intermediate code, and finally generates assembly code. After that the tool chain outside of the compiler usually has at least a linking phase that produces the final executable.

like image 154
Teemu Kurppa Avatar answered Oct 13 '22 00:10

Teemu Kurppa