Configuration of Flamel

Gofer it
smalltalkhubUser: ‘gisela’ project: ‘Flamel’;
configurationOf: ‘Flamel’;
loadVersion: #development.

Advertisements

Abstraction process

If take a look in the metavariable patterns you can see that it can get as complex as you want.

But, let’s focus in a particular token. We end up with a metavariable, but we can see a pattern from simplicity to complexity:

1. Just abstract the token as a metavariable: we do not care if the method contains the exact word we want everything that contains something acting as that.

Example:

aVariable size.

Maybe we do not care about who is the sender of the message #size. In order to do that, we will abstract the variable ‘aVariable’ as a metavariable:

`object size

2. Abstract a list of tokens: we do not care if the method cointain not only one element also a lot of elements.

Example:

aVariable size.

If the pattern is `object size we are too specific because we are only matching the send to size whom receiver is an object, if we have something like this:

(aCollection select: #even) asOrderedCollection size.

Is not a result, if we want that, we have to specify that we do not care:

`@lotOfStuff size

3. Abstract a recursive pattern: still maybe we want matches if the pattern is repeated

aVariable size size.

If our pattern is: `object size, this does not match. If it’s: `@some size we have one match when some = ‘aVariable size’.

If we put a recursive pattern:

“@some size

We have two matches: one when some=’aVariable size’ and another when some= ‘aVariable’

4. Abstract a statement: Maybe we do not even care about the hole statement, and for this we should use the dot.

Example:

`@.Stat

We can think that in the abstraction patterns you have a variety in abstraction, since one more concret with more information until one more abstract.

And for that we can conclude that we have a flow during the metavariable abstraction:

NoAbstraction <=> Simple <=> List <=> Recursive <=>Statement

In order to support this in flamel I’ve added #FlamelAbstractionStep that basically have 3 main responsabilities:

  • next step: abstract
  • previous step: unAbstract
  • pattern: pattern

You can take an expression, obtain the AST representation and then just send to the node the messages abstract and unAbstract to let the abstration proccess to continue, once you finish just use the expression builder to obtain the expression.

Example:

testAbstractVariableNodeWritesRightPattern
| searchExpression variable root expression |
expression := 'aVariable aMessage'.
root := RBParser parseExpression: expression.
variable := root receiver .
variable abstractOnMatching.
searchExpression := FlamelSearchExpressionBuilder new searchExpressionFor: root.
self assert: searchExpression equals: '`aVariable aMessage'

If we do:

variable variable abstractOnMatching.
variable variable abstractOnMatching.

We will end up with: `@aVariable aMessage.

If you want to get fun annotating nodes I added some protocols to maintain the state in a node:

  • abstractOnMatching: instead the source code for the node we are interested in the metavariable. Each time you say abstractOnMatching you are going up in the matching steps
  • deleteOnMatching: when we want to match, we should not include the code contained inside the node
  • ignoreOnMatching: we go to the last step in the matching process
  • unAbstractOnMatching: we want the previous step for the metavariable

I Also wrote a visitor to genrate the matching expression, so in order to obtain the expression, you can evaluate:

FlamelSearchExpressionBuilder new searchExpressionFor: root.

Define a simple rule for matching

Ok let’s start to understand the rewrite engine.

Let’s do it with an example, our goal:Find all the methods that send the consecutives mesages: #globlals #at:

In our example we want as result:

 

findClassesForCategories: aCollection
| items |
aCollection isEmpty
ifTrue: [ ^ self baseClass withAllSubclasses asSet ].
items := aCollection
gather: [ :category |
((Smalltalk organization listAtCategoryNamed: category)
collect: [ :each | Smalltalk globals at: each ])
select: [ :each | each includesBehavior: self baseClass ] ].
^ items asSet

But not with this variation:

findClassesForCategories: aCollection
| items |
aCollection isEmpty
ifTrue: [ ^ self baseClass withAllSubclasses asSet ].
items := aCollection
gather: [ :category |
((Smalltalk organization listAtCategoryNamed: category)
collect: [ :each | Smalltalk globals at: each ifAbsent: [ "ignore" ]])
select: [ :each | each includesBehavior: self baseClass ] ].
^ items asSet

Why? because in the second example we send the messages #globals (ok we want this!) but then we send #at:ifAbsent: (we don’t want this)

Ok so… Which object do I send wich message to find my “problematics” methods?

Which object?
The answer is very simple a RULE… For each rule you should extend one flavor of rule and define what you want to do. Sounds easy let’s check the rules hierarchy

All of those are abstract classes, so we will take a look into them and choose the one that is better for our case.

  • RBLintRule: defines the protocol used for execute a rule.
    This is a very general class, doesn’t define:
    – what to do when we are cheeking a class, for this we have to implement: #checkClass:. In our case we don’t care about the class, so we can let the default that does nothing with the class
    – what to do when we are cheeking methods, for this we have to implement: #checkMethod:.
    In our case we should obtain the source code form the method and search in the source code all the variants for the consecutive messages #globals #at:, an inocent version of this can be:
    A way to do it:

    checkMethod: aContext
    (aContext compiledMethod source findString: 'globals at:') ~= 0
    ifTrue:["we have a match in aContext selectedClass>> aContext selector we should handle it"]
    

    I said that it is an innocent implementation because if we have a method with the code: “(…) globals  “yes a comment here!”     at: (…)” or “(…) globals           at: number” we aren’t causing a match and if we have: “(…) globals at: something ifAbsent: (…)” we are and we shouldn’t.
    Probably we should allways use one subclass of LintRule with more features implemented otherwise we have to extend LintRule to define what to do in case of matching, model a result, transforming code (…)

  • RBBasicLintRule: it’s another abstract class that adds a result associated to a rule. We still should redefine checkMethod and/or check class but we have a proposal for a result:
    checkMethod: aContext
    (aContext compiledMethod source findString: 'globals at:') ~= 0
    ifTrue:[result addClass: aContext selectedClass selector: aContext selector ]
    

    This can be a good extension point, but again… you have a lot to implement here.

  • RBBlockLintRule: it’s an abstract class, that by default specifies that the resultClass corresponds to a selector environment.
    This class doesn’t add a lot of behavior but we reduce errors related to the result handling.
  • RBParseTreeLintRule: here is where everything gets interesting.
    The main point in this class is to offer an implementation for #checkMethod: the implementation motivation is to check methods using ast’s representations.
    We will have a wanted tree and then we will obtain the AST for the checked method, in order to find a match we observe if the wanted tree is subtree of the method tree.
    Also it’s posible to define metavariables where we can specify that we want to match with a node type but not necesary the value of it.
    In our example our matching expression will look like:

    “@lotOfStuffBefore globals at: “@lotOfStuffAfter

    With this expresion we are saying:
    –  “@lotOfStuffBefore: ignore everything before globals (receiver / message send):
    –   “@lotOfStuffAfter: ignore everything after at: (object / messages)
    (For more information about metavariables see my first post)
    The solution implemented for the check method introduces new objects:

    Matcher: Is the responsable for visit an AST and verify the matches. Is the matcher the one who interprets the matching expressions. First of all we have to specify if we are matching with a method (matchesMethod: aString do: aBlock) or an expreesion (matches: aString do: aBlock) pattern.
    We can add more than one matching expression, it’s very important to know that every time we add an expression in the matcher inside we are adding a RBSearchRule for that expression.
    When the tree rule sends the message executeTree: to the matcher at the end the matchers iterates over all the rules visiting the nodes delegating in the RBSearchRules to perform the match.
    It’s important to say that the search rules aren’t deleted automatically, so, if you want to reuse the object probably you should reset the rule, reseting the matcher.
    ParseTreeEnvironment: Is an specialized SelectorEnvironment that makes it possible to detect the selection interval for an expression inside the method, using the ast matcher
    This class is still abstract because we should categorize it, adding a name and initilize the rule with the matching expression patterns.
    In functionality is almost the same that before but we have other abstraction level, the result is handled automatically, and we don’t have to worry about checking a method or a class only to define the desired matching expression.

  • RBCompositeLintRule: Is just a composite for rules.
  • RBTransformationRule: The main idea here is to produce a transformation in the system, for this implements: #checkMethod: in a similar way that RBParseTreeLintRule the diference is that if we find a match we will produce a modification in the code and then we change the method with the new version of the code (recompiling the new method).
    In order to solve this the rule adds some objects:
    RBParseTreeEnvironment: with all the results, the results are: RBAddMethodChange to track a change in a method
    RBParseTreeRewriter: It’s a subclass off the matcher (RBParseTreeSearcher) and again the main point is that this is a visitor that works over a method AST changing it depending in the matching and transforming expression.
    The transforming expression also works with metavariable and usually we use the metavariables defined in the matching expression to specify the transformation.

Resuming:

  1. Before start you should choose if you want to:
    perform a search
    do a match
  2. Implement your rules because all of them are abstract, probably you will end up using the Tree rules because are more automatics and powerfull than to basics.
  3. When you are defining your rule:
    – give a name for it
    – define if you will use a method or an expression type pattern
    – write your patterns and add them to the rule
    – if you are in a search rule to the matcher
    – if you are in a transformation rule rewriteRule
    – define what to do with a result
  4. run your rule
  5. use your results
  6. if you want to reuse it reset your rule, again if it’s a search rule, reset the matcher, if it’s a transformation rule the rewriteRule.

In our example:

  • we want to match, so let’s create an object that extends: RBParseTreeLintRule:
 RBParseTreeLintRule subclass: #SearchGlobalsAtUsage
 instanceVariableNames: ''
 classVariableNames: ''
 poolDictionaries: ''
 category: 'Blog-example'
 
  •  we have to implement the abstract methods:
 name
 ^ 'Find all potential wrong usage in with globals'
 
  • I want to match an expression type because I do not care about the rest of the method, I want everything that contains the messages: #globals #at:, we also have to say what to do with the matching node in this example I will open an inspector:
 initialize
 super initialize.
 self matcher
 matches: '``@lotOfStuffBefore globals at: ``@lotOfStuffAfter'
 do: [:theMatch :theOwner | theMatch inspect].
 
  • now we should run the rule:

WARNING: this can take a time because you will check the hole system

 SearchGlobalsAtUsage new run.

To avoid this you can restrict the environment for your rule, an example:

 rule := SearchGlobalsAtUsage new.
 environment := RBClassEnvironment class: Result.
 RBSmalllintChecker runRule: rule onEnvironment: (environment).
 

If you have matches then you will see the inspector.

So, as we can see this is quite complex, and in the sinposis you can see that before doing anything you have to make too many decisions, the idea behind Flamel is to make it easier.

The equivalent code (with a restricted environment) using Flamel for all this is:

FlamelMatchAndTransformRule new
 matchingExpression: '``@lotOfStuffBefore globals at: ``@lotOfStuffAfter';
 scope: environment;
 run;
 result

If you evaluate that and inspect it you can search your results 🙂

I think this is quite cool to replace all that code (with class creation included) with 5 lines.

And this was all for understanding a little bit the rewrite engine and see Flamel in action for today

 

Searching in Flamel!

I want to show a proposal for using the matching expression builder.

The idea is to keep it simple, so if you think this is very complex, let me know!

First of all open Flamel-UI, in a workspace:

Flamel new openWithSpec.

For those non familiarized with the project, you will see something like this:

Flamel - UI
A short summary:

  • Scope for the rule: Here we restrict the scopes for the rule, for those familiarized with the RW-Engine behind this we have the RBEnvironment objects.
  • Define match: The idea here is to help to define the matching rule, for this we have:
  • Starting point example method: We choose a method to use as an example for the pattern, you can change for the method you want, and you have more options available (just, right click and see)
  • Pattern expression type: 3 options here:
  •             Method: The pattern corresponds to a method
  •             Expression: The pattern corresponds to an expression, so we don’t have the selector definition plus the optional temporary variables definition
  •             Both: Basically, try to search the matching expression as a method and as an expression
  • Matching expression: The pattern we will search
  • Define transformation: The same idea for the matching but in this case to help you with the transformation

How to use Flamel in 5 stepChoose the scope for your rule

  1. if we don’t clarify this we will look in the hole image and this takes time

  2. Select your base example: You can use the default example or… choose an example method that is better for you

    The example will help you to define the pattern

    For change the example, right click in the Starting point example method and choose: “Change example”, you will see a window like this:

    FlamelUI-selectMethodWhere you can choose the class and method you desire to use as an example.

  3. Choose the Pattern expression type: If you are not sure, just let the both and we will try to do our best, but if you really know if you want to define a pattern with a method syntax or not (an expression) choose the best option.
  4. Define the matching expression: For this we use the right-click menu options to help us.
    We can start choosing “Reset expression” and then we will see the same code in the example as a pattern
    Then we use the menu to modify the expression
  5.  Perform the search just clicking in the Search button.

And then see your results!

Flamel is growing!

One image it’s a great way to show the current status:

A quick view

A quick view

As you can see we still have (a lot of) work to do… But we can:

  • Choose the scope where we run the run (right now a class/es or a package/packages)
  • Enter the expresion for matching and transforming
  • Search the matches
  • Apply the entire rule (matching expresion + transforming)
  • We have some actions implemented for the menus (same code, containing code, defining a variable)
  • Inspect the result for a Search or Transformation action

But still now I have some thing that I observed: The rewrite engine its in fact very cool, and surely does everything we want to do.

But it’s very complex you have to choose the matcher , modify the pattern (is an expression? is a method? you have multiple options? is about an argument?), set the environment (do you want to run where? each Environment is represented but wait! Which matcher are you using? Because not all have the feature, and they are not all polimorfic when you want to match. And of course do not even talk about  the regular expresions and the usual doubts we have (with temps? with N arguments? previous statements? and don’t forget the dot!), and… before starting… do you want to match? or do you want to transform? You have to choose!

And usually you don’t have all the information to choose that in an early moment, so what I’ve done it’s to implement a rule that delegates in existing components but takes the desitions for you… By example: Do you want to transform? Or just match? That depends… do we have a transformation expression? If that is true we want to search and replace.


testMatchAnUndefinedExpressionNotFind
 | rule |
 rule := FlamelMatchAndTransformRule new.
 rule matchingExpression: 'testFlamelFlamelNotDefinedInAnyPlaceNever'.
 rule scope: (RBClassEnvironment class: FlamelSearchMock ).
 rule run.
 self assert: (rule result isEmpty )

I want to change that to be something like:

testMatchAnUndefinedExpressionNotFind
| rule |
rule := FlamelMatchAndTransformRule new.
rule matchingExpression: 'testFlamelFlamelNotDefinedInAnyPlaceNever'.
rule applyToClass: FlamelSearchMock.
rule run.
self assert: (rule result isEmpty )

So, I have lot of work!

Some known bugs, and some unknown you can check the todo list in a Trello dashboard: https://trello.com/b/XqfJGqeB/flamel

It would be great to improve the UI because it’s quite “rustic”.

And my plan for this week it’s:

  • Implement result views ==> with this one we have a first real prototype for the tool because we can: filter the scope, enter a matching/transforming expression and understand the results
  • Implement actions for transforming menu

And as allways if you want to try download from Smalltalkhubhttp://smalltalkhub.com/mc/gisela/Flamel/main.

To open the browser just:

Flamel new openWithSpec

All the comments that you have are very wellcome, please don’t hestiate in comment or send me an email directly to me: giseladecuzzi@gmail.com.

Have a great week and nice coding!