SlideShare una empresa de Scribd logo
1 de 29
/29
Kotlin
Kotlin
Compiler Construction
Nurgaliev Ildar
/29
Kotlin
Why?
One reason is enough:
Java platform and Java language there is huge gap
/29
Kotlin
Chalenges in JVM language design.
/29
Kotlin
Introduction
● Statically typed
● Compiles to JVM byte codes or JavaScript
● JVM version is Java compatible both ways
● Intended for industrial use
o Designed for READABILITY
o Relies simple (but powerful) abstractions
o Performance is a priority
o Tooling matters
● Open Source (Apache 2)
o http://github.com/JetBrains/Kotlin
/29
Kotlin
Keywords
for
while
match
case
if
then
else
do
return
fun
initial
in
val
var
null
continue
String
package
class
private
void
internal
protected
/29
Kotlin
Java
type
Kotlin type
byte kotlin.Byte
short kotlin.Short
int kotlin.Int
double kotlin.Double
boolean kotlin.Boolean
Mapped types
Kotlin treats some Java types specially. Such types are
not loaded from Java “as is”, but are mapped to
corresponding Kotlin types. The mapping only matters
at compile time, the runtime representation remains
unchanged. Java’s primitive types are mapped to
corresponding Kotlin types (keeping platform types in
mind):
java.lang.Object kotlin.Any!
int[] kotlin.IntArray!
/29
Kotlin
Basic syntax
● You do not need ; to break statements.
● Comments are similar to Java or C#, /* This is comment */ for multi line comments and // for single line
comment.
● Unlike Java, you do not need to match your file name to your class name.
● Like JavaScript, you can create functions outside classes. So there is no need to stuff your functions as static
members of classes like what you do in C# or Java.
● Kotlin has string templates, which is awesome. e.g. "$firstName $lastName" for simple variable name or
"${person.name} is ${1 * 2}" for any expressions. You can still do the string concatenation if you like e.g.
"hello " + "world", but that means being stupid.
● It has no tuple although Kotlin's data classes is an option to use in place of tuple.
● Use function literals to filter and map collections: basic functional programming inside
/29
Kotlin
Variable semantic
● There are two keywords for variable declaration, var and val.
● Use var when the variable value is to be modified and val where the variable value will not change after first
assigned.
● This val is similar to readonly keyword in C# or final keyword in Java.
● val variable must be initialized at declaration.
● Unlike Java or C#, you declare the type of a variable after the name, e.g. var firstName : String
● Number primitive types are as follows: Double, Float, Long, Int, Short, Byte. There is no automatic conversion
between types. You have to explicitly convert them.
● More primitive types: Char, String, Boolean.
● All variable declarations in Kotlin must be initialized.
/29
Kotlin
Identifiers
4 types of identifiers supported by Scala:
● ALPHANUMERIC IDENTIFIERS
● OPERATOR IDENTIFIERS
● LITERAL IDENTIFIERS
/29
Kotlin
ALPHANUMERIC IDENTIFIERS
● An ALPHANUMERIC IDENTIFIERS starts with a letter or underscore,
which can be followed by further letters, digits, or underscores.
● '$' character is a reserved keyword
Legal alphanumeric identifiers:
age, salary, _value, __1_value
Illegal identifiers:
$salary, 123abc, -salary
/29
Kotlin
grammar
На сайте выложено, EBNF
/29
Kotlin
Semantic
- arrays the index used in an array selection expression must be of
integer type
- expressions the two operands to logical && must both be bool type, the result
is bool type
- functions the type of each actual argument in a function call must be
compatible with the formal parameter
- classes if specified, the parent of a class must be a properly declared class
type
- interfaces all methods of the interface must be implemented if a class states
that it implements the interface
/29
Kotlin
Semantic (easy stuff)
Class names can be used before being defined
• We can’t check class names
– using a symbol table
– or even in one pass
• Solution
– Pass 1: Gather all class names
– Pass 2: Do the checking
/29
Kotlin
AST
– Before: Process an AST node n
– Recurse: Process the children of n
– After: Finish processing the AST node n
/29
Kotlin
Example AST rules
● Before processing e, add definition of x to current
definitions, overriding any other definition of x
● – Recurse
● – After processing e, remove definition of x and restore
old definition of x
for (x : Char in “abc”){ ( x )
Expressions…. ( e )
}
/29
Kotlin
Symbol table operations
● addSymbol(x) push x and associated info, such as
x’s type, on the stack
● findSymbol(x) search stack, starting from top, for
x. Return first x found or NULL if none found
● removeSymbol() pop the stack
● enterScope() start a new nested scope
● findSymbol(x) finds current x (or null)
● addSymbol(x) add a symbol x to the table
● checkScope(x) true if x defined in current scope
● exitScope() exit current scope
/29
Kotlin
Recall to symbol tables for resolving
fun main(args: Array<String>) {
if (args.size == 0) {
println("Provide a name")
return
}
println("Hello, ${args[0]}!")
//String Interpolation to cut down ceremony.
}
/29
Kotlin
Method declaration
● Method names have complex rules
● A method need not to be defined in the class in which it
is used, but in some parent class
● Methods may also be redefined (overridden) (Hard point)
/29
Kotlin
Type checking
Type checking computes via reasoning:
If E1 and E2 have certain types, then E3 has a certain type
(e1 : Int AND e2: Int) IMPLIES e1 + e2: Int
We work with hypotheses and conclusions.
So we create type rules.
Ex: is add minus
/29
Kotlin
Type checking
Type checking proves facts e: T
– Proof is on the structure of the AST
– Proof has the shape of the AST
– One type rule is used for each AST node
• In the type rule used for a node e:
– Hypotheses are the proofs of types of e’s subexpressions
– Conclusion is the type of e
• Types are computed in a bottom-up pass over the AST
/29
Kotlin
Type environment before type check
The type environment gives types to the free
identifiers in the current scope
• The type environment is passed down the AST from
the root towards the leaves
• Types are computed up the AST from the leaves
towards the root
/29
Kotlin
Subtyping
Consider:
if e0 then e1 else e2
• The result can be either e1 or e2
• The type is either e1’s type or of e2’s type
• The best we can do is the smallest supertype larger than the type of e1 or e2
/29
Kotlin
Subtyping
lub(X,Y), the Least Upper Bound of X and Y, is Z if
– X ⩽ Z AND Y ⩽ Z
Z is an upper bound
– X ⩽ Z’ AND Y ⩽ Z’ IMPLIES Z ⩽ Z’
Z is least among upper bounds
so the least upper bound of two types is their
least common ancestor in the inheritance tree
/29
Kotlin
Subtyping
Ex 2: The rule for case expressions takes a lub over all branches
Ex 1: if-Then-Else
/29
Kotlin
Typing methods
prelude: A method foo and an object foo can coexist in the
same scope
• In the type rules, this is reflected by a separate mapping
M for method signatures
M(C,f) = (T1,. . .Tn,Tn+1)
means in class C there is a method f
f(x1:T1,. . .,xn:Tn): Tn+1 the last one is type of return st
/29
Kotlin
Polymorphism (Self type)
class Count {
val i = 0;
fun inc() : Count {
i++
return this
}
};
inc() should return “dynamic type”
class Stock extends Count(var name:String)
{
};
fun main(args: Array<>String){
val a = Stock(“test”)
a = (new Stock).inc (); // fail
… a.name …
};
/29
Kotlin
Polymorphism (Self type)
– So, we must redefine inc for each of the subclasses, with a specialized return
type
● Introduce the keyword SELF_TYPE to use for the return value of such
functions
SELF_TYPE is not a dynamic type
– It is a static type
– It helps the type checker to keep better track of types
– It enables the type checker to accept more correct
programs
/29
Kotlin
Semantic
Else one Hard aspect:
1) Lamda expressions as new feature of the language:
val positiveNumbers = list.filter {it > 0}
Правила редукции типовых и без типовых лямбда исчислений
Область видимо-сти. Операционная семантика, виды редукций.
Представление термов без использования имён (индексы де Брауна)
Безопасность, продвижение, сохранение.
Простое типизированное лямбда-исчисление: Типы функций.
Отношение типизации. Свойства типизации. Соответствие Карри–Говарда(введения
устранения, при совпадении вычисление).
Стирание типов и типизируемость
/29
Kotlin
Code generation
Вряд ли я с этим справлюсь

Más contenido relacionado

La actualidad más candente

It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About MorphismsUberto Barbini
 
FINITE STATE MACHINE AND CHOMSKY HIERARCHY
FINITE STATE MACHINE AND CHOMSKY HIERARCHYFINITE STATE MACHINE AND CHOMSKY HIERARCHY
FINITE STATE MACHINE AND CHOMSKY HIERARCHYnishimanglani
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysisDattatray Gandhmal
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite AutomataRatnakar Mikkili
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Alexander Podkhalyuzin
 
Java moderno java para Jedis episodio I
Java moderno  java para  Jedis  episodio IJava moderno  java para  Jedis  episodio I
Java moderno java para Jedis episodio IRoan Brasil Monteiro
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysisraosir123
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slidesrfojdar
 
Finite automata examples
Finite automata examplesFinite automata examples
Finite automata examplesankitamakin
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Iffat Anjum
 
Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Daniyal Mughal
 

La actualidad más candente (20)

It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
FINITE STATE MACHINE AND CHOMSKY HIERARCHY
FINITE STATE MACHINE AND CHOMSKY HIERARCHYFINITE STATE MACHINE AND CHOMSKY HIERARCHY
FINITE STATE MACHINE AND CHOMSKY HIERARCHY
 
Finite automata
Finite automataFinite automata
Finite automata
 
Finite Automata
Finite AutomataFinite Automata
Finite Automata
 
Lecture: Automata
Lecture: AutomataLecture: Automata
Lecture: Automata
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysis
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite Automata
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 
Finite automata
Finite automataFinite automata
Finite automata
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
 
Template classes and ROS messages
Template classes and ROS messagesTemplate classes and ROS messages
Template classes and ROS messages
 
Lexical
LexicalLexical
Lexical
 
Java moderno java para Jedis episodio I
Java moderno  java para  Jedis  episodio IJava moderno  java para  Jedis  episodio I
Java moderno java para Jedis episodio I
 
Ch2 finite automaton
Ch2 finite automatonCh2 finite automaton
Ch2 finite automaton
 
02. chapter 3 lexical analysis
02. chapter 3   lexical analysis02. chapter 3   lexical analysis
02. chapter 3 lexical analysis
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
 
Optimization of dfa
Optimization of dfaOptimization of dfa
Optimization of dfa
 
Finite automata examples
Finite automata examplesFinite automata examples
Finite automata examples
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6Type checking compiler construction Chapter #6
Type checking compiler construction Chapter #6
 

Similar a Kotlin compiler construction (very brief)

Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiNico Ludwig
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlinZoran Stanimirovic
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_iNico Ludwig
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programmingNico Ludwig
 
Finals-review.pptx
Finals-review.pptxFinals-review.pptx
Finals-review.pptxamara jyothi
 
c programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPTc programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPTKauserJahan6
 
A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...bhargavi804095
 
Introduction to Problem Solving C Programming
Introduction to Problem Solving C ProgrammingIntroduction to Problem Solving C Programming
Introduction to Problem Solving C ProgrammingRKarthickCSEKIOT
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfssusera0bb35
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and conceptsNicola Bonelli
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programmingNico Ludwig
 

Similar a Kotlin compiler construction (very brief) (20)

Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 
9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin9054799 dzone-refcard267-kotlin
9054799 dzone-refcard267-kotlin
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
Finals-review.pptx
Finals-review.pptxFinals-review.pptx
Finals-review.pptx
 
