-
-
Notifications
You must be signed in to change notification settings - Fork 347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
review: feature: introduce the concept of "Pattern" #1686
Merged
Merged
Changes from all commits
Commits
Show all changes
140 commits
Select commit
Hold shift + click to select a range
34c3b2e
feat: Metamodel provides metadata about Spoon types and fields
pvojtechovsky 274efac
rename MMType, MMField - runtime metamodel
pvojtechovsky 5c4f605
Pattern
pvojtechovsky 40d9f01
rename MMType, MMField - pattern
pvojtechovsky 25b3fc1
Factory is available during whole generation process
pvojtechovsky 967f405
move parameter classes to own package
pvojtechovsky 5806741
rename Accessor to ParameterInfo
pvojtechovsky 8fc3ed5
Rename Parameters
pvojtechovsky f9a5060
All Node classes moved to package node
pvojtechovsky 5ce66bb
Generator used in generation process
pvojtechovsky 964bf84
rename Node to RootNode (to avoid Eclipse problem with `Node`)
pvojtechovsky 7414078
AbstractNode#toString
pvojtechovsky e71c085
Printing of pattern sources of live statements
pvojtechovsky c54079b
ElementNode toString
pvojtechovsky 0fd2162
matcher ignores some roles
pvojtechovsky 94881ea
fix Template containerKind
pvojtechovsky ed3286c
position is generated too - same like before
pvojtechovsky 89970cc
generate by
pvojtechovsky cdf3685
support of generated by comments
pvojtechovsky 34a0cfd
simplify generated code
pvojtechovsky 4cf1675
Pattern printing
pvojtechovsky 18e7800
Support specific matcher + generic matcher for other container items
pvojtechovsky 03afb4c
Matching of MapEntries
pvojtechovsky 287d60f
fix tests and some docu
pvojtechovsky 6d2312d
more comments
pvojtechovsky 712ebc4
fix runtime metamodel
pvojtechovsky 89935b8
fix runtime metamodel test
pvojtechovsky 9b26a20
checkstyle and fixed some java doc
pvojtechovsky 98d18b8
review testTemplateMatchOfMultipleElements
monperrus 3b3ca5e
Pattern can be created from spoon AST directly
pvojtechovsky fc7050a
added explanation of PatternBuilder selector
pvojtechovsky bb50912
some javadoc added to TemplateModelBuilder
pvojtechovsky eb84831
up
monperrus 7c35eb3
javadoc of Match
pvojtechovsky 32402ae
check style
pvojtechovsky 4dca389
up
monperrus 26c8cb0
added comment
pvojtechovsky 3fa34b3
remove default implementation to force children define behavior
pvojtechovsky 9d1f9c4
cleaning and test of matching in Set
pvojtechovsky 2e392db
Documentation updated - 1st part ... TODO
pvojtechovsky 39c2d56
PatternBuilder documentation
pvojtechovsky f805d64
rename `live` to `inline` statements
pvojtechovsky bf53692
fix template_definition documentation
pvojtechovsky 60e0ebd
TemplateModelBuilder moved to separate file
pvojtechovsky 26b1f26
fix docu
pvojtechovsky 9f8b8bf
work on API and tests
monperrus a692251
up
monperrus cdf1a57
up
monperrus 9ae435b
check all params of both matches
pvojtechovsky f257c12
patternModel is unmodifiable list. method selectNodes was deleted
pvojtechovsky 0b19d6b
fix tests
pvojtechovsky 9dcffea
check if declaring type is computable
pvojtechovsky a3e3927
remove declaring typeRef from PatternBuilder#create
pvojtechovsky f675ade
configureLocalParameters is package protected
pvojtechovsky 8fdb2a2
test of generating of self referenced methods and types
pvojtechovsky 9e7f91a
hiding some methods, tests
pvojtechovsky 983b129
up
monperrus 8d609bd
little documentation changes
pvojtechovsky b248ecf
feature: PatternBuilder#matchInlinedStatements
pvojtechovsky 5d333a0
up
monperrus 5f0d791
up
monperrus b3d68cd
up
monperrus 5c8a03e
up
monperrus 71712f6
up
monperrus 34aaf91
up
monperrus e4157a4
added contract to #testGenerateMultiValues
pvojtechovsky 410586e
up
monperrus 215b3c2
Pattern is Consumable (to simplify API)
monperrus 14daf59
doc
monperrus 0afd673
udpate test testGenerateMultiValues
monperrus 1d9713e
up
monperrus d709a50
up
monperrus 81a0e96
copy ElementPrinterHelper to test to keep test independent on spoon core
pvojtechovsky 65dc0bc
fix to pass testTemplateInheritance
pvojtechovsky 3aa1103
move tests related to Pattern from TemplateTest into PatternTest
monperrus a2e7415
up
monperrus 4aa325c
up
monperrus e7bac51
end of review of testMatchIfElse
monperrus 6304878
up
monperrus 6aa7845
ParameterValueProvider moved to spoon.support.util
pvojtechovsky 370e4d3
up
monperrus c00b65b
up
monperrus 2567fc2
up
monperrus 14f06aa
up
monperrus ca2c35b
Commit by Martin Monperrus on 01 May 2018
monperrus 0b43f8b
fix test
pvojtechovsky 488abca
fix test on MS Windows
pvojtechovsky c14eeb2
up
monperrus d679177
Merge branch 'master' into feaPattern
monperrus 5dd9c92
up
monperrus 198248d
move non public API classes to package ...internal...
pvojtechovsky 7c9e350
up
monperrus c6dfc8d
up
monperrus 898f878
up
monperrus 15f2543
up
monperrus 176468d
up
monperrus 0a30676
delete ParameterValueProviderFactory
monperrus edd4b21
fix problems caused by refactoring
pvojtechovsky 649f8a4
Merge branch 'feaPattern' of github.com:pvojtechovsky/spoon into feaP…
monperrus ba1b554
re-add removeSuperClass which is needed to create pattern from legacy
pvojtechovsky 15c22f1
add test for Match#toString
monperrus e8d934d
add test for ImmutableMapImpl#asMap
monperrus c729798
remove untested useless code in StatementTemplate
monperrus b476963
fix javadoc bug
monperrus d132fc5
fix checkstyle
monperrus b363333
up
monperrus e9df1b8
up
monperrus 1719d49
fix javadoc error
pvojtechovsky 71a5ac3
move feature configurePatternParameters(Map) to byTemplateParameter and
pvojtechovsky e445995
Pattern generator methods moved to class Generator
pvojtechovsky 8ee3507
fix javadoc error
pvojtechovsky 5f40017
up
monperrus 8091954
up
monperrus c957f78
up
monperrus 9ce97bd
up
monperrus 5632894
up
monperrus 6ed144c
up
monperrus eecce4c
up
monperrus 585a4df
remove ModelNode, and Pattern#getModelValueResolver
pvojtechovsky b30534d
up
monperrus 67090bb
up
monperrus 5e547d7
up
monperrus 41a7559
up
monperrus e787e0c
Merge branch 'master' into feaPattern
monperrus f0fc029
cleaning and buig fixing
pvojtechovsky a15e5f8
ExtensionTemplate uses new generator - more tests covered
pvojtechovsky 98adea5
Merge remote-tracking branch 'origin/master' into feaPattern
pvojtechovsky 60d0381
remove SubstitutionVisitor
pvojtechovsky dd30d1e
use/test PatternBuilderHelper#setReturnExpressionOfMethod
pvojtechovsky fce2bc9
Merge branch 'master' into feaPattern
monperrus c9eee72
up
monperrus 6ffea86
test optional generator and fix SwitchNode
pvojtechovsky 6ef61b3
Merge remote-tracking branch 'origin/master' into feaPattern
pvojtechovsky 1451e5b
improve metamodel test
pvojtechovsky c17e74c
Merge remote-tracking branch 'origin/master' into feaPattern
pvojtechovsky 1483c51
unsettableProperty implies derived on leaf concept
pvojtechovsky 89123b2
Pattern uses new metamodel
pvojtechovsky 7e7f89f
move old metamodel to test to be able to check computed metamode
pvojtechovsky d7947c2
fix javadoc
pvojtechovsky bb782e9
remove metamodel test and MetamodelGenerator from this PR
pvojtechovsky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
--- | ||
title: Spoon Patterns | ||
--- | ||
|
||
Spoon patterns enables you to find code elements. A Spoon pattern is based on a one or several AST nodes, which represent the code to match, where some parts of the AST are pattern parameters. When a pattern is matched, one can access to the code matched in each pattern parameter. | ||
|
||
The main classes of Spoon patterns are those in package `spoon.pattern`: | ||
|
||
* classes: PatternBuilder, Pattern, Match, PatternBuilderHelper, PatternParameterConfigurator, InlinedStatementConfigurator | ||
* eums: ConflictResolutionMode, Quantifier | ||
|
||
Example usage: | ||
|
||
```java | ||
Factory spoonFactory = ... | ||
//build a Spoon pattern | ||
Pattern pattern = ... build a spoon pattern. For example for an method ... | ||
|
||
//search for all occurences of the method in the root package | ||
pattern.forEachMatch(spoonFactory.getRootPackage(), (Match match) -> { | ||
Map<String, Object> parameters = match.getParametersAsMap(); | ||
CtMethod<?> matchingMethod = match.getMatchingElement(CtMethod.class); | ||
String aNameOfMatchedMethod = parameters.get("methodName"); | ||
... | ||
}); | ||
``` | ||
|
||
## PatternBuilder | ||
|
||
To create a Spoon pattern, one must use `PatternBuilder`, which takes AST nodes as input, and **pattern parameters** are defined. | ||
|
||
|
||
```java | ||
// creates pattern from the body of method "matcher1" | ||
Pattern t = PatternBuilder.create( | ||
new PatternBuilderHelper(fooClass).setBodyOfMethod("matcher1").getPatternElements()) | ||
.configurePatternParameters() | ||
.build(); | ||
``` | ||
|
||
|
||
This pattern matches all statements of the body of method `statement`, ie. a precondition to check that a list is smaller than a certain size. | ||
This pattern has one single pattern parameter called `_col_`, which is automatically considered as a pattern parameter because it is declared outside of the AST node. This automatic configuration happens when `configurePatternParameters` is called. | ||
|
||
## Pattern | ||
|
||
The main methods of `Pattern` are `getMatches` and `forEachMatch`. | ||
|
||
``` | ||
List<Match> matches = pattern.getMatches(ctClass); | ||
``` | ||
|
||
## Match | ||
|
||
A `Match` represent a match of a pattern on a code elements. | ||
|
||
The main methods are `getMatchingElement` and `getMatchingElements`. | ||
|
||
## PatternBuilderHelper | ||
|
||
`PatternBuilderHelper` is used to select AST nodes that would act as pattern. It is mainly used to get the body (method `setBodyOfMethod`) or the return expression of a method (method `setReturnExpressionOfMethod`) . | ||
|
||
## PatternParameterConfigurator | ||
|
||
To create pattern paramters, one uses a `PatternParameterConfigurator` as a lambda: | ||
|
||
|
||
```java | ||
//a pattern model | ||
void method(String _x_) { | ||
zeroOneOrMoreStatements(); | ||
System.out.println(_x_); | ||
} | ||
|
||
//a pattern definition | ||
Pattern t = PatternBuilder.create(...select pattern model...) | ||
.configureParameters(pb -> | ||
// creating a pattern parameter called "firstParamName" | ||
pb.parameter("firstParamName") | ||
//...select which AST nodes are parameters... | ||
//e.g. using parameter selector | ||
.bySimpleName("zeroOneOrMoreStatements") | ||
//...modify behavior of parameters... | ||
//e.g. using parameter modifier | ||
.setMinOccurence(0); | ||
|
||
//... you can define as many parameters as you need... | ||
|
||
// another parameter (all usages of variable "_x_" | ||
pb.parameter("lastParamName").byVariable("_x_"); | ||
) | ||
.build(); | ||
``` | ||
|
||
`ParametersBuilder` has many methods to create the perfect pattern parameters, incl: | ||
|
||
* `byType(Class|CtTypeReference|String)` - all the references to the type defined by Class, | ||
CtTypeReference or qualified name are considered as pattern parameter | ||
* `byLocalType(CtType<?> searchScope, String localTypeSimpleName)` - all the types defined in `searchScope` | ||
and having simpleName equal to `localTypeSimpleName` are considered as pattern parameter | ||
* `byVariable(CtVariable|String)` - all read/write variable references to CtVariable | ||
or any variable named with the provided simple name are considered as pattern parameter | ||
* `byInvocation(CtMethod<?> method)` - all invocations of `method` are considered as pattern parameter | ||
* `byVariable(CtVariable|String... variableName)` - each `variableName` is a name of a variable | ||
which references instance of a class with fields. Each such field is considered as pattern parameter. | ||
* `byFilter(Filter)` - any pattern model element, where `Filter.accept(element)` returns true is a pattern parameter. | ||
* `byRole(CtRole role, Filter filter)` - the attribute defined by `role` of all | ||
pattern model elements, where `Filter.accept(element)` returns true is a pattern parameter. It can be used to define a varible on any CtElement attribute. E.g. method modifiers or throwables, ... | ||
* `byString(String name)` - all pattern model string attributes whose value is equal to `name` are considered as pattern parameter.This can be used to define full name of the methods and fields, etc. | ||
* `bySubstring(String stringMarker)` - all pattern model string attributes whose value contains | ||
whole string or a substring equal to `stringMarker`are pattern parameter. Note: only the `stringMarker` substring of the string value is substituted, other parts of string/element name are kept unchanged. | ||
* `byNamedElement(String name)` - any CtNamedElement identified by it's simple name is a pattern parameter. | ||
* `byReferenceName(String name)` - any CtReference identified by it's simple name is a pattern parameter. | ||
|
||
|
||
Any parameter of a pattern can be configured like this: | ||
|
||
* `setMinOccurence(int)` - defines minimal number of occurences of the value of this parameter during **matching**, | ||
which is needed by matcher to accept that value. | ||
* `setMinOccurence(0)` - defines optional parameter | ||
* `setMinOccurence(1)` - defines mandatory parameter | ||
* `setMinOccurence(n)` - defines parameter, whose value must be repeated at least n-times | ||
* `setMaxOccurence(int)` - defines maximal number of occurences of the value of this parameter during **matching**, | ||
which is accepted by matcher to accept that value. | ||
* `setMatchingStrategy(Quantifier)` - defines how to matching engine arehave when two pattern nodes may accept the same value. | ||
* `Quantifier#GREEDY` - Greedy quantifiers are considered "greedy" because they force the matcher to read in, or eat, the entire input prior to attempting the next match. | ||
If the next match attempt (the entire input) fails, the matcher backs off the input by one and tries again, | ||
repeating the process until a match is found or there are no more elements left to back off from. | ||
* `Quantifier#RELUCTANT` - The reluctant quantifier takes the opposite approach: It start at the beginning of the input, | ||
then reluctantly eat one character at a time looking for a match. | ||
The last thing it tries is the entire input. | ||
* `Quantifier#POSSESSIVE` - The possessive quantifier always eats the entire input string, | ||
trying once (and only once) for a match. Unlike the greedy quantifiers, possessive quantifiers never back off, | ||
even if doing so would allow the overall match to succeed. | ||
* `setValueType(Class type)` - defines a required type of the value. If defined the pattern matched, will match only values which are assigneable from the provided `type` | ||
* `matchCondition(Class<T> type, Predicate<T> matchCondition)` - defines a `Predicate`, whose method `boolean test(T)`, | ||
are called by pattern matcher. Template matcher accepts that value only if `test` returns true for the value. | ||
The `setValueType(type)` is called internally too, so match condition assures both a type of value and condition on value. | ||
* `setContainerKind(ContainerKind)` - defines what container are used to store the value. | ||
* `ContainerKind#SINGLE` - only single value is accepted as a parameter value. | ||
It can be e.g. single String or single CtStatement, etc. | ||
* `ContainerKind#LIST` - The values are always stored as `List`. | ||
* `ContainerKind#SET` - The values are always stored as `Set`. | ||
* `ContainerKind#MAP` - The values are always stored as `Map`. | ||
|
||
|
||
## InlinedStatementConfigurator | ||
|
||
It is possible to match inlined code, eg: | ||
|
||
```java | ||
System.out.println(1); | ||
System.out.println(2); | ||
System.out.println(3); | ||
``` | ||
|
||
can be matched by | ||
|
||
```java | ||
for (int i=0; i<n; i++) { | ||
System.out.println(n); | ||
} | ||
``` | ||
|
||
One mark code to be matched inlined using method `configureInlineStatements`, which receives a InlinedStatementConfigurator as follows: | ||
```java | ||
Pattern t = PatternBuilder.create(...select pattern model...) | ||
//...configure parameters... | ||
configureInlineStatements(ls -> | ||
//...select to be inlined statements... | ||
//e.g. by variable name: | ||
ls.byVariableName("intValues") | ||
).build(); | ||
``` | ||
|
||
The inlining methods are: | ||
|
||
* `inlineIfOrForeachReferringTo(String varName)` - all CtForEach and CtIf statements | ||
whose expression references variable named `varName` are understood as | ||
inline statements | ||
* `markAsInlined(CtForEach|CtIf)` - provided CtForEach or CtIf statement | ||
is understood as inline statement | ||
|
||
## Generator | ||
|
||
All patterns can be used for code generation. The idea is that one calls `#generator()` on a pattern object to get a `Generator`. This class contains methods that takes as input a map of string,objects where each string key points to a pattern parameter name and each map value contains the element to be put in place of the pattern parameter. | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The keywords
statement
and_col_
are wrong with updated exampleThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could you fix them directly? that would likely be more effective.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I started to do it before I wrote this comment, but then I had feeling like there is too many changes and I do not know your vision, so my fix might ho in wrong direction:
A) to remove comment about col
B) to re-add the example you removed
... I would prefer B), but you already removed it so, you probably prefer something else :-)