Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace ResharperContextActions
- {
- using System;
- using System.Text;
- using JetBrains.Application;
- using JetBrains.ReSharper.Intentions;
- using JetBrains.ReSharper.Intentions.CSharp.ContextActions;
- using JetBrains.ReSharper.Psi.CSharp.Tree;
- using JetBrains.ReSharper.Psi.ExtensionsAPI;
- /// <summary>
- /// Inlines power declaration.
- /// </summary>
- [ContextAction(Group = "C#", Name = "Inline a power function",
- Description = "Inlines a power statement; e.g., changes Math.Pow(x, 3) to x*x*x.",
- Priority = 15)]
- internal class InlinePowerAction : ContextActionBase
- {
- private string text;
- public InlinePowerAction(ICSharpContextActionDataProvider provider) : base(provider) {}
- protected override void Execute(JetBrains.ReSharper.Psi.Tree.IElement element)
- {
- IInvocationExpression expression = GetSelectedElement<IInvocationExpression>(false);
- if (expression != null)
- {
- IInvocationExpressionNode node = expression.ToTreeNode();
- if (node != null)
- {
- IArgumentListNode args = node.ArgumentList;
- int count = (int)double.Parse(args.Arguments[1].Value.GetText().Replace("f", string.Empty));
- bool isShort = node.Arguments[0].Value is ILiteralExpression ||
- node.Arguments[0].Value is IReferenceExpression;
- var sb = new StringBuilder();
- sb.Append("(");
- for (int i = 0; i < count; ++i)
- {
- if (!isShort) sb.Append("(");
- sb.Append(args.Arguments[0].GetText());
- if (!isShort) sb.Append(")");
- if (i + 1 != count)
- sb.Append("*");
- }
- sb.Append(")");
- // now replace everything
- ICSharpExpression newExp = Provider.ElementFactory.CreateExpression(
- sb.ToString(), new object[] { });
- if (newExp != null)
- {
- LowLevelModificationUtil.ReplaceChildRange(
- expression.ToTreeNode(),
- expression.ToTreeNode(),
- new[] { newExp.ToTreeNode() });
- }
- }
- }
- }
- protected override string GetText()
- {
- return text;
- }
- protected override bool IsAvailable(JetBrains.ReSharper.Psi.Tree.IElement element)
- {
- using (ReadLockCookie.Create())
- {
- IInvocationExpression invEx = GetSelectedElement<IInvocationExpression>(false);
- if (invEx != null && invEx.InvokedExpression.GetText() == "Math.Pow")
- {
- IArgumentListNode node = invEx.ToTreeNode().ArgumentList;
- if (node != null && node.Arguments.Count == 2)
- {
- ILiteralExpression value = node.Arguments[1].Value as ILiteralExpression;
- if (value != null)
- {
- float n;
- if (float.TryParse(value.GetText().Replace("f", string.Empty), out n) &&
- (n - Math.Floor(n) == 0 && n >= 1 && n <= 10))
- {
- text = "Replace with " + (n-1) + " multiplications";
- return true;
- }
- }
- }
- }
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement