SlideShare una empresa de Scribd logo
1 de 62
Descargar para leer sin conexión
!
Compiler construction is
a microcosm of computer science
a = 1 # ref_cnt of a = 1
b = a # ref_cnt of a = 2
c = a + b # ref_cnt of a 2 -> 3 -> 2
sum_function(a) # ref_cnt of a 3
# A very basic HTTP server
require "http/server"
server = HTTP::Server.new do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world, got #{context.request.path}!"
end
puts "Listening on http://127.0.0.1:8080"
server.listen(8080)
!
"
with open('foo.py', 'rb') as f:
import ast
import tokenize import ast
!
"
import unittest import ctypes
import this
AST = 'is Tree'
String
Token(type=NAME, value='AST')
Token(type=OP, value='=')
Token(type=STRING, value="'is Tree'")
Tokens
keywords = {'if', 'else', 'return'}
import re
token_specification = [
('NUMBER', r'd+(.d*)?'), # Integer or decimal number
('ASSIGN', r'='), # Assignment operator
('ID', r'[A-Za-z]+'), # Identifiers
('OP', r'[+-*/]'), # Arithmetic operators
('NEWLINE', r'n'), # Line endings
('SKIP', r'[ t]+'), # Skip over spaces and tabs
('MISMATCH',r'.'), # Any other character
]
tok_regex = '|'.join(
'(?P<%s>%s)' % pair for pair in token_specification
)
def tokenize(code):
for mo in re.finditer(tok_regex, code):
kind = mo.lastgroup
value = mo.group(kind)
if kind == 'NEWLINE':
elif kind == 'SKIP':
pass
elif kind == 'MISMATCH':
raise RuntimeError(f'{value!r} unexpected')
else:
if kind == 'ID' and value in keywords:
kind = value
column = mo.start() - line_start
yield Token(kind, value)
import tokenize
def say_hello():
print("Hello, World!")
0,0-0,0: ENCODING 'utf-8'
1,0-1,3: NAME 'def'
1,4-1,13: NAME 'say_hello'
1,13-1,14: OP '('
1,14-1,15: OP ')'
1,15-1,16: OP ':'
1,16-1,17: NEWLINE 'n'
2,0-2,4: INDENT ' '
2,4-2,9: NAME 'print'
2,9-2,10: OP '('
2,10-2,25: STRING '"Hello, World!"'
2,25-2,26: OP ')'
2,26-2,27: NEWLINE 'n'
3,0-3,0: DEDENT ''
3,0-3,0: ENDMARKER ''
Assign(
targets=[
Name(id='AST')
],
value=Str(value="'is Tree'"),
)
Token(type=NAME, value='AST')
Token(type=OP, value='=')
Token(type=STRING, value="'is Tree'")
Tokens
AST
Bin OP
Bin OP + a
* cb
a + b * c
token = tokenize(code)
while token is not None:
if token.type == NAME:
if token.value == 'def':
tree = FunctionDef()
next_token = token.next()
token = token.next()
Token(type=NUMBER, value='0')
Token(type=NAME, value='sum')
if next_token.type != NAME:
raise SyntaxError()
AST
std::string AST = "is Tree"
Target Code
Assign(
targets=[
Name(id='AST')
],
value=Str(value="'is Tree'"),
)
b
b, c
mul $t0, b, c
add $t1, $t0, a
ASM
Bin OP
Bin OP + a
* cb
Bin OP
Bin OP + a
* cb
stmt = FunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value)
| AugAssign(expr target, operator op, expr value)
-- 'simple' indicates that we annotate simple name without parens
| AnnAssign(expr target, expr annotation, expr? value, int simple)
-- use 'orelse' because else is a keyword in target languages
| For(expr target, expr iter, stmt* body, stmt* orelse)
| AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
| While(expr test, stmt* body, stmt* orelse)
| If(expr test, stmt* body, stmt* orelse)
| With(withitem* items, stmt* body)
| AsyncWith(withitem* items, stmt* body)
| Raise(expr? exc, expr? cause)
| Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
| Assert(expr test, expr? msg)
| Import(alias* names)
| ImportFrom(identifier? module, alias* names, int? level)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
class NodeVisitor(object):
def visit(self, node):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
visit_Num()
visit_Return()
symbol_table = {} Assign(
targets=[
Name(id='foo')
],
value=Str(value="'bar'"),
)target_code = ''
symbol_table = {
'foo': str,
}
target_code = "string foo = 'bar'"
Symobl(type=[str], pointer=some_location, etc=[])
symbol_table = {
'foo': str,
}
Name(id='a') raise SyntaxError()
int *ptr_one;
ptr_one = (int *) malloc(sizeof(int));
free(ptr_one)
foo = 100000
# ...
# Automatically release
register int foo = 42;
•
•
10 // 4
10 // 4 * 3
10 >> 2
10 - 10 >> 2
foo = {}
foo['a'] = 1
foo['b'] = 2
foo['c'] = 3
foo = {
'a': 1,
'b': 2,
'c': 3,
}
⚙
add $s0, $t0, $t1
sub $t2, $s0, $t3
add $t3, $s0, $t4
and $t7, $t5, $t4
add $s0, $t0, $t1
and $t7, $t5, $t4
sub $t2, $s0, $t3
add $t3, $s0, $t4
A microcosm of computer science
typedef struct {
char *tp_name;
} A;
typedef struct {
char *tp_name;
int value;
float rate;
} B;
unsigned add1(unsigned a, unsigned b) {
return a + b;
}
unsigned add2(unsigned a, unsigned b) {
if (a == 0) return b;
return add2(a - 1, b + 1);
}
%struct.A = type { i8* }
%struct.B = type { i8*, i32, float }
define i32 @add1(i32 %a, i32 %b) {
entry:
%tmp1 = add i32 %a, %b
ret i32 %tmp1
}
define i32 @add2(i32 %a, i32 %b) {
entry:
%tmp1 = icmp eq i32 %a, 0 br i1
%tmp1, label %done, label %recurse
recurse:
%tmp2 = sub i32 %a, 1
%tmp3 = add i32 %b, 1
%tmp4 = call i32 @add2(i32 %tmp2, i32 %tmp3)
ret i32 %tmp4
done:
ret i32 %b
}
from numba import jit
from numpy import arrange
@jit
def sum2d(arr):
M, N = arr.shape
result = 0.0
for i in range(M):
for j in range(N):
result += arr[i,j]
return result
a = arange(9).reshape(3,3)
print(sum2d(a))
from llvmlite import ir
# Create some useful types
double = ir.DoubleType()
fnty = ir.FunctionType(double, (double, double))
# Create an empty module...
module = ir.Module(name=__file__)
# and declare a function named "fpadd" inside it
func = ir.Function(module, fnty, name="fpadd")
# Now implement the function
block = func.append_basic_block(name="entry")
builder = ir.IRBuilder(block) a, b = func.args
result = builder.fadd(a, b, name="res")
builder.ret(result)
# Print the module IR
print(module)
; ModuleID = "examples/ir_fpadd.py"
target triple = "unknown-unknown-unknown"
target datalayout = ""
define double @"fpadd"(double %".1", double %".2")
{
entry:
%"res" = fadd double %".1", %".2"
ret double %"res"
}
from llvmlite import ir
# Create some useful types
double = ir.DoubleType()
fnty = ir.FunctionType(double, (double, double))
# Create an empty module...
module = ir.Module(name=__file__)
# and declare a function named "fpadd" inside it
func = ir.Function(module, fnty, name="fpadd")
# Now implement the function
block = func.append_basic_block(name="entry")
builder = ir.IRBuilder(block) a, b = func.args
result = builder.fadd(a, b, name="res")
builder.ret(result)
# Print the module IR
print(module)
import llvmlite.binding as llvm
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def create_execution_engine():
target = llvm.Target.from_default_triple()
target_machine = target.create_target_machine()
backing_mod = llvm.parse_assembly("")
engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
return engine
def compile_ir(engine, llvm_ir):
mod = llvm.parse_assembly(llvm_ir)
mod.verify()
engine.add_module(mod)
engine.finalize_object()
engine.run_static_constructors()
return mod
engine = create_execution_engine()
mod = compile_ir(engine, llvm_ir)
from ctypes import CFUNCTYPE, c_double
func_ptr = engine.get_function_address("fpadd")
cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr)
res = cfunc(1.0, 3.5)
!
from ast import (
FunctionDef,
NodeVisitor,
)
from llvmlite import (
ir,
)
class CodeGen(NodeVisitor):
def visit_FunctionDef(self, node: FunctionDef):
func_name = node.name
func_args_types = [self.get_type(arg.annotation.id) for arg in node.args.args]
func_return_type = self.get_type(node.returns.id)
func_type = ir.FunctionType(func_return_type, func_args_types)
func = ir.Function(self.module, func_type, func_name)
def sum(a: int, b: int) -> int:
return a + b * 3 + 4
define i32 @sum(i32 %a, i32 %b) {
entry:
%multmp = mul i32 %b, 3
%addtmp = add i32 %a, 4
%addtmp.1 = add i32 %addtmp, %multmp
ret i32 %addtmp.1
}
_sum:
leal (%rsi,%rsi,2), %eax
leal 4(%rdi,%rax), %eax
retq
Primitive Type VS Object
Need Runtime or Not?
CPython’s CAPI or not?
RC VS GC
typedef struct _object {
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size;
} PyVarObject;
typedef struct _longobject {
PyVarObject ob_base;
digit ob_digit[1];
} PyLongObject;
static PyObject *
some_function() {
return (PyObject *) PyLongObject …;
}
foo = 1
isinstance(foo, int)
foo = 'bar'
isinstance(foo, str)
foo = True
isinstance(foo, bool)
class NodeVisitor(object):
def visit(self, node):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
class A:
pass
foo = A()
print(foo.bar)
#'A' object has no attribute 'bar'
bar = A()
bar.bar = 3
print(bar.bar)
# 3
print(foo.bar)
# 'A' object has no attribute 'bar'
A.foo = 10
print(foo.foo)
# 10
print(bar.foo)
# 10
class TestClass(object):
name = 'TestClass’
foo = TestClass()
class TestClass(object):
nickname = 'TestClass2'
bar = TestClass()
print(foo.name)
# TestClass
print(foo.nickname)
# 'TestClass' object has no attribute 'nickname'
print(bar.name)
# 'TestClass' object has no attribute 'name'
print(bar.nickname)
# TestClass2
§
§
§
§
def foo(bar: int) -> int: pass
!
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python

Más contenido relacionado

La actualidad más candente

Bibliometrics - an overview
Bibliometrics - an overviewBibliometrics - an overview
Bibliometrics - an overview
claudia cavicchi
 
fontes de informação
fontes de informaçãofontes de informação
fontes de informação
Ingridy Dias
 
Fundamentals of e-resource licensing
Fundamentals of e-resource licensingFundamentals of e-resource licensing
Fundamentals of e-resource licensing
NASIG
 
Academic visibility
Academic visibilityAcademic visibility
Academic visibility
Sina Moeini
 

La actualidad más candente (20)

Bibliometrics - an overview
Bibliometrics - an overviewBibliometrics - an overview
Bibliometrics - an overview
 
National programmes in information literacy
National programmes in information literacyNational programmes in information literacy
National programmes in information literacy
 
Web Technologies for Libraries
Web Technologies for LibrariesWeb Technologies for Libraries
Web Technologies for Libraries
 
ECS19 Elio Struyf - Setting Up Your SPFx CI/CD pipelines on Azure DevOps
ECS19 Elio Struyf - Setting Up Your SPFx CI/CD pipelines on Azure DevOpsECS19 Elio Struyf - Setting Up Your SPFx CI/CD pipelines on Azure DevOps
ECS19 Elio Struyf - Setting Up Your SPFx CI/CD pipelines on Azure DevOps
 
