Jason Bock

.NET Development Using the Compiler API

Jason Bock

Shakopee, Minnesota, USA

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com/9781484221105 . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-2110-5

e-ISBN 978-1-4842-2111-2

DOI 10.1007/978-1-4842-2111-2

Library of Congress Control Number: 2016945755

© Jason Bock 2016

.NET Development Using the Compiler API

Managing Director: Welmoed Spahr

Lead Editor: James DeWolf

Technical Reviewer: Fabio Claudio Ferracchiati

Editorial Board: Steve Anglin, Pramila Balan, Aaron Black, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, James Markham, Natalie Pao, Susan McDermott, Matthew Moodie, Ben Renow-Clarke, Gwenan Spearing

Coordinating Editor: Melissa Maldonado

Copy Editor: Laura Lawrie

Compositor: SPi Global

Indexer: SPi Global

Artist: SPi Global

For information on translations, please e-mail [email protected] , or visit www.apress.com .

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales .

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

About the Technical Reviewer

A prolific writer on cutting-edge technologies, Fabio Claudio Ferracchiati has contributed to more than a dozen books on .NET, C#, Visual Basic, and ASP.NET. He is a .NET Microsoft Certified Solution Developer and lives in Milan, Italy. You can read his blog at http://www.Ferracchiati.com .

Introduction

Most developers I know typically view coding as a means to an end. That is, they write the code to satisfy the requirements set forth by the business. The code is interpreted or compiled, but either way, the final result is machine code that executes and (hopefully) does the right thing.

However, there’s more to software development than just that. I’m not talking about process or patterns per se; what I’m getting at is for developers to view their code in a more analytical way. Throughout my career, I’ve run into numerous cases in which I would’ve loved to have the ability to analyze my code so I could find errors quickly. I’ve also wanted to be able to extend and augment languages in certain ways so I didn’t have to write the same code over and over again. The primary language that I’ve used throughout my career has been C#, and although C# is a fine language to develop in, it seemed to lack these dynamic, analytical capabilities.

That’s no longer the case. Microsoft has provided public, open-source components in its Compiler API that allows developers to create analyzers that will help them detect problematic issues. This API also empowers developers to build code at runtime to create amazing, dynamic applications and libraries. Because all of this code is open source, it’s available to read and contribute to. Enabling .NET developers to shape and mold the future of the .NET compilation system is a wonderful thing to behold, and it’s exciting to see the development community embrace this model.

I wrote this book to help you navigate this new open-source API world. In it, I demonstrate how to use the Compiler API to write custom analyzers and refactorings to improve your code base. I show you how to use the Scripting API (part of the Compiler API) to use C# as a scripting language, a feature that was essentially unavailable to C# developers. I also illustrate how to use the Compiler API in innovative ways that go beyond these typical scenarios. My hope is that when you’ve finished this book, you’ll view C# and the ecosystem that supports it in a fundamentally different (and hopefully positive!) way—as a language that is open in terms of its implementation and its community involvement.

Who This Book Is For

This book is for architects and developers who have experience with C# and want to dive deeper into how code is compiled and executed. There’s no expectation that the reader has any experience with compilers, but I do assume that the reader has foundational knowledge of C#.

Chapter Contents

To give you a feel for the content in the book, here’s a brief synopsis of each chapter.

  • Chapter 1 —You’ll get an introduction to the Compiler API and its constituent parts: syntax trees, semantic models, and formatters.

  • Chapter 2 —This chapter covers diagnostics. You’ll learn how to write analyzers and build code fixes to automate code corrections.

  • Chapter 3 —Refactoring code is a primary tenant for developers. This chapter shows you how to write refactorings to clean up your code base.

  • Chapter 4 —C# is now a scripting language! In this chapter, you’ll see how the Scripting API works.

  • Chapter 5 —You’ll discover how developers are using the Compiler API to empower their own components and get a preview of a future C# feature based on the Compiler API that could fundamentally change how you write code in C#.

Code Samples

Throughout the book I show code snippets to illustrate various aspects of the Compiler API. You’ll find all of the code at https://github.com/jasonbock/compilerAPIBook . The folder structure is set up to map the code content to each chapter of the book.

Errata

The author, the technical reviewers, and many Apress staff have made every effort to find and eliminate all errors from this book’s text and code. Even so, there are bound to be one or two glitches left. To keep you informed, there’s an Errata tab on the Apress book page ( www.apress.com/9781484221105 ). If you find any errors that haven’t already been reported, such as misspellings or faulty code, please let us know by e-mailing [email protected] .

Customer Support

Apress wants to hear what you think—what you liked, what you didn’t like, and what you think could be done better next time. You can send comments to [email protected] . Be sure to mention the book title in your message.

Contacting the Author

Feel free to follow me on Twitter at @jasonbock. My web site is http://www.jasonbock.net . You can also contact me via e-mail at [email protected] .

Acknowledgments

I’d like to thank Apress for contacting me at VSLive in 2015 and asking me if I’d be interested in writing a book on the Compiler API. Getting the opportunity to write on a topic that I’ve been deeply interested in since I heard about it eight years ago was something I just couldn’t pass up. Specifically, I’d like to thank Anne Marie Walker, James DeWolf, Mark Powers, Melissa Maldonado, and Fabio Claudio Ferracchiati for their assistance, guidance, and editing prowess—they made the book far better than it would have been if I did it on my own.

Thanks also to Magenic, especially Greg Frankenfield and Paul Fridman, for creating and growing a great place to work. I’ve been with Magenic for 15 years, and I feel fortunate to work for a dynamic and innovative company where I fit in. Here’s to another 15 (or more!) years. I’d also like to thank Jeff Ferguson for providing a couple of figures for me that are used in the book.

Finally, I’d like to thank my family for their support and encouragement: my wife Liz and my sons Hayden and Ryan. I am grateful to have found someone like Liz and that we’ve been able to have two awesome sons.

Contents

  1. Chapter 1:​ An Overview of the Compiler API
    1. From Closed to Open
      1. What Do Compilers Do?​
      2. Compilers as a Closed Box
      3. Compilers as an Open Box
    2. Compiling Code
      1. Referencing Assemblies
      2. Building Code
    3. Creating Code Using Trees
      1. Visualizing Trees
      2. Building Trees
    4. Navigating and Editing Trees
      1. Finding Content from a Node
      2. Finding Content Using Walkers
      3. Semantic Models
      4. Editing Trees
    5. Annotations and Formatters
      1. Using Annotations
      2. Using Formatters
    6. Conclusion
  2. Chapter 2:​ Writing Diagnostics
    1. The Need to Diagnose Compilation
    2. Designing the Diagnostic
      1. Understanding the Problem
      2. Using the Syntax Visualizer
    3. Creating a Diagnostic
      1. Using the Template
      2. Building the Diagnostic
    4. Providing Code Fixes
      1. Designing the Fix
      2. Implementing the Fix
      3. Using Syntax Trees
      4. Parsing Statements
      5. Executing the Diagnostic and Code Fix
    5. Debugging Diagnostics
      1. Unit Testing
      2. VSIX Installation
      3. Visual Studio Logging
    6. Deploying and Installing Diagnostics
      1. VSIX Packaging
      2. NuGet Packaging
    7. Conclusion
  3. Chapter 3:​ Creating Refactorings and Handling Workspaces
    1. Consistency in Structure
    2. Developing a Refactoring
      1. Understanding the Problem
      2. Creating a Refactoring Solution
      3. Building the Refactoring
      4. Executing the Refactoring
    3. Debugging Refactorings
      1. Unit Testing
      2. VSIX Installation
    4. Interacting with a Workspace
      1. What Is a Workspace?​
      2. Updating Solutions and Projects
    5. Conclusion
  4. Chapter 4:​ Using the Scripting API
    1. What Is a Scripting Language?​
      1. Orchestrating an Environment
      2. Dynamic Capabilities
    2. Using the C# REPL
      1. Loading Code in Script
    3. Making C# Interactive
      1. Referencing the Scripting NuGet Package
      2. Evaluating Scripts
      3. Analyzing Scripts
      4. State Management in Scripts
    4. Concerns with the Scripting API
      1. Scripts, Performance, and Memory Usage
      2. Scripts and Security
    5. Conclusion
  5. Chapter 5:​ The Future of the Compiler API
    1. Current Usage
      1. Generating Mocks
      2. Building Code with Code
      3. Other Compiler API-Based Tools and Frameworks
    2. Looking into C#’s Future
      1. A Quick Story About Property Change Notifications
      2. Reusing Common Implementations
    3. Conclusion
  6. Index

About the Author

About the Author

A395045_1_En_BookFrontmatter_Figb_HTML.jpg

Jason Bock is a Practice Lead for Magenic ( http://www.magenic.com ) and a Microsoft MVP (C#). He has 20 years of experience working on a number of business applications using a diverse set of frameworks and languages such as C#, .NET, and JavaScript. He is the author of Metaprogramming in .NET, Applied .NET Attributes , and CIL Programming: Under the Hood of .NET . He has written numerous articles on software development issues and has presented at a number of conferences and user groups. He is a leader of the Twin Cities Code Camp ( http://www.twincitiescodecamp.com ). Jason holds a Master’s degree in electrical engineering from Marquette University. Visit his website at http://www.jasonbock.net .

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.6.114