title: C# CodeAnalysis - Structure of expressions
body: <p>I want to do a simple code replacement in a C# (.NET 4.5) script in VS2013. Each <code>@GetIt</code> call should be rewritten so that it is encapsulated in a lambda function:</p>
  
  <pre><code>new MyClass(@GetInt("a") * @GetInt("b"));
  </code></pre>
  
  <p>becomes</p>
  
  <pre><code>new MyClass( x =&gt; (x.GetInt("a") * x.GetInt("b")) )
  </code></pre>
  
  <p>I installed the CodeAnalysis of Roslyn to parse the scripts. I use the following call to get all tokens with the <code>@GetInt</code> identifier:</p>
  
  <pre><code>var getters = CSharpSyntaxTree.ParseText("new MyClass(@GetInt("a") * @GetInt("b"));")
                                .GetRoot().DescendantTokens().OfType&lt;SyntaxToken&gt;()
                                .Where(x =&gt; x.Text.Equals("@GetInt"));
  </code></pre>
  
  <p>For <code>@GetInt</code> as a simple parameter of the <code>MyClass</code> constructor it works fine and using <code>getters[i].Parent.Parent.Parent.Parent</code> I correctly get to the <code>MethodDeclarationSyntax</code> node of the constructor.</p>
  
  <p>However, adding the multiplication as in the example on the top, token for the second <code>@GetInt</code> declares <code>* GetInt("b")</code> as its parent (it is howevver already a <code>MethodDeclarationSyntax</code>, not a parameter node) and traversing back to its parent leads to the <code>CompilationUnitSyntax</code> which is the root! </p>
  
  <p>This way, I get no information about the position of the second <code>@GetInt</code> in the syntax tree. Consequently the replacement is not possible without the missing information.</p>
  
  <p>I have checked the case without using the prefix <code>@</code>, but the result was the same. Can someone please tell me whether I'm doing something wrong?</p>
  
  <p><strong>SOLUTION</strong> as suggested by JoshVarty in one of his comments: Until the code analysis of Scripts is disabled in the NuGet package, I have to use a workaround. First, I take the <code>string script = "..."</code> and decorate it to</p>
  
  <pre><code>var decoratedScript = "class MYCLASS { void METHOD() {\n" + script + "\n} }";
  </code></pre>
  
  <p>After the rewriting of <code>@GetInt</code> is done, I remove the added decorations.</p>