Digital literacy for librarians
Digital literacy for librariansDigital literacy for librarians
Digital literacy for librarians
 
Digital library software
Digital library softwareDigital library software
Digital library software
 
fontes de informação
fontes de informaçãofontes de informação
fontes de informação
 
ورشة عمل رؤوس الموضوعات
ورشة عمل رؤوس الموضوعات ورشة عمل رؤوس الموضوعات
ورشة عمل رؤوس الموضوعات
 
Fundamentals of e-resource licensing
Fundamentals of e-resource licensingFundamentals of e-resource licensing
Fundamentals of e-resource licensing
 
Folksonomy
FolksonomyFolksonomy
Folksonomy
 
Electronic resource management system (ERM)
Electronic resource management system (ERM)Electronic resource management system (ERM)
Electronic resource management system (ERM)
 
Opac search
Opac searchOpac search
Opac search
 
Designing an information literacy program: Basic Elements
Designing an information literacy program: Basic ElementsDesigning an information literacy program: Basic Elements
Designing an information literacy program: Basic Elements
 
Transformation of library and information science: Resources, services and pr...
Transformation of library and information science: Resources, services and pr...Transformation of library and information science: Resources, services and pr...
Transformation of library and information science: Resources, services and pr...
 
تقنيات البحث المتقدمة
تقنيات البحث المتقدمةتقنيات البحث المتقدمة
تقنيات البحث المتقدمة
 
