var str = "string"
How does the LLVM detect the variable is a string?
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.
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.
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?
The compiler does its job in steps and type inference is one step in this process.
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
, "
.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With