Skip to content

Instantly share code, notes, and snippets.

@dgrunwald
Created February 19, 2011 21:06
Show Gist options
  • Save dgrunwald/835364 to your computer and use it in GitHub Desktop.
Save dgrunwald/835364 to your computer and use it in GitHub Desktop.
Pattern Matching Idea
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