VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks

Marcus Denker
Marcus DenkerResearch Scientist at INRIA
Advanced Reflection:
MetaLinks
Marcus Denker, Inria
http://marcusdenker.de
Lecture at VUB Brussels, October 30, 2019
What we know…
• Smalltalk is reflective

• Classes, Methods, Stack-Frames… are Objects

• Reflective API on all Objects
Take home message
• Reflection is based on the meta-class model, thus
inherently structural.
• Behavioural reflection limited to:
• Method lookup upon failure ( doesNotUnderstand:
message)
• Current execution reified (thisContext)
61
Can we do better?
• A more fine-grained reflective mechanism seems to be
missing

• Let’s look again at a Method in the Inspector
Inspector on a Method
The AST
• AST = Abstract Syntax Tree

• Tree Representation of the Method

• Produced by the Parser (part of the Compiler)

• Used by all tools (refactoring, syntax-highlighting,…)
Smalltalk compiler parse: 'test ^(1+2)'
AST
• RBMethodNode Root

• RBVariableNode Variable (read and write)

• RBAssignmentNode Assignment

• RBMessageNode A Message (most of them)

• RBReturnNode Return
Inspect a simple AST
• A very simple Example
Smalltalk compiler parse: 'test ^(1+2)'
AST: Navigation
• To make it easy to find and enumerate nodes, there are
some helper methods

• CompiledMethod has: #sendNodes,
#variableNodes, #assignmentNodes
• Every AST node has #nodesDo: and #allChildren
AST: Visitor
• RBProgramNodeVisitor: Visitor Pattern for the AST

• Make subclass, override visit… methods

• Let’s see it in action: Count Message sends
Demo: Visitor
Repeat:The AST
• AST = Abstract Syntax Tree

• Tree Representation of the Method

• Produced by the Parser (part of the Compiler)

• Used by all tools (refactoring, syntax-highlighting,…)
Smalltalk compiler parse: 'test ^(1+2)'
The Compiler
• Smalltalk compiler -> Compiler Facade 

• Classes define the compiler to use

• You can override method #compiler

• Behind: Compiler Chain
The Compiler
Source AST
Annotated
AST
IR
Annotated
AST
Bytecode
RBParser OCSemanticAnalyzer
OCASTTranslator/
IRBuilder
IRBytecodeGenerator
AST Integration
• Originally just internal to the compiler

• Pharo: 

• send #ast to a method to get the AST

• Cached for persistency.
(Point>>#x) ast == (Point>>#x) ast
—> true
AST Integration
• We can navigate from execution to AST

• Example:
[ 1 + 2 ] sourceNode ==
thisContext method sourceNode blockNodes first
Compiler: Extensible
• All parts can be subclassed

• Compiler instance can be setup to use the subclass for
any part (parser, name analysis, translator…)

• enable for a class only by implementing #compiler on the
class side
Compiler Plugins
• The AST can be easily transformed

• We added a Plugin architecture to the Compiler

• enable for a class only by implementing:
compiler

	 ^super compiler addPlugin: MyPlugin
The Compiler
Source AST
Annotated
AST
IR
Annotated
AST
Bytecode
RBParser OCSemanticAnalyzer
OCASTTranslator/
IRBuilder
IRBytecodeGenerator
Plugin
Source AST
Annotated
AST
IR
Annotated
AST
Bytecode
RBParser OCSemanticAnalyzer
OCASTTranslator/
IRBuilder
IRBytecodeGenerator
OCCompilerASTPlugin
Annotated
AST
Plugin: Example
• We get all ifTrue: sends

• replace them with true
DemoPlugin>>transform
transform
| sends |
sends := ast sendNodes.
sends := sends select: [ :each | each selector = #ifTrue: ].
sends do: [:each | each replaceWith:
(RBLiteralNode value: true)].
^ast
Back to the topic…
• A more fine-grained reflective mechanism seems to be
missing

• Can’t we do something with the AST?
Wouldn’t it be nice..
• With the AST, wouldn’t it be nice if we could use this
structure for Behavioural Reflection?

• If we could somehow attach a “arrow to the code” that
points to a meta-object
test
^( 1 + 2 )
meta-object
for this Send
We have all pieces…
• We have the AST for each method

• It is quite simple

• We have a compiler in the system

• So this should be possible…
The MetaLink
• MetaLink points to metaObject

• Defines a selector to call

• And a control attribute: #before, #after, #instead

• Installed on a AST node:
link := MetaLink new
metaObject: Halt;
selector: #once;
control: #before.
(Number>>#sin) ast link: link
The MetaLink
• Can be installed on any AST Node

• Methods will be re-compiled on the fly just before next
execution

• Link installation is very fast

• Changing a method removes all links from this method

• Managing link re-installation has to be done by the user
MetaLink: MetaObject
• MetaObject can be any object

• Even a Block: [Transcript show ‘hello’]
• Install on any Node with #link:

• de-install a link with #uninstall
MetaLink: Selector
• MetaLink defines a message send to the MetaObject

• #selector defines which one

• Default is #value

• Yes, a selector with arguments is supported 

• We can pass information to the meta-object
MetaLink: Argument
• The arguments define which arguments to pass

• We support a number of reifications
Reifications
• Reifications define data to be passed as arguments

• Reify —> Make something into an object that is not one
normally

• Example: “All arguments of this message”
Reifications: examples
• All nodes: #object #context #class #node
#link
• Sends: #arguments #receiver #selector
• Method: #arguments #selector 

• Variable: #value

They are defined as subclasses of class RFReification
Reifications as MetaObject
• We support some special metaObjects:

• #node The AST Node we are installed on

• #object self at runtime

• #class The class the links is installed in
MetaLink: Condition
• We can specify a condition for the MetaLink

• Link is active if the condition evaluates to true
• We can pass reifications as arguments
link := MetaLink new
metaObject: Halt;
selector: #once;
condition: [:object | object == 5] arguments: #(object).
(Number>>#sin) ast link: link.
MetaLink: control
• We can specify when to call the meta-object

• We support #before, #after and #instead
• The instead is very simple: last one wins
Example: Log
• We want to just print something to the Transcript
link := MetaLink new
metaObject: [Transcript show: 'Reached Here'].
(Number>>#sin) ast link: link
Recursion Problem
• Before we see more examples: There is a problem

• Imagine we put a MetaLink on some method deep in the
System (e.g new, +, do: ).

• Our Meta-Object might use exactly that method, too
Endless Loop!!
Recursion Problem
• Solution: Meta-Level

• We encode the a level in the execution of the system

• Every Link Activation increases the level

• A meta-link is just active for one level. (e.g. 0)
link := MetaLink new
metaObject: [ Object new ];
level: 0.
(Behavior>>#new) ast link: link.
Example: Log
• Better use #level: 0

• Nevertheless: be careful! If you add this to method called
often it can be very slow.
link := MetaLink new
metaObject: [Transcript show: 'Reached Here’];
level: 0.
Example: Counter
• In the Browser you can add a “counter” to the AST

• See class ExecutionCounter
install
link := MetaLink new
metaObject: self;
selector: #increase.
node link: link.
Example: Breakpoint
• “Add Breakpoint” in AST (Suggestions) Menu

• See class Breakpoint

• Break Once 

• Conditional Break breakLink
^ MetaLink new
metaObject: Break;
selector: #break;
options: options
Example: WatchPoint
• Watchpoint: Record Value at a point in the AST

• Example: Watch event in WorldMorph>>#mouseDown:
Click on background
-> value recorded
Example: WatchPoint
• Implementation: class Watchpoint, method install

• example of a #after link with a condition
link := MetaLink new
metaObject: self;
selector: #addValue:;
arguments: #(value);
control: #after;
condition: [ recording ].
Example: Code Coverage
• Small Demo.

• Start with CoverageDemo new openWithSpec
Example: Code Coverage
• Example of a MetaLink with a #node MetaObject

• Meta-Object is the node that the link is installed on
link := MetaLink new
metaObject: #node;
selector: #tagExecuted.
Interesting Properties
• Cross Cutting

• One Link can be installed multiple times

• Over multiple methods and even Classes

• And across operations (e.g., Send and Assignment) as
long as all reifications requested are compatible

• Fully Dynamic: Links can be added and removed at runtime

• Even by the meta-object of another meta-link!
Example: Accept for Test
• Imagine we want to edit a method that is called often by
the System.

• How do we test it?

• It would be nice if we could “Accept for Test”
Example: Accept for Test
• Menu in the browser. Quick hack, a Suggestions AST
menu shows for all nodes.
SugsSuggestion subclass: #SugsAcceptForTest
instanceVariableNames: ''
classVariableNames: ''
package: 'SmartSuggestions-Suggestion'
label
^'Accept for test'
• We implement our code in the #execute method
Example: Accept for Test
• How we know that we are in a test?
CurrentExecutionEnvironment value isTest
• We can compile the current text buffer
newMethod := context selectedClass compiler
source: context code;
options: #(+ optionParseErrors);
compile.
Example: Accept for Test
• Add this code to the beginning of the method:
[:aContext :args |
CurrentExecutionEnvironment value isTest ifTrue: [
aContext return: (newMethod
valueWithReceiver: aContext
receiver
arguments: args) ]]
• Let’s do that with a MetaLink!
Example: Accept for Test
execute
| newMethod metaLink |
newMethod := context selectedClass compiler
source: context code;
options: #(+ optionParseErrors);
compile.
"the link executes the method we just created and returns"
metaLink := MetaLink new
metaObject: [ :aContext :args |
CurrentExecutionEnvironment value isTest
ifTrue: [ aContext return: (newMethod
valueWithReceiver: aContext receiver
arguments: args) ] ];
selector: #value:value:;
arguments: #(context arguments).
context selectedMethod ast link: metaLink
Limitations
• #instead needs more work (e.g to support conditions)

• Keep in mind: next metaLink taken into account for next
method activation 

• Take care with long running loops!
Help Wanted
• We are always interested in improvements!

• Pharo 8 is under active development. 

• Pull Requests Welcome!
1 of 52

Recommended

Lecture: Advanced Reflection. MetaLinks by
Lecture: Advanced Reflection. MetaLinksLecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinksMarcus Denker
1.4K views47 slides
Lecture: MetaLinks by
Lecture: MetaLinksLecture: MetaLinks
Lecture: MetaLinksMarcus Denker
4.1K views37 slides
Reflection in Pharo: Beyond Smalltak by
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakMarcus Denker
1.2K views56 slides
Dynamically Composing Collection Operations through Collection Promises by
Dynamically Composing Collection Operations through Collection PromisesDynamically Composing Collection Operations through Collection Promises
Dynamically Composing Collection Operations through Collection PromisesMarcus Denker
727 views15 slides
Introduction to Akka - Atlanta Java Users Group by
Introduction to Akka - Atlanta Java Users GroupIntroduction to Akka - Atlanta Java Users Group
Introduction to Akka - Atlanta Java Users GroupRoy Russo
2.4K views87 slides
Reflection in Pharo: Beyond Smalltak by
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakMarcus Denker
746 views56 slides

More Related Content

What's hot

Variables in Pharo5 by
Variables in Pharo5Variables in Pharo5
Variables in Pharo5Marcus Denker
2.4K views31 slides
Enhanced Web Service Testing: A Better Mock Structure by
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
1.9K views44 slides
Enhanced Web Service Testing: A Better Mock Structure by
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureCRMScienceKirk
860 views27 slides
Whoops! where did my architecture go? by
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?Oliver Gierke
41.2K views81 slides
Whoops! Where did my architecture go? by
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
7.1K views75 slides
Java 8 concurrency abstractions by
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractionsNawazish Mohammad Khan
8.1K views27 slides

What's hot(20)

Enhanced Web Service Testing: A Better Mock Structure by Salesforce Developers
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure by CRMScienceKirk
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
CRMScienceKirk860 views
Whoops! where did my architecture go? by Oliver Gierke
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?
Oliver Gierke41.2K views
Whoops! Where did my architecture go? by Oliver Gierke
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
Oliver Gierke7.1K views
Testing in Scala. Adform Research by Vasil Remeniuk
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
Vasil Remeniuk967 views
The dark side of Akka and the remedy by krivachy
The dark side of Akka and the remedyThe dark side of Akka and the remedy
The dark side of Akka and the remedy
krivachy4.5K views
Async in .NET by RTigger
Async in .NETAsync in .NET
Async in .NET
RTigger1.8K views
The dark side of Akka and the remedy - bp.scala meetup by krivachy
The dark side of Akka and the remedy - bp.scala meetupThe dark side of Akka and the remedy - bp.scala meetup
The dark side of Akka and the remedy - bp.scala meetup
krivachy8.2K views
2014-02-20 | Akka Concurrency (Vienna Scala User Group) by Dominik Gruber
2014-02-20 | Akka Concurrency (Vienna Scala User Group)2014-02-20 | Akka Concurrency (Vienna Scala User Group)
2014-02-20 | Akka Concurrency (Vienna Scala User Group)
Dominik Gruber1.5K views
Legacy Code Kata v3.0 by William Munn
Legacy Code Kata v3.0Legacy Code Kata v3.0
Legacy Code Kata v3.0
William Munn2.5K views
Reactive Micro Services with Java seminar by Gal Marder
Reactive Micro Services with Java seminarReactive Micro Services with Java seminar
Reactive Micro Services with Java seminar
Gal Marder830 views
Legacy Dependency Kata v2.0 by William Munn
Legacy Dependency Kata v2.0Legacy Dependency Kata v2.0
Legacy Dependency Kata v2.0
William Munn1.6K views
Advanced Reflection in Pharo by Marcus Denker
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
Marcus Denker4.6K views
Servlet11 by patinijava
Servlet11Servlet11
Servlet11
patinijava1.2K views
Streams, Streams Everywhere! An Introduction to Rx by Andrzej Sitek
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek2.4K views
C# 5 deep drive into asynchronous programming by Praveen Prajapati
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
Praveen Prajapati5.4K views

Similar to VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks

Lecture: "Advanced Reflection: MetaLinks" by
Lecture: "Advanced Reflection: MetaLinks"Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"Marcus Denker
11 views54 slides
Lecture. Advanced Reflection: MetaLinks by
Lecture. Advanced Reflection: MetaLinksLecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinksMarcus Denker
11 views54 slides
Behavioral Reflection in Pharo by
Behavioral Reflection in PharoBehavioral Reflection in Pharo
Behavioral Reflection in PharoESUG
308 views48 slides
#Pharo Days 2016 Reflectivity by
#Pharo Days 2016 Reflectivity#Pharo Days 2016 Reflectivity
#Pharo Days 2016 ReflectivityPhilippe Back
547 views56 slides
Behavioral Reflection by
Behavioral ReflectionBehavioral Reflection
Behavioral ReflectionMarcus Denker
1.9K views32 slides
Presentation 3rd by
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
138 views39 slides

Similar to VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks(20)

Lecture: "Advanced Reflection: MetaLinks" by Marcus Denker
Lecture: "Advanced Reflection: MetaLinks"Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"
Marcus Denker11 views
Lecture. Advanced Reflection: MetaLinks by Marcus Denker
Lecture. Advanced Reflection: MetaLinksLecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinks
Marcus Denker11 views
Behavioral Reflection in Pharo by ESUG
Behavioral Reflection in PharoBehavioral Reflection in Pharo
Behavioral Reflection in Pharo
ESUG308 views
#Pharo Days 2016 Reflectivity by Philippe Back
#Pharo Days 2016 Reflectivity#Pharo Days 2016 Reflectivity
#Pharo Days 2016 Reflectivity
Philippe Back547 views
Behavioral Reflection by Marcus Denker
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
Marcus Denker1.9K views
Presentation 3rd by Connex
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex138 views
First Class Variables as AST Annotations by ESUG
 First Class Variables as AST Annotations First Class Variables as AST Annotations
First Class Variables as AST Annotations
ESUG58 views
First Class Variables as AST Annotations by Marcus Denker
First Class Variables as AST AnnotationsFirst Class Variables as AST Annotations
First Class Variables as AST Annotations
Marcus Denker5 views
DjangoCon 2010 Scaling Disqus by zeeg
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
zeeg32.6K views
Data weave (MuleSoft) by Nandu List5
Data weave (MuleSoft)Data weave (MuleSoft)
Data weave (MuleSoft)
Nandu List52.1K views
Runtime Bytecode Transformation for Smalltalk by Marcus Denker
Runtime Bytecode Transformation for SmalltalkRuntime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for Smalltalk
Marcus Denker410 views
Akka london scala_user_group by Skills Matter
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter1.1K views
The hardest part of microservices: your data by Christian Posta
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your data
Christian Posta21.4K views
Runtime Bytecode Transformation for Smalltalk by ESUG
Runtime Bytecode Transformation for SmalltalkRuntime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for Smalltalk
ESUG390 views
DDD, CQRS and testing with ASP.Net MVC by Andy Butland
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
Andy Butland7.7K views
Code transformation With Spoon by Gérard Paligot
Code transformation With SpoonCode transformation With Spoon
Code transformation With Spoon
Gérard Paligot1.7K views
Presentation 4th by Connex
Presentation 4thPresentation 4th
Presentation 4th
Connex118 views

More from Marcus Denker

Soil And Pharo by
Soil And PharoSoil And Pharo
Soil And PharoMarcus Denker
47 views12 slides
ConstantBlocks in Pharo11 by
ConstantBlocks in Pharo11ConstantBlocks in Pharo11
ConstantBlocks in Pharo11Marcus Denker
50 views26 slides
Demo: Improved DoIt by
Demo: Improved DoItDemo: Improved DoIt
Demo: Improved DoItMarcus Denker
4 views3 slides
Supporting Pharo / Getting Pharo Support by
Supporting Pharo / Getting Pharo SupportSupporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo SupportMarcus Denker
8 views19 slides
thisContext in the Debugger by
thisContext in the DebuggerthisContext in the Debugger
thisContext in the DebuggerMarcus Denker
413 views7 slides
Improving code completion for Pharo by
Improving code completion for PharoImproving code completion for Pharo
Improving code completion for PharoMarcus Denker
292 views19 slides

More from Marcus Denker(19)

Supporting Pharo / Getting Pharo Support by Marcus Denker
Supporting Pharo / Getting Pharo SupportSupporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo Support
Marcus Denker8 views
thisContext in the Debugger by Marcus Denker
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
Marcus Denker413 views
Improving code completion for Pharo by Marcus Denker
Improving code completion for PharoImproving code completion for Pharo
Improving code completion for Pharo
Marcus Denker292 views
Open-Source: An Infinite Game by Marcus Denker
Open-Source: An Infinite GameOpen-Source: An Infinite Game
Open-Source: An Infinite Game
Marcus Denker1.2K views
PharoTechTalk: Contributing to Pharo by Marcus Denker
PharoTechTalk: Contributing to PharoPharoTechTalk: Contributing to Pharo
PharoTechTalk: Contributing to Pharo
Marcus Denker684 views
Feedback Loops in Practice by Marcus Denker
Feedback Loops in PracticeFeedback Loops in Practice
Feedback Loops in Practice
Marcus Denker860 views
Perfection & Feedback Loops or: why worse is better by Marcus Denker
Perfection & Feedback Loops or: why worse is betterPerfection & Feedback Loops or: why worse is better
Perfection & Feedback Loops or: why worse is better
Marcus Denker7.5K views
How to Contribute to Pharo by Marcus Denker
How to Contribute to PharoHow to Contribute to Pharo
How to Contribute to Pharo
Marcus Denker1.3K views
Pharo Status (from PharoDays 2015) by Marcus Denker
Pharo Status (from PharoDays 2015)Pharo Status (from PharoDays 2015)
Pharo Status (from PharoDays 2015)
Marcus Denker1.3K views
Pharo Status Fosdem 2015 by Marcus Denker
Pharo Status Fosdem 2015Pharo Status Fosdem 2015
Pharo Status Fosdem 2015
Marcus Denker6.9K views
Pharo Status ESUG 2014 by Marcus Denker
Pharo Status ESUG 2014Pharo Status ESUG 2014
Pharo Status ESUG 2014
Marcus Denker1.2K views
Nomads do not build Cathedrals by Marcus Denker
Nomads do not build CathedralsNomads do not build Cathedrals
Nomads do not build Cathedrals
Marcus Denker1.5K views

Recently uploaded

El Arte de lo Possible by
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo PossibleNeo4j
34 views35 slides
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDeltares
12 views13 slides
Unleash The Monkeys by
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
7 views28 slides
Winter '24 Release Chat.pdf by
Winter '24 Release Chat.pdfWinter '24 Release Chat.pdf
Winter '24 Release Chat.pdfmelbourneauuser
9 views20 slides
Best Mics For Your Live Streaming by
Best Mics For Your Live StreamingBest Mics For Your Live Streaming
Best Mics For Your Live Streamingontheflystream
6 views6 slides
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...Marc Müller
35 views62 slides

Recently uploaded(20)

El Arte de lo Possible by Neo4j
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo Possible
Neo4j34 views
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares12 views
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller35 views
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida by Deltares
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - PridaDSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
Deltares17 views
Cycleops - Automate deployments on top of bare metal.pptx by Thanassis Parathyras
Cycleops - Automate deployments on top of bare metal.pptxCycleops - Automate deployments on top of bare metal.pptx
Cycleops - Automate deployments on top of bare metal.pptx
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... by Deltares
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
Deltares9 views
MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
Citi TechTalk Session 2: Kafka Deep Dive by confluent
Citi TechTalk Session 2: Kafka Deep DiveCiti TechTalk Session 2: Kafka Deep Dive
Citi TechTalk Session 2: Kafka Deep Dive
confluent17 views
Neo4j y GenAI by Neo4j
Neo4j y GenAI Neo4j y GenAI
Neo4j y GenAI
Neo4j35 views
Neo4j : Graphes de Connaissance, IA et LLMs by Neo4j
Neo4j : Graphes de Connaissance, IA et LLMsNeo4j : Graphes de Connaissance, IA et LLMs
Neo4j : Graphes de Connaissance, IA et LLMs
Neo4j46 views
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut... by HCLSoftware
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
Elevate your SAP landscape's efficiency and performance with HCL Workload Aut...
HCLSoftware6 views
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan... by Deltares
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...
Deltares10 views
Roadmap y Novedades de producto by Neo4j
Roadmap y Novedades de productoRoadmap y Novedades de producto
Roadmap y Novedades de producto
Neo4j43 views
DSD-INT 2023 Next-Generation Flood Inundation Mapping for Taiwan - Delft3D FM... by Deltares
DSD-INT 2023 Next-Generation Flood Inundation Mapping for Taiwan - Delft3D FM...DSD-INT 2023 Next-Generation Flood Inundation Mapping for Taiwan - Delft3D FM...
DSD-INT 2023 Next-Generation Flood Inundation Mapping for Taiwan - Delft3D FM...
Deltares7 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares10 views

VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks

  • 1. Advanced Reflection: MetaLinks Marcus Denker, Inria http://marcusdenker.de Lecture at VUB Brussels, October 30, 2019
  • 2. What we know… • Smalltalk is reflective • Classes, Methods, Stack-Frames… are Objects • Reflective API on all Objects
  • 3. Take home message • Reflection is based on the meta-class model, thus inherently structural. • Behavioural reflection limited to: • Method lookup upon failure ( doesNotUnderstand: message) • Current execution reified (thisContext) 61
  • 4. Can we do better? • A more fine-grained reflective mechanism seems to be missing • Let’s look again at a Method in the Inspector
  • 5. Inspector on a Method
  • 6. The AST • AST = Abstract Syntax Tree • Tree Representation of the Method • Produced by the Parser (part of the Compiler) • Used by all tools (refactoring, syntax-highlighting,…) Smalltalk compiler parse: 'test ^(1+2)'
  • 7. AST • RBMethodNode Root • RBVariableNode Variable (read and write) • RBAssignmentNode Assignment • RBMessageNode A Message (most of them) • RBReturnNode Return
  • 8. Inspect a simple AST • A very simple Example Smalltalk compiler parse: 'test ^(1+2)'
  • 9. AST: Navigation • To make it easy to find and enumerate nodes, there are some helper methods • CompiledMethod has: #sendNodes, #variableNodes, #assignmentNodes • Every AST node has #nodesDo: and #allChildren
  • 10. AST: Visitor • RBProgramNodeVisitor: Visitor Pattern for the AST • Make subclass, override visit… methods • Let’s see it in action: Count Message sends
  • 12. Repeat:The AST • AST = Abstract Syntax Tree • Tree Representation of the Method • Produced by the Parser (part of the Compiler) • Used by all tools (refactoring, syntax-highlighting,…) Smalltalk compiler parse: 'test ^(1+2)'
  • 13. The Compiler • Smalltalk compiler -> Compiler Facade • Classes define the compiler to use • You can override method #compiler • Behind: Compiler Chain
  • 14. The Compiler Source AST Annotated AST IR Annotated AST Bytecode RBParser OCSemanticAnalyzer OCASTTranslator/ IRBuilder IRBytecodeGenerator
  • 15. AST Integration • Originally just internal to the compiler • Pharo: • send #ast to a method to get the AST • Cached for persistency. (Point>>#x) ast == (Point>>#x) ast —> true
  • 16. AST Integration • We can navigate from execution to AST • Example: [ 1 + 2 ] sourceNode == thisContext method sourceNode blockNodes first
  • 17. Compiler: Extensible • All parts can be subclassed • Compiler instance can be setup to use the subclass for any part (parser, name analysis, translator…) • enable for a class only by implementing #compiler on the class side
  • 18. Compiler Plugins • The AST can be easily transformed • We added a Plugin architecture to the Compiler • enable for a class only by implementing: compiler ^super compiler addPlugin: MyPlugin
  • 19. The Compiler Source AST Annotated AST IR Annotated AST Bytecode RBParser OCSemanticAnalyzer OCASTTranslator/ IRBuilder IRBytecodeGenerator
  • 21. Plugin: Example • We get all ifTrue: sends • replace them with true DemoPlugin>>transform transform | sends | sends := ast sendNodes. sends := sends select: [ :each | each selector = #ifTrue: ]. sends do: [:each | each replaceWith: (RBLiteralNode value: true)]. ^ast
  • 22. Back to the topic… • A more fine-grained reflective mechanism seems to be missing • Can’t we do something with the AST?
  • 23. Wouldn’t it be nice.. • With the AST, wouldn’t it be nice if we could use this structure for Behavioural Reflection? • If we could somehow attach a “arrow to the code” that points to a meta-object test ^( 1 + 2 ) meta-object for this Send
  • 24. We have all pieces… • We have the AST for each method • It is quite simple • We have a compiler in the system • So this should be possible…
  • 25. The MetaLink • MetaLink points to metaObject • Defines a selector to call • And a control attribute: #before, #after, #instead • Installed on a AST node: link := MetaLink new metaObject: Halt; selector: #once; control: #before. (Number>>#sin) ast link: link
  • 26. The MetaLink • Can be installed on any AST Node • Methods will be re-compiled on the fly just before next execution • Link installation is very fast • Changing a method removes all links from this method • Managing link re-installation has to be done by the user
  • 27. MetaLink: MetaObject • MetaObject can be any object • Even a Block: [Transcript show ‘hello’] • Install on any Node with #link: • de-install a link with #uninstall
  • 28. MetaLink: Selector • MetaLink defines a message send to the MetaObject • #selector defines which one • Default is #value • Yes, a selector with arguments is supported • We can pass information to the meta-object
  • 29. MetaLink: Argument • The arguments define which arguments to pass • We support a number of reifications
  • 30. Reifications • Reifications define data to be passed as arguments • Reify —> Make something into an object that is not one normally • Example: “All arguments of this message”
  • 31. Reifications: examples • All nodes: #object #context #class #node #link • Sends: #arguments #receiver #selector • Method: #arguments #selector • Variable: #value
 They are defined as subclasses of class RFReification
  • 32. Reifications as MetaObject • We support some special metaObjects: • #node The AST Node we are installed on • #object self at runtime • #class The class the links is installed in
  • 33. MetaLink: Condition • We can specify a condition for the MetaLink • Link is active if the condition evaluates to true • We can pass reifications as arguments link := MetaLink new metaObject: Halt; selector: #once; condition: [:object | object == 5] arguments: #(object). (Number>>#sin) ast link: link.
  • 34. MetaLink: control • We can specify when to call the meta-object • We support #before, #after and #instead • The instead is very simple: last one wins
  • 35. Example: Log • We want to just print something to the Transcript link := MetaLink new metaObject: [Transcript show: 'Reached Here']. (Number>>#sin) ast link: link
  • 36. Recursion Problem • Before we see more examples: There is a problem • Imagine we put a MetaLink on some method deep in the System (e.g new, +, do: ). • Our Meta-Object might use exactly that method, too Endless Loop!!
  • 37. Recursion Problem • Solution: Meta-Level • We encode the a level in the execution of the system • Every Link Activation increases the level • A meta-link is just active for one level. (e.g. 0) link := MetaLink new metaObject: [ Object new ]; level: 0. (Behavior>>#new) ast link: link.
  • 38. Example: Log • Better use #level: 0 • Nevertheless: be careful! If you add this to method called often it can be very slow. link := MetaLink new metaObject: [Transcript show: 'Reached Here’]; level: 0.
  • 39. Example: Counter • In the Browser you can add a “counter” to the AST • See class ExecutionCounter install link := MetaLink new metaObject: self; selector: #increase. node link: link.
  • 40. Example: Breakpoint • “Add Breakpoint” in AST (Suggestions) Menu • See class Breakpoint • Break Once • Conditional Break breakLink ^ MetaLink new metaObject: Break; selector: #break; options: options
  • 41. Example: WatchPoint • Watchpoint: Record Value at a point in the AST • Example: Watch event in WorldMorph>>#mouseDown: Click on background -> value recorded
  • 42. Example: WatchPoint • Implementation: class Watchpoint, method install • example of a #after link with a condition link := MetaLink new metaObject: self; selector: #addValue:; arguments: #(value); control: #after; condition: [ recording ].
  • 43. Example: Code Coverage • Small Demo. • Start with CoverageDemo new openWithSpec
  • 44. Example: Code Coverage • Example of a MetaLink with a #node MetaObject • Meta-Object is the node that the link is installed on link := MetaLink new metaObject: #node; selector: #tagExecuted.
  • 45. Interesting Properties • Cross Cutting • One Link can be installed multiple times • Over multiple methods and even Classes • And across operations (e.g., Send and Assignment) as long as all reifications requested are compatible • Fully Dynamic: Links can be added and removed at runtime • Even by the meta-object of another meta-link!
  • 46. Example: Accept for Test • Imagine we want to edit a method that is called often by the System. • How do we test it? • It would be nice if we could “Accept for Test”
  • 47. Example: Accept for Test • Menu in the browser. Quick hack, a Suggestions AST menu shows for all nodes. SugsSuggestion subclass: #SugsAcceptForTest instanceVariableNames: '' classVariableNames: '' package: 'SmartSuggestions-Suggestion' label ^'Accept for test' • We implement our code in the #execute method
  • 48. Example: Accept for Test • How we know that we are in a test? CurrentExecutionEnvironment value isTest • We can compile the current text buffer newMethod := context selectedClass compiler source: context code; options: #(+ optionParseErrors); compile.
  • 49. Example: Accept for Test • Add this code to the beginning of the method: [:aContext :args | CurrentExecutionEnvironment value isTest ifTrue: [ aContext return: (newMethod valueWithReceiver: aContext receiver arguments: args) ]] • Let’s do that with a MetaLink!
  • 50. Example: Accept for Test execute | newMethod metaLink | newMethod := context selectedClass compiler source: context code; options: #(+ optionParseErrors); compile. "the link executes the method we just created and returns" metaLink := MetaLink new metaObject: [ :aContext :args | CurrentExecutionEnvironment value isTest ifTrue: [ aContext return: (newMethod valueWithReceiver: aContext receiver arguments: args) ] ]; selector: #value:value:; arguments: #(context arguments). context selectedMethod ast link: metaLink
  • 51. Limitations • #instead needs more work (e.g to support conditions) • Keep in mind: next metaLink taken into account for next method activation • Take care with long running loops!
  • 52. Help Wanted • We are always interested in improvements! • Pharo 8 is under active development. • Pull Requests Welcome!