Implementing Semantic Search
Implementing Semantic SearchImplementing Semantic Search
Implementing Semantic Search
 
14 Tips for Planning ECM Content Migration to SharePoint
14 Tips for Planning ECM Content Migration to SharePoint14 Tips for Planning ECM Content Migration to SharePoint
14 Tips for Planning ECM Content Migration to SharePoint
 
mendely.pptx
mendely.pptxmendely.pptx
mendely.pptx
 
Academic visibility
Academic visibilityAcademic visibility
Academic visibility
 
Gerenciamento de Documentos com Software Alfresco
Gerenciamento de Documentos com Software AlfrescoGerenciamento de Documentos com Software Alfresco
Gerenciamento de Documentos com Software Alfresco
 

Similar a Imugi: Compiler made with Python

PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
GkhanGirgin3
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
malavshah9013
 

Similar a Imugi: Compiler made with Python (20)

EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
c programming
c programmingc programming
c programming
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Javascript
JavascriptJavascript
Javascript
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 

Último

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Último (20)

Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 

Imugi: Compiler made with Python

  • 1. !
  • 2.
  • 3.
  • 4. Compiler construction is a microcosm of computer science
  • 5.
  • 6. a = 1 # ref_cnt of a = 1 b = a # ref_cnt of a = 2 c = a + b # ref_cnt of a 2 -> 3 -> 2 sum_function(a) # ref_cnt of a 3
  • 7.
  • 8. # A very basic HTTP server require "http/server" server = HTTP::Server.new do |context| context.response.content_type = "text/plain" context.response.print "Hello world, got #{context.request.path}!" end puts "Listening on http://127.0.0.1:8080" server.listen(8080)
  • 9. ! " with open('foo.py', 'rb') as f: import ast
  • 11. ! " import unittest import ctypes import this
  • 12.
  • 13.
  • 14. AST = 'is Tree' String Token(type=NAME, value='AST') Token(type=OP, value='=') Token(type=STRING, value="'is Tree'") Tokens
  • 15. keywords = {'if', 'else', 'return'} import re token_specification = [ ('NUMBER', r'd+(.d*)?'), # Integer or decimal number ('ASSIGN', r'='), # Assignment operator ('ID', r'[A-Za-z]+'), # Identifiers ('OP', r'[+-*/]'), # Arithmetic operators ('NEWLINE', r'n'), # Line endings ('SKIP', r'[ t]+'), # Skip over spaces and tabs ('MISMATCH',r'.'), # Any other character ] tok_regex = '|'.join( '(?P<%s>%s)' % pair for pair in token_specification ) def tokenize(code): for mo in re.finditer(tok_regex, code): kind = mo.lastgroup value = mo.group(kind) if kind == 'NEWLINE': elif kind == 'SKIP': pass elif kind == 'MISMATCH': raise RuntimeError(f'{value!r} unexpected') else: if kind == 'ID' and value in keywords: kind = value column = mo.start() - line_start yield Token(kind, value)
  • 16.
  • 17. import tokenize def say_hello(): print("Hello, World!") 0,0-0,0: ENCODING 'utf-8' 1,0-1,3: NAME 'def' 1,4-1,13: NAME 'say_hello' 1,13-1,14: OP '(' 1,14-1,15: OP ')' 1,15-1,16: OP ':' 1,16-1,17: NEWLINE 'n' 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' 2,9-2,10: OP '(' 2,10-2,25: STRING '"Hello, World!"' 2,25-2,26: OP ')' 2,26-2,27: NEWLINE 'n' 3,0-3,0: DEDENT '' 3,0-3,0: ENDMARKER ''
  • 18. Assign( targets=[ Name(id='AST') ], value=Str(value="'is Tree'"), ) Token(type=NAME, value='AST') Token(type=OP, value='=') Token(type=STRING, value="'is Tree'") Tokens AST Bin OP Bin OP + a * cb a + b * c
  • 19. token = tokenize(code) while token is not None: if token.type == NAME: if token.value == 'def': tree = FunctionDef() next_token = token.next() token = token.next() Token(type=NUMBER, value='0') Token(type=NAME, value='sum') if next_token.type != NAME: raise SyntaxError()
  • 20. AST std::string AST = "is Tree" Target Code Assign( targets=[ Name(id='AST') ], value=Str(value="'is Tree'"), ) b b, c mul $t0, b, c add $t1, $t0, a ASM Bin OP Bin OP + a * cb
  • 21. Bin OP Bin OP + a * cb stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns) | AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns) | ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list) | Return(expr? value) | Delete(expr* targets) | Assign(expr* targets, expr value) | AugAssign(expr target, operator op, expr value) -- 'simple' indicates that we annotate simple name without parens | AnnAssign(expr target, expr annotation, expr? value, int simple) -- use 'orelse' because else is a keyword in target languages | For(expr target, expr iter, stmt* body, stmt* orelse) | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse) | While(expr test, stmt* body, stmt* orelse) | If(expr test, stmt* body, stmt* orelse) | With(withitem* items, stmt* body) | AsyncWith(withitem* items, stmt* body) | Raise(expr? exc, expr? cause) | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) | Assert(expr test, expr? msg) | Import(alias* names) | ImportFrom(identifier? module, alias* names, int? level) | Global(identifier* names) | Nonlocal(identifier* names) | Expr(expr value) | Pass | Break | Continue class NodeVisitor(object): def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) visit_Num() visit_Return()
  • 22. symbol_table = {} Assign( targets=[ Name(id='foo') ], value=Str(value="'bar'"), )target_code = '' symbol_table = { 'foo': str, } target_code = "string foo = 'bar'" Symobl(type=[str], pointer=some_location, etc=[]) symbol_table = { 'foo': str, } Name(id='a') raise SyntaxError()
  • 23.
  • 24. int *ptr_one; ptr_one = (int *) malloc(sizeof(int)); free(ptr_one) foo = 100000 # ... # Automatically release register int foo = 42; • •
  • 25. 10 // 4 10 // 4 * 3 10 >> 2 10 - 10 >> 2 foo = {} foo['a'] = 1 foo['b'] = 2 foo['c'] = 3 foo = { 'a': 1, 'b': 2, 'c': 3, } ⚙
  • 26. add $s0, $t0, $t1 sub $t2, $s0, $t3 add $t3, $s0, $t4 and $t7, $t5, $t4 add $s0, $t0, $t1 and $t7, $t5, $t4 sub $t2, $s0, $t3 add $t3, $s0, $t4
  • 27. A microcosm of computer science
  • 28.
  • 29.
  • 30.
  • 31.
  • 32. typedef struct { char *tp_name; } A; typedef struct { char *tp_name; int value; float rate; } B; unsigned add1(unsigned a, unsigned b) { return a + b; } unsigned add2(unsigned a, unsigned b) { if (a == 0) return b; return add2(a - 1, b + 1); } %struct.A = type { i8* } %struct.B = type { i8*, i32, float } define i32 @add1(i32 %a, i32 %b) { entry: %tmp1 = add i32 %a, %b ret i32 %tmp1 } define i32 @add2(i32 %a, i32 %b) { entry: %tmp1 = icmp eq i32 %a, 0 br i1 %tmp1, label %done, label %recurse recurse: %tmp2 = sub i32 %a, 1 %tmp3 = add i32 %b, 1 %tmp4 = call i32 @add2(i32 %tmp2, i32 %tmp3) ret i32 %tmp4 done: ret i32 %b }
  • 33.
  • 34.
  • 35. from numba import jit from numpy import arrange @jit def sum2d(arr): M, N = arr.shape result = 0.0 for i in range(M): for j in range(N): result += arr[i,j] return result a = arange(9).reshape(3,3) print(sum2d(a))
  • 36. from llvmlite import ir # Create some useful types double = ir.DoubleType() fnty = ir.FunctionType(double, (double, double)) # Create an empty module... module = ir.Module(name=__file__) # and declare a function named "fpadd" inside it func = ir.Function(module, fnty, name="fpadd") # Now implement the function block = func.append_basic_block(name="entry") builder = ir.IRBuilder(block) a, b = func.args result = builder.fadd(a, b, name="res") builder.ret(result) # Print the module IR print(module)
  • 37. ; ModuleID = "examples/ir_fpadd.py" target triple = "unknown-unknown-unknown" target datalayout = "" define double @"fpadd"(double %".1", double %".2") { entry: %"res" = fadd double %".1", %".2" ret double %"res" } from llvmlite import ir # Create some useful types double = ir.DoubleType() fnty = ir.FunctionType(double, (double, double)) # Create an empty module... module = ir.Module(name=__file__) # and declare a function named "fpadd" inside it func = ir.Function(module, fnty, name="fpadd") # Now implement the function block = func.append_basic_block(name="entry") builder = ir.IRBuilder(block) a, b = func.args result = builder.fadd(a, b, name="res") builder.ret(result) # Print the module IR print(module)
  • 38. import llvmlite.binding as llvm llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() def create_execution_engine(): target = llvm.Target.from_default_triple() target_machine = target.create_target_machine() backing_mod = llvm.parse_assembly("") engine = llvm.create_mcjit_compiler(backing_mod, target_machine) return engine def compile_ir(engine, llvm_ir): mod = llvm.parse_assembly(llvm_ir) mod.verify() engine.add_module(mod) engine.finalize_object() engine.run_static_constructors() return mod engine = create_execution_engine() mod = compile_ir(engine, llvm_ir) from ctypes import CFUNCTYPE, c_double func_ptr = engine.get_function_address("fpadd") cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr) res = cfunc(1.0, 3.5)
  • 39. !
  • 40. from ast import ( FunctionDef, NodeVisitor, ) from llvmlite import ( ir, ) class CodeGen(NodeVisitor): def visit_FunctionDef(self, node: FunctionDef): func_name = node.name func_args_types = [self.get_type(arg.annotation.id) for arg in node.args.args] func_return_type = self.get_type(node.returns.id) func_type = ir.FunctionType(func_return_type, func_args_types) func = ir.Function(self.module, func_type, func_name)
  • 41.
  • 42. def sum(a: int, b: int) -> int: return a + b * 3 + 4 define i32 @sum(i32 %a, i32 %b) { entry: %multmp = mul i32 %b, 3 %addtmp = add i32 %a, 4 %addtmp.1 = add i32 %addtmp, %multmp ret i32 %addtmp.1 } _sum: leal (%rsi,%rsi,2), %eax leal 4(%rdi,%rax), %eax retq
  • 43.
  • 44. Primitive Type VS Object Need Runtime or Not? CPython’s CAPI or not? RC VS GC
  • 45. typedef struct _object { Py_ssize_t ob_refcnt; struct _typeobject *ob_type; } PyObject; typedef struct { PyObject ob_base; Py_ssize_t ob_size; } PyVarObject; typedef struct _longobject { PyVarObject ob_base; digit ob_digit[1]; } PyLongObject; static PyObject * some_function() { return (PyObject *) PyLongObject …; }
  • 46. foo = 1 isinstance(foo, int) foo = 'bar' isinstance(foo, str) foo = True isinstance(foo, bool) class NodeVisitor(object): def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node)
  • 47. class A: pass foo = A() print(foo.bar) #'A' object has no attribute 'bar' bar = A() bar.bar = 3 print(bar.bar) # 3 print(foo.bar) # 'A' object has no attribute 'bar' A.foo = 10 print(foo.foo) # 10 print(bar.foo) # 10 class TestClass(object): name = 'TestClass’ foo = TestClass() class TestClass(object): nickname = 'TestClass2' bar = TestClass() print(foo.name) # TestClass print(foo.nickname) # 'TestClass' object has no attribute 'nickname' print(bar.name) # 'TestClass' object has no attribute 'name' print(bar.nickname) # TestClass2
  • 49. def foo(bar: int) -> int: pass
  • 50.
  • 51.
  • 52.
  • 53. !