Chapter02.PPT
Chapter02.PPTChapter02.PPT
Chapter02.PPT
 
c programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPTc programming 2nd chapter pdf.PPT
c programming 2nd chapter pdf.PPT
 
A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...A File is a collection of data stored in the secondary memory. So far data wa...
A File is a collection of data stored in the secondary memory. So far data wa...
 
Introduction to Problem Solving C Programming
Introduction to Problem Solving C ProgrammingIntroduction to Problem Solving C Programming
Introduction to Problem Solving C Programming
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
C#unit4
C#unit4C#unit4
C#unit4
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 

Más de Ildar Nurgaliev

Анализ маркетинговой деятельности ООО “БАРС ГРУП”
Анализ маркетинговой деятельности  ООО “БАРС ГРУП”Анализ маркетинговой деятельности  ООО “БАРС ГРУП”
Анализ маркетинговой деятельности ООО “БАРС ГРУП”Ildar Nurgaliev
 
Fuzzy logic and application in AI
Fuzzy logic and application in AIFuzzy logic and application in AI
Fuzzy logic and application in AIIldar Nurgaliev
 
Artificial neural network
Artificial neural networkArtificial neural network
Artificial neural networkIldar Nurgaliev
 
Social dynamic simulation
Social dynamic simulationSocial dynamic simulation
Social dynamic simulationIldar Nurgaliev
 

Más de Ildar Nurgaliev (7)

Presentation
PresentationPresentation
Presentation
 
CloSapn
CloSapnCloSapn
CloSapn
 
Анализ маркетинговой деятельности ООО “БАРС ГРУП”
Анализ маркетинговой деятельности  ООО “БАРС ГРУП”Анализ маркетинговой деятельности  ООО “БАРС ГРУП”
Анализ маркетинговой деятельности ООО “БАРС ГРУП”
 
Fuzzy logic and application in AI
Fuzzy logic and application in AIFuzzy logic and application in AI
Fuzzy logic and application in AI
 
Scala syntax analysis
Scala syntax analysisScala syntax analysis
Scala syntax analysis
 
Artificial neural network
Artificial neural networkArtificial neural network
Artificial neural network
 
Social dynamic simulation
Social dynamic simulationSocial dynamic simulation
Social dynamic simulation
 

Último

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Último (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Kotlin compiler construction (very brief)

  • 2. /29 Kotlin Why? One reason is enough: Java platform and Java language there is huge gap
  • 3. /29 Kotlin Chalenges in JVM language design.
  • 4. /29 Kotlin Introduction ● Statically typed ● Compiles to JVM byte codes or JavaScript ● JVM version is Java compatible both ways ● Intended for industrial use o Designed for READABILITY o Relies simple (but powerful) abstractions o Performance is a priority o Tooling matters ● Open Source (Apache 2) o http://github.com/JetBrains/Kotlin
  • 6. /29 Kotlin Java type Kotlin type byte kotlin.Byte short kotlin.Short int kotlin.Int double kotlin.Double boolean kotlin.Boolean Mapped types Kotlin treats some Java types specially. Such types are not loaded from Java “as is”, but are mapped to corresponding Kotlin types. The mapping only matters at compile time, the runtime representation remains unchanged. Java’s primitive types are mapped to corresponding Kotlin types (keeping platform types in mind): java.lang.Object kotlin.Any! int[] kotlin.IntArray!
  • 7. /29 Kotlin Basic syntax ● You do not need ; to break statements. ● Comments are similar to Java or C#, /* This is comment */ for multi line comments and // for single line comment. ● Unlike Java, you do not need to match your file name to your class name. ● Like JavaScript, you can create functions outside classes. So there is no need to stuff your functions as static members of classes like what you do in C# or Java. ● Kotlin has string templates, which is awesome. e.g. "$firstName $lastName" for simple variable name or "${person.name} is ${1 * 2}" for any expressions. You can still do the string concatenation if you like e.g. "hello " + "world", but that means being stupid. ● It has no tuple although Kotlin's data classes is an option to use in place of tuple. ● Use function literals to filter and map collections: basic functional programming inside
  • 8. /29 Kotlin Variable semantic ● There are two keywords for variable declaration, var and val. ● Use var when the variable value is to be modified and val where the variable value will not change after first assigned. ● This val is similar to readonly keyword in C# or final keyword in Java. ● val variable must be initialized at declaration. ● Unlike Java or C#, you declare the type of a variable after the name, e.g. var firstName : String ● Number primitive types are as follows: Double, Float, Long, Int, Short, Byte. There is no automatic conversion between types. You have to explicitly convert them. ● More primitive types: Char, String, Boolean. ● All variable declarations in Kotlin must be initialized.
  • 9. /29 Kotlin Identifiers 4 types of identifiers supported by Scala: ● ALPHANUMERIC IDENTIFIERS ● OPERATOR IDENTIFIERS ● LITERAL IDENTIFIERS
  • 10. /29 Kotlin ALPHANUMERIC IDENTIFIERS ● An ALPHANUMERIC IDENTIFIERS starts with a letter or underscore, which can be followed by further letters, digits, or underscores. ● '$' character is a reserved keyword Legal alphanumeric identifiers: age, salary, _value, __1_value Illegal identifiers: $salary, 123abc, -salary
  • 12. /29 Kotlin Semantic - arrays the index used in an array selection expression must be of integer type - expressions the two operands to logical && must both be bool type, the result is bool type - functions the type of each actual argument in a function call must be compatible with the formal parameter - classes if specified, the parent of a class must be a properly declared class type - interfaces all methods of the interface must be implemented if a class states that it implements the interface
  • 13. /29 Kotlin Semantic (easy stuff) Class names can be used before being defined • We can’t check class names – using a symbol table – or even in one pass • Solution – Pass 1: Gather all class names – Pass 2: Do the checking
  • 14. /29 Kotlin AST – Before: Process an AST node n – Recurse: Process the children of n – After: Finish processing the AST node n
  • 15. /29 Kotlin Example AST rules ● Before processing e, add definition of x to current definitions, overriding any other definition of x ● – Recurse ● – After processing e, remove definition of x and restore old definition of x for (x : Char in “abc”){ ( x ) Expressions…. ( e ) }
  • 16. /29 Kotlin Symbol table operations ● addSymbol(x) push x and associated info, such as x’s type, on the stack ● findSymbol(x) search stack, starting from top, for x. Return first x found or NULL if none found ● removeSymbol() pop the stack ● enterScope() start a new nested scope ● findSymbol(x) finds current x (or null) ● addSymbol(x) add a symbol x to the table ● checkScope(x) true if x defined in current scope ● exitScope() exit current scope
  • 17. /29 Kotlin Recall to symbol tables for resolving fun main(args: Array<String>) { if (args.size == 0) { println("Provide a name") return } println("Hello, ${args[0]}!") //String Interpolation to cut down ceremony. }
  • 18. /29 Kotlin Method declaration ● Method names have complex rules ● A method need not to be defined in the class in which it is used, but in some parent class ● Methods may also be redefined (overridden) (Hard point)
  • 19. /29 Kotlin Type checking Type checking computes via reasoning: If E1 and E2 have certain types, then E3 has a certain type (e1 : Int AND e2: Int) IMPLIES e1 + e2: Int We work with hypotheses and conclusions. So we create type rules. Ex: is add minus
  • 20. /29 Kotlin Type checking Type checking proves facts e: T – Proof is on the structure of the AST – Proof has the shape of the AST – One type rule is used for each AST node • In the type rule used for a node e: – Hypotheses are the proofs of types of e’s subexpressions – Conclusion is the type of e • Types are computed in a bottom-up pass over the AST
  • 21. /29 Kotlin Type environment before type check The type environment gives types to the free identifiers in the current scope • The type environment is passed down the AST from the root towards the leaves • Types are computed up the AST from the leaves towards the root
  • 22. /29 Kotlin Subtyping Consider: if e0 then e1 else e2 • The result can be either e1 or e2 • The type is either e1’s type or of e2’s type • The best we can do is the smallest supertype larger than the type of e1 or e2
  • 23. /29 Kotlin Subtyping lub(X,Y), the Least Upper Bound of X and Y, is Z if – X ⩽ Z AND Y ⩽ Z Z is an upper bound – X ⩽ Z’ AND Y ⩽ Z’ IMPLIES Z ⩽ Z’ Z is least among upper bounds so the least upper bound of two types is their least common ancestor in the inheritance tree
  • 24. /29 Kotlin Subtyping Ex 2: The rule for case expressions takes a lub over all branches Ex 1: if-Then-Else
  • 25. /29 Kotlin Typing methods prelude: A method foo and an object foo can coexist in the same scope • In the type rules, this is reflected by a separate mapping M for method signatures M(C,f) = (T1,. . .Tn,Tn+1) means in class C there is a method f f(x1:T1,. . .,xn:Tn): Tn+1 the last one is type of return st
  • 26. /29 Kotlin Polymorphism (Self type) class Count { val i = 0; fun inc() : Count { i++ return this } }; inc() should return “dynamic type” class Stock extends Count(var name:String) { }; fun main(args: Array<>String){ val a = Stock(“test”) a = (new Stock).inc (); // fail … a.name … };
  • 27. /29 Kotlin Polymorphism (Self type) – So, we must redefine inc for each of the subclasses, with a specialized return type ● Introduce the keyword SELF_TYPE to use for the return value of such functions SELF_TYPE is not a dynamic type – It is a static type – It helps the type checker to keep better track of types – It enables the type checker to accept more correct programs
  • 28. /29 Kotlin Semantic Else one Hard aspect: 1) Lamda expressions as new feature of the language: val positiveNumbers = list.filter {it > 0} Правила редукции типовых и без типовых лямбда исчислений Область видимо-сти. Операционная семантика, виды редукций. Представление термов без использования имён (индексы де Брауна) Безопасность, продвижение, сохранение. Простое типизированное лямбда-исчисление: Типы функций. Отношение типизации. Свойства типизации. Соответствие Карри–Говарда(введения устранения, при совпадении вычисление). Стирание типов и типизируемость
  • 29. /29 Kotlin Code generation Вряд ли я с этим справлюсь

Notas del editor

  1. Big amount of java programmer. Because it’s well suitable and maintained so JAva platform is very nice ecosystem. Java platform and Java language there is huge gap. So for the java programers 10 лет, за монитором наблюдали за языком. Монитор развивался а язык нет.
  2. Kotlin — современный статически типизированный объектно-ориентированный язык программирования, компилируемый в байт-код Java и в JavaScript. Kotlin полностью совместим с Java и предоставляет дополнительные возможности, упрощающие повседневную работу программиста и повышающие продуктивность. Kotlin сочетает в себе лаконичность, выразительность, производительность и простоту в изучении.
  3. https://github.com/JetBrains/kotlin/tree/master/grammar/src https://confluence.jetbrains.com/display/Kotlin/Expressions
  4. Designing a Type Checker When designing a type checker for a compiler, here’s the process: 1. identify the types that are available in the language 2. identify the language constructs that have types associated with them 3. identify the semantic rules for the language String fake class String.last(): Char this[] Checks of many kinds . . . coolc checks: 1. All identifiers are declared 2. Types 3. Inheritance relationships 4. Classes defined only once 5. Methods in a class defined only once 6. Reserved identifiers are not misused And others . . . • The requirements depend on the language
  5. val people = hashMapOf<String, Int>() for ((person, age) in people) { println("${person} in ${age} years old") }
  6. Скормить байткоду java создание массива и присваиванию ему метода, к примеру, set то все пройдет нормально. Но после запуска там не будет никакой ошибки он просто там сдохнет незаметно и все