Created
February 19, 2011 21:06
-
-
Save dgrunwald/835364 to your computer and use it in GitHub Desktop.
Pattern Matching Idea
This file contains hidden or 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
var usingVarDecl = new VariableDeclarationStatement { | |
Type = Pattern.Any("type"), | |
Variables = { | |
Pattern.NamedGroup( | |
"variable", | |
new VariableInitializer { | |
Initializer = Pattern.Any() | |
} | |
) | |
} | |
}; | |
var usingTryCatch = new TryCatchStatement { | |
TryBlock = Pattern.Any("body"), | |
FinallyBlock = new BlockStatement { | |
Statements = { | |
new IfElseStatement { | |
Condition = new BinaryOperatorExpression( | |
Pattern.NamedGroup("ident", new IdentifierExpression()), | |
BinaryOperatorType.InEquality, | |
new NullReferenceExpression() | |
), | |
TrueStatement = new BlockStatement { | |
Statements = { | |
new ExpressionStatement(Pattern.Backreference("ident").ToExpression().Invoke("Dispose")) | |
} | |
} | |
} | |
} | |
} | |
}; | |
foreach (AstNode node in compilationUnit.Descendants.ToArray()) { | |
Match m1 = usingVarDecl.Match(node); | |
if (m1 == null) continue; | |
Match m2 = usingTryCatch.Match(node.NextSibling); | |
if (m2 == null) continue; | |
if (m1.Single<VariableInitializer>("variable").Identifier == m2.Single<IdentifierExpression>("ident")) { | |
BlockStatement body = m2.Single<BlockStatement>("body"); | |
body.Remove(); | |
node.NextSibling.Remove(); | |
node.ReplaceWith( | |
varDecl => new UsingStatement { | |
ResourceAcquisition = varDecl, | |
EmbeddedStatement = body